title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Pafy - Getting Watch URL for Each Item of Playlist - GeeksforGeeks
20 Jul, 2020 In this article we will see how we can get the watch URLfrom playlist items in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. A playlist in YouTube is a list, or group, of videos that plays in order, one video after the other. Watch URL is basically youtube actual URL for each item i.e each playlist video. We can get the playlist from youtube in pafy with the help of get_playlist method, below is the command given to do this pafy.get_playlist(url) The playlist url should exist on youtube as it get the information of those videos which are present on the youtube. YouTube is an American online video-sharing platform. Steps to get the playlist ID1. Import the pafy module2. Get the playlist with the help of URL of playlist3. Return play list work as dictionary so use ‘items’ as key with the return playlist4. Store the result in variable and from the items select the single item5. With the single item use ‘pafy’ key with it6. Use watchv_url attribute with this pafy object to get the url In order to do this we use watchv_url attribute with the playlist item’s pafy object Syntax : playlist_pafy.watchv_url Argument : It takes no argument Return : It returns string Below is the implementation # importing pafyimport pafy # url of playlisturl = "https://www.youtube.com / playlist?list = PLqM7alHXFySGqCvcwfqqMrteqWukz9ZoE" # getting playlistplaylist = pafy.get_playlist(url) # getting playlist itemsitems = playlist["items"] # selecting single itemitem = items[1] # getting pafy objecti_pafy = item['pafy'] # getting watch urly_url = i_pafy.watchv_url # printing urlprint(y_url) Output : http://www.youtube.com/watch?v=AfxHGNRtFac Another example # importing pafyimport pafy # url of playlisturl = "https://www.youtube.com / playlist?list = PLqM7alHXFySE71A2bQdYp37vYr0aReknt" # getting playlistplaylist = pafy.get_playlist(url) # getting playlist itemsitems = playlist["items"] # selecting single itemitem = items[1] # getting pafy objecti_pafy = item['pafy'] # getting watch urly_url = i_pafy.watchv_url # printing urlprint(y_url) Output : http://www.youtube.com/watch?v=WdgAKCnWnwA Python-Pafy 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 ? Selecting rows in pandas DataFrame based on conditions 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 Defaultdict in Python Python OOPs Concepts Python | os.path.join() method Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n20 Jul, 2020" }, { "code": null, "e": 24719, "s": 24292, "text": "In this article we will see how we can get the watch URLfrom playlist items in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. A playlist in YouTube is a list, or group, of videos that plays in order, one video after the other. Watch URL is basically youtube actual URL for each item i.e each playlist video." }, { "code": null, "e": 24840, "s": 24719, "text": "We can get the playlist from youtube in pafy with the help of get_playlist method, below is the command given to do this" }, { "code": null, "e": 24864, "s": 24840, "text": " pafy.get_playlist(url)" }, { "code": null, "e": 25035, "s": 24864, "text": "The playlist url should exist on youtube as it get the information of those videos which are present on the youtube. YouTube is an American online video-sharing platform." }, { "code": null, "e": 25409, "s": 25035, "text": "Steps to get the playlist ID1. Import the pafy module2. Get the playlist with the help of URL of playlist3. Return play list work as dictionary so use ‘items’ as key with the return playlist4. Store the result in variable and from the items select the single item5. With the single item use ‘pafy’ key with it6. Use watchv_url attribute with this pafy object to get the url" }, { "code": null, "e": 25494, "s": 25409, "text": "In order to do this we use watchv_url attribute with the playlist item’s pafy object" }, { "code": null, "e": 25528, "s": 25494, "text": "Syntax : playlist_pafy.watchv_url" }, { "code": null, "e": 25560, "s": 25528, "text": "Argument : It takes no argument" }, { "code": null, "e": 25587, "s": 25560, "text": "Return : It returns string" }, { "code": null, "e": 25615, "s": 25587, "text": "Below is the implementation" }, { "code": "# importing pafyimport pafy # url of playlisturl = \"https://www.youtube.com / playlist?list = PLqM7alHXFySGqCvcwfqqMrteqWukz9ZoE\" # getting playlistplaylist = pafy.get_playlist(url) # getting playlist itemsitems = playlist[\"items\"] # selecting single itemitem = items[1] # getting pafy objecti_pafy = item['pafy'] # getting watch urly_url = i_pafy.watchv_url # printing urlprint(y_url)", "e": 26015, "s": 25615, "text": null }, { "code": null, "e": 26024, "s": 26015, "text": "Output :" }, { "code": null, "e": 26067, "s": 26024, "text": "http://www.youtube.com/watch?v=AfxHGNRtFac" }, { "code": null, "e": 26083, "s": 26067, "text": "Another example" }, { "code": "# importing pafyimport pafy # url of playlisturl = \"https://www.youtube.com / playlist?list = PLqM7alHXFySE71A2bQdYp37vYr0aReknt\" # getting playlistplaylist = pafy.get_playlist(url) # getting playlist itemsitems = playlist[\"items\"] # selecting single itemitem = items[1] # getting pafy objecti_pafy = item['pafy'] # getting watch urly_url = i_pafy.watchv_url # printing urlprint(y_url)", "e": 26491, "s": 26083, "text": null }, { "code": null, "e": 26500, "s": 26491, "text": "Output :" }, { "code": null, "e": 26543, "s": 26500, "text": "http://www.youtube.com/watch?v=WdgAKCnWnwA" }, { "code": null, "e": 26555, "s": 26543, "text": "Python-Pafy" }, { "code": null, "e": 26562, "s": 26555, "text": "Python" }, { "code": null, "e": 26660, "s": 26562, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26669, "s": 26660, "text": "Comments" }, { "code": null, "e": 26682, "s": 26669, "text": "Old Comments" }, { "code": null, "e": 26714, "s": 26682, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26769, "s": 26714, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26825, "s": 26769, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26867, "s": 26825, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26909, "s": 26867, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26948, "s": 26909, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26970, "s": 26948, "text": "Defaultdict in Python" }, { "code": null, "e": 26991, "s": 26970, "text": "Python OOPs Concepts" }, { "code": null, "e": 27022, "s": 26991, "text": "Python | os.path.join() method" } ]
Assembly - Conditions
Conditional execution in assembly language is accomplished by several looping and branching instructions. These instructions can change the flow of control in a program. Conditional execution is observed in two scenarios − Unconditional jump This is performed by the JMP instruction. Conditional execution often involves a transfer of control to the address of an instruction that does not follow the currently executing instruction. Transfer of control may be forward, to execute a new set of instructions or backward, to re-execute the same steps. Conditional jump This is performed by a set of jump instructions j<condition> depending upon the condition. The conditional instructions transfer the control by breaking the sequential flow and they do it by changing the offset value in IP. Let us discuss the CMP instruction before discussing the conditional instructions. The CMP instruction compares two operands. It is generally used in conditional execution. This instruction basically subtracts one operand from the other for comparing whether the operands are equal or not. It does not disturb the destination or source operands. It is used along with the conditional jump instruction for decision making. CMP destination, source CMP compares two numeric data fields. The destination operand could be either in register or in memory. The source operand could be a constant (immediate) data, register or memory. CMP DX, 00 ; Compare the DX value with zero JE L7 ; If yes, then jump to label L7 . . L7: ... CMP is often used for comparing whether a counter value has reached the number of times a loop needs to be run. Consider the following typical condition − INC EDX CMP EDX, 10 ; Compares whether the counter has reached 10 JLE LP1 ; If it is less than or equal to 10, then jump to LP1 As mentioned earlier, this is performed by the JMP instruction. Conditional execution often involves a transfer of control to the address of an instruction that does not follow the currently executing instruction. Transfer of control may be forward, to execute a new set of instructions or backward, to re-execute the same steps. The JMP instruction provides a label name where the flow of control is transferred immediately. The syntax of the JMP instruction is − JMP label The following code snippet illustrates the JMP instruction − MOV AX, 00 ; Initializing AX to 0 MOV BX, 00 ; Initializing BX to 0 MOV CX, 01 ; Initializing CX to 1 L20: ADD AX, 01 ; Increment AX ADD BX, AX ; Add AX to BX SHL CX, 1 ; shift left CX, this in turn doubles the CX value JMP L20 ; repeats the statements If some specified condition is satisfied in conditional jump, the control flow is transferred to a target instruction. There are numerous conditional jump instructions depending upon the condition and data. Following are the conditional jump instructions used on signed data used for arithmetic operations − Following are the conditional jump instructions used on unsigned data used for logical operations − The following conditional jump instructions have special uses and check the value of flags − The syntax for the J<condition> set of instructions − Example, CMP AL, BL JE EQUAL CMP AL, BH JE EQUAL CMP AL, CL JE EQUAL NON_EQUAL: ... EQUAL: ... The following program displays the largest of three variables. The variables are double-digit variables. The three variables num1, num2 and num3 have values 47, 22 and 31, respectively − section .text global _start ;must be declared for using gcc _start: ;tell linker entry point mov ecx, [num1] cmp ecx, [num2] jg check_third_num mov ecx, [num2] check_third_num: cmp ecx, [num3] jg _exit mov ecx, [num3] _exit: mov [largest], ecx mov ecx,msg mov edx, len mov ebx,1 ;file descriptor (stdout) mov eax,4 ;system call number (sys_write) int 0x80 ;call kernel mov ecx,largest mov edx, 2 mov ebx,1 ;file descriptor (stdout) mov eax,4 ;system call number (sys_write) int 0x80 ;call kernel mov eax, 1 int 80h section .data msg db "The largest digit is: ", 0xA,0xD len equ $- msg num1 dd '47' num2 dd '22' num3 dd '31' segment .bss largest resb 2 When the above code is compiled and executed, it produces the following result − The largest digit is: 47 46 Lectures 2 hours Frahaan Hussain 23 Lectures 12 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2308, "s": 2085, "text": "Conditional execution in assembly language is accomplished by several looping and branching instructions. These instructions can change the flow of control in a program. Conditional execution is observed in two scenarios −" }, { "code": null, "e": 2327, "s": 2308, "text": "Unconditional jump" }, { "code": null, "e": 2635, "s": 2327, "text": "This is performed by the JMP instruction. Conditional execution often involves a transfer of control to the address of an instruction that does not follow the currently executing instruction. Transfer of control may be forward, to execute a new set of instructions or backward, to re-execute the same steps." }, { "code": null, "e": 2652, "s": 2635, "text": "Conditional jump" }, { "code": null, "e": 2876, "s": 2652, "text": "This is performed by a set of jump instructions j<condition> depending upon the condition. The conditional instructions transfer the control by breaking the sequential flow and they do it by changing the offset value in IP." }, { "code": null, "e": 2959, "s": 2876, "text": "Let us discuss the CMP instruction before discussing the conditional instructions." }, { "code": null, "e": 3298, "s": 2959, "text": "The CMP instruction compares two operands. It is generally used in conditional execution. This instruction basically subtracts one operand from the other for comparing whether the operands are equal or not. It does not disturb the destination or source operands. It is used along with the conditional jump instruction for decision making." }, { "code": null, "e": 3323, "s": 3298, "text": "CMP destination, source\n" }, { "code": null, "e": 3504, "s": 3323, "text": "CMP compares two numeric data fields. The destination operand could be either in register or in memory. The source operand could be a constant (immediate) data, register or memory." }, { "code": null, "e": 3607, "s": 3504, "text": "CMP DX,\t00 ; Compare the DX value with zero\nJE L7 ; If yes, then jump to label L7\n.\n.\nL7: ... " }, { "code": null, "e": 3762, "s": 3607, "text": "CMP is often used for comparing whether a counter value has reached the number of times a loop needs to be run. Consider the following typical condition −" }, { "code": null, "e": 3894, "s": 3762, "text": "INC\tEDX\nCMP\tEDX, 10\t; Compares whether the counter has reached 10\nJLE\tLP1 ; If it is less than or equal to 10, then jump to LP1" }, { "code": null, "e": 4224, "s": 3894, "text": "As mentioned earlier, this is performed by the JMP instruction. Conditional execution often involves a transfer of control to the address of an instruction that does not follow the currently executing instruction. Transfer of control may be forward, to execute a new set of instructions or backward, to re-execute the same steps." }, { "code": null, "e": 4359, "s": 4224, "text": "The JMP instruction provides a label name where the flow of control is transferred immediately. The syntax of the JMP instruction is −" }, { "code": null, "e": 4370, "s": 4359, "text": "JMP\tlabel\n" }, { "code": null, "e": 4431, "s": 4370, "text": "The following code snippet illustrates the JMP instruction −" }, { "code": null, "e": 4716, "s": 4431, "text": "MOV AX, 00 ; Initializing AX to 0\nMOV BX, 00 ; Initializing BX to 0\nMOV CX, 01 ; Initializing CX to 1\nL20:\nADD AX, 01 ; Increment AX\nADD BX, AX ; Add AX to BX\nSHL CX, 1 ; shift left CX, this in turn doubles the CX value\nJMP L20 ; repeats the statements" }, { "code": null, "e": 4923, "s": 4716, "text": "If some specified condition is satisfied in conditional jump, the control flow is transferred to a target instruction. There are numerous conditional jump instructions depending upon the condition and data." }, { "code": null, "e": 5024, "s": 4923, "text": "Following are the conditional jump instructions used on signed data used for arithmetic operations −" }, { "code": null, "e": 5124, "s": 5024, "text": "Following are the conditional jump instructions used on unsigned data used for logical operations −" }, { "code": null, "e": 5217, "s": 5124, "text": "The following conditional jump instructions have special uses and check the value of flags −" }, { "code": null, "e": 5271, "s": 5217, "text": "The syntax for the J<condition> set of instructions −" }, { "code": null, "e": 5280, "s": 5271, "text": "Example," }, { "code": null, "e": 5366, "s": 5280, "text": "CMP\tAL, BL\nJE\tEQUAL\nCMP\tAL, BH\nJE\tEQUAL\nCMP\tAL, CL\nJE\tEQUAL\nNON_EQUAL: ...\nEQUAL: ..." }, { "code": null, "e": 5553, "s": 5366, "text": "The following program displays the largest of three variables. The variables are double-digit variables. The three variables num1, num2 and num3 have values 47, 22 and 31, respectively −" }, { "code": null, "e": 6386, "s": 5553, "text": "section\t.text\n global _start ;must be declared for using gcc\n\n_start:\t ;tell linker entry point\n mov ecx, [num1]\n cmp ecx, [num2]\n jg check_third_num\n mov ecx, [num2]\n \n\tcheck_third_num:\n\n cmp ecx, [num3]\n jg _exit\n mov ecx, [num3]\n \n\t_exit:\n \n mov [largest], ecx\n mov ecx,msg\n mov edx, len\n mov ebx,1\t;file descriptor (stdout)\n mov eax,4\t;system call number (sys_write)\n int 0x80\t;call kernel\n\t\n mov ecx,largest\n mov edx, 2\n mov ebx,1\t;file descriptor (stdout)\n mov eax,4\t;system call number (sys_write)\n int 0x80\t;call kernel\n \n mov eax, 1\n int 80h\n\nsection\t.data\n \n msg db \"The largest digit is: \", 0xA,0xD \n len equ $- msg \n num1 dd '47'\n num2 dd '22'\n num3 dd '31'\n\nsegment .bss\n largest resb 2 " }, { "code": null, "e": 6467, "s": 6386, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 6494, "s": 6467, "text": "The largest digit is: \n47\n" }, { "code": null, "e": 6527, "s": 6494, "text": "\n 46 Lectures \n 2 hours \n" }, { "code": null, "e": 6544, "s": 6527, "text": " Frahaan Hussain" }, { "code": null, "e": 6578, "s": 6544, "text": "\n 23 Lectures \n 12 hours \n" }, { "code": null, "e": 6586, "s": 6578, "text": " Uplatz" }, { "code": null, "e": 6593, "s": 6586, "text": " Print" }, { "code": null, "e": 6604, "s": 6593, "text": " Add Notes" } ]
NumPy Array Copy vs View
The main difference between a copy and a view of an array is that the copy is a new array, and the view is just a view of the original array. The copy owns the data and any changes made to the copy will not affect original array, and any changes made to the original array will not affect the copy. The view does not own the data and any changes made to the view will affect the original array, and any changes made to the original array will affect the view. Make a copy, change the original array, and display both arrays: The copy SHOULD NOT be affected by the changes made to the original array. Make a view, change the original array, and display both arrays: The view SHOULD be affected by the changes made to the original array. Make a view, change the view, and display both arrays: The original array SHOULD be affected by the changes made to the view. As mentioned above, copies owns the data, and views does not own the data, but how can we check this? Every NumPy array has the attribute base that returns None if the array owns the data. Otherwise, the base attribute refers to the original object. Print the value of the base attribute to check if an array owns it's data or not: The copy returns None.The view returns the original array. Use the correct method to make a copy of the array. arr = np.array([1, 2, 3, 4, 5]) x = arr. Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 142, "s": 0, "text": "The main difference between a copy and a view of an array is that\nthe copy is a new array, and the view is just a view of the original array." }, { "code": null, "e": 301, "s": 142, "text": "The copy owns the data and any changes made to the copy will not \naffect original array, and any changes made to the original array will not \naffect the copy." }, { "code": null, "e": 464, "s": 301, "text": "The view does not own the data and any changes made to the view will \naffect the original array, and any changes made to the original array will \naffect the view." }, { "code": null, "e": 529, "s": 464, "text": "Make a copy, change the original array, and display both arrays:" }, { "code": null, "e": 604, "s": 529, "text": "The copy SHOULD NOT be affected by the changes made to the original array." }, { "code": null, "e": 669, "s": 604, "text": "Make a view, change the original array, and display both arrays:" }, { "code": null, "e": 740, "s": 669, "text": "The view SHOULD be affected by the changes made to the original array." }, { "code": null, "e": 795, "s": 740, "text": "Make a view, change the view, and display both arrays:" }, { "code": null, "e": 866, "s": 795, "text": "The original array SHOULD be affected by the changes made to the view." }, { "code": null, "e": 969, "s": 866, "text": "As mentioned above, copies owns the data, and views does not own \nthe data, but how can we check this?" }, { "code": null, "e": 1057, "s": 969, "text": "Every NumPy array has the attribute base that \nreturns None if the array owns the data." }, { "code": null, "e": 1121, "s": 1057, "text": "Otherwise, the base attribute refers to the original object.\n\n" }, { "code": null, "e": 1204, "s": 1121, "text": "Print the value of the base attribute to check if an array owns it's data or \nnot:" }, { "code": null, "e": 1263, "s": 1204, "text": "The copy returns None.The view returns the original array." }, { "code": null, "e": 1315, "s": 1263, "text": "Use the correct method to make a copy of the array." }, { "code": null, "e": 1358, "s": 1315, "text": "arr = np.array([1, 2, 3, 4, 5])\n\nx = arr.\n" }, { "code": null, "e": 1377, "s": 1358, "text": "Start the Exercise" }, { "code": null, "e": 1410, "s": 1377, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1452, "s": 1410, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1559, "s": 1452, "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": 1578, "s": 1559, "text": "[email protected]" } ]
C Program for Counting Sort - GeeksforGeeks
10 Oct, 2021 Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence. C // C Program for counting sort#include <stdio.h>#include <string.h>#define RANGE 255 // The main function that sort the given string arr[] in// alphabetical ordervoid countSort(char arr[]){ // The output character array that will have sorted arr char output[strlen(arr)]; // Create a count array to store count of individual // characters and initialize count array as 0 int count[RANGE + 1], i; memset(count, 0, sizeof(count)); // Store count of each character for(i = 0; arr[i]; ++i) ++count[arr[i]]; // Change count[i] so that count[i] now contains actual // position of this character in output array for (i = 1; i <= RANGE; ++i) count[i] += count[i-1]; // Build the output character array for (i = 0; arr[i]; ++i) { output[count[arr[i]]-1] = arr[i]; --count[arr[i]]; } // Copy the output array to arr, so that arr now // contains sorted characters for (i = 0; arr[i]; ++i) arr[i] = output[i];} // Driver program to test above functionint main(){ char arr[] = "geeksforgeeks";//"applepp"; countSort(arr); printf("Sorted character array is %sn", arr); return 0;} Sorted character array is eeeefggkkorssn Please refer complete article on Counting Sort for more details! simmytarika5 surinderdawra388 counting-sort C Programs Sorting Sorting 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 Header files in C/C++ and its uses How to Append a Character to a String in C Program to find Prime Numbers Between given Interval time() function in C Bubble Sort Selection Sort std::sort() in C++ STL Time Complexities of all Sorting Algorithms Merge two sorted arrays
[ { "code": null, "e": 23830, "s": 23802, "text": "\n10 Oct, 2021" }, { "code": null, "e": 24090, "s": 23830, "text": "Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence. " }, { "code": null, "e": 24092, "s": 24090, "text": "C" }, { "code": "// C Program for counting sort#include <stdio.h>#include <string.h>#define RANGE 255 // The main function that sort the given string arr[] in// alphabetical ordervoid countSort(char arr[]){ // The output character array that will have sorted arr char output[strlen(arr)]; // Create a count array to store count of individual // characters and initialize count array as 0 int count[RANGE + 1], i; memset(count, 0, sizeof(count)); // Store count of each character for(i = 0; arr[i]; ++i) ++count[arr[i]]; // Change count[i] so that count[i] now contains actual // position of this character in output array for (i = 1; i <= RANGE; ++i) count[i] += count[i-1]; // Build the output character array for (i = 0; arr[i]; ++i) { output[count[arr[i]]-1] = arr[i]; --count[arr[i]]; } // Copy the output array to arr, so that arr now // contains sorted characters for (i = 0; arr[i]; ++i) arr[i] = output[i];} // Driver program to test above functionint main(){ char arr[] = \"geeksforgeeks\";//\"applepp\"; countSort(arr); printf(\"Sorted character array is %sn\", arr); return 0;}", "e": 25266, "s": 24092, "text": null }, { "code": null, "e": 25307, "s": 25266, "text": "Sorted character array is eeeefggkkorssn" }, { "code": null, "e": 25375, "s": 25309, "text": "Please refer complete article on Counting Sort for more details! " }, { "code": null, "e": 25388, "s": 25375, "text": "simmytarika5" }, { "code": null, "e": 25405, "s": 25388, "text": "surinderdawra388" }, { "code": null, "e": 25419, "s": 25405, "text": "counting-sort" }, { "code": null, "e": 25430, "s": 25419, "text": "C Programs" }, { "code": null, "e": 25438, "s": 25430, "text": "Sorting" }, { "code": null, "e": 25446, "s": 25438, "text": "Sorting" }, { "code": null, "e": 25544, "s": 25446, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25553, "s": 25544, "text": "Comments" }, { "code": null, "e": 25566, "s": 25553, "text": "Old Comments" }, { "code": null, "e": 25607, "s": 25566, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 25642, "s": 25607, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 25685, "s": 25642, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 25738, "s": 25685, "text": "Program to find Prime Numbers Between given Interval" }, { "code": null, "e": 25759, "s": 25738, "text": "time() function in C" }, { "code": null, "e": 25771, "s": 25759, "text": "Bubble Sort" }, { "code": null, "e": 25786, "s": 25771, "text": "Selection Sort" }, { "code": null, "e": 25809, "s": 25786, "text": "std::sort() in C++ STL" }, { "code": null, "e": 25853, "s": 25809, "text": "Time Complexities of all Sorting Algorithms" } ]
C++ Program to Find Factorial of a Number using Iteration
Factorial of a non-negative integer n is the product of all the positive integers that are less than or equal to n. For example: The factorial of 6 is 720. 6! = 6 * 5 * 4 * 3 * 2 *1 6! = 720 The factorial of an integer can be found using a recursive program or an iterative program. A for loop can be used to find the factorial of a number using an iterative program. This is demonstrated as follows. Live Demo #include <iostream> using namespace std; int main() { int n = 6, fact = 1, i; for(i=1; i<=n; i++) fact = fact * i; cout<<"Factorial of "<< n <<" is "<<fact; return 0; } Factorial of 6 is 720 In the above program, the for loop runs from 1 to n. For each iteration of the loop, fact is multiplied with i. The final value of fact is the product of all numbers from 1 to n. This is demonstrated using the following code snippet. for(i=1; i<=n; i++) fact = fact * i;
[ { "code": null, "e": 1178, "s": 1062, "text": "Factorial of a non-negative integer n is the product of all the positive integers that are less than or equal to n." }, { "code": null, "e": 1218, "s": 1178, "text": "For example: The factorial of 6 is 720." }, { "code": null, "e": 1253, "s": 1218, "text": "6! = 6 * 5 * 4 * 3 * 2 *1\n6! = 720" }, { "code": null, "e": 1345, "s": 1253, "text": "The factorial of an integer can be found using a recursive program or an iterative program." }, { "code": null, "e": 1463, "s": 1345, "text": "A for loop can be used to find the factorial of a number using an iterative program. This is demonstrated as follows." }, { "code": null, "e": 1474, "s": 1463, "text": " Live Demo" }, { "code": null, "e": 1658, "s": 1474, "text": "#include <iostream>\nusing namespace std;\nint main() {\n int n = 6, fact = 1, i;\n for(i=1; i<=n; i++)\n fact = fact * i;\n cout<<\"Factorial of \"<< n <<\" is \"<<fact;\n return 0;\n}" }, { "code": null, "e": 1680, "s": 1658, "text": "Factorial of 6 is 720" }, { "code": null, "e": 1914, "s": 1680, "text": "In the above program, the for loop runs from 1 to n. For each iteration of the loop, fact is multiplied with i. The final value of fact is the product of all numbers from 1 to n. This is demonstrated using the following code snippet." }, { "code": null, "e": 1951, "s": 1914, "text": "for(i=1; i<=n; i++)\nfact = fact * i;" } ]
C program to draw a moving boat using graphics - GeeksforGeeks
26 Jun, 2021 In C graphics, the graphics.h functions are used to draw different shapes like circles, rectangles, etc, display text(any message) in a different format (different fonts and colors). By using the functions in the header graphics.h, programs, animations, and different games can also be made. In this article, we will discuss how to draw a moving boat in C using graphics. Functions Used: getmaxx(): The graphics.h header file includes the getmaxx() function, which returns the maximum X coordinate for the current graphics mode and driver. setcolor(N): The setcolor() function in the header file graphics.h is used to change the current drawing color to the new color. setlinestyle(linestyle, upattern, thickness): The setlinestyle() function in the header file graphics.h sets the style for all lines drawn by using functions like line, lineto, rectangle, drawpoly, and so on. rectangle(X1, Y1, X2, Y2): It is employed in the creation of a rectangle. The rectangle must be drawn using the coordinates of the left top and right bottom corners. The X-coordinate and Y-coordinate of the top left corner are X1 and Y1 and the X-coordinate and Y-coordinate of the bottom right corner are X2 and Y2 respectively. floodfill(pattern, color): The function is used to fill a confined space. To fill the area, the current fill pattern and color are used. Approach: Follow the steps below to generate the moving boat: Pass three arguments to the initgraph() function to initialize the graphics driver and graphics mode. Initialize the boat’s position by considering two variables X and Y. Create a river/sea on which the boat will move by drawing a rectangle and fill it with light blue paint to make it look like a river/sea. Choose the coordinates so that the boat is just above the river/sea. Change the boat’s position using a loop continuously so that it appears to be moving in the river. Below is the implementation of the above approach: C // C program to draw the moving boat// using c graphics #include <conio.h>#include <dos.h>#include <graphics.h>#include <stdio.h> // Driver Codeint main(){ // Initialize graphic driver int gdriver = DETECT, gmode, err; int i = 0, j, x, y, x1, y1, x2, y2; // Start graphics mode by passing // three arguments to initgraph() // &gdriver is the address of the // gdriver variable. // &gmode is the address of gmode // "C:Turboc3BGI" is the directory // path where BGI files are stored initgraph(&gdriver, &gmode, "C:\\Turboc3\\BGI"); err = graphresult(); if (err != grOk) { printf("Graphics Error: %s\n", grapherrormsg(err)); return 0; } j = 0; // Initialize position for boat x = 50, y = getmaxy() / 2 + 140; while (x + 60 < getmaxx() && (!kbhit())) { // Set the positions for rain x1 = 10, i = y1 = 0; x2 = 0, y2 = 50; // Clears graphic screen cleardevice(); // Set the color of river/sea setcolor(LIGHTBLUE); setlinestyle(SOLID_LINE, 1, 1); setfillstyle(SOLID_FILL, LIGHTBLUE); // Draw the river/sea rectangle(0, getmaxy() / 2 + 150, getmaxx(), getmaxy()); floodfill(getmaxx() - 10, getmaxy() - 10, LIGHTBLUE); // Rain drops setlinestyle(DASHED_LINE, 1, 2); while (i < 700) { line(x1, y1, x2, y2); x1 = x1 + 20; y2 = y2 + 50; i++; } // Drawing the boat setlinestyle(SOLID_LINE, 1, 2); setcolor(BROWN); setfillstyle(SOLID_FILL, BROWN); sector(x, y, 180, 360, 50, 10); setcolor(DARKGRAY); setlinestyle(SOLID_LINE, 1, 3); // Leg and body of stick man line(x + 40, y - 15, x + 40, y - 40); line(x + 40, y - 15, x + 45, y - 10); line(x + 45, y - 10, x + 45, y); line(x + 40, y - 15, x + 37, y); // Head and hand of stick man circle(x + 40, y - 45, 5); line(x + 40, y - 35, x + 50, y - 30); line(x + 40, y - 35, x + 35, y - 32); line(x + 35, y - 32, x + 45, y - 25); line(x + 60, y - 45, x + 27, y + 10); // Moving the position of // boat and stick man x++; setcolor(LIGHTBLUE); delay(250); // Clears the graphic device cleardevice(); // Drawing sea/river setlinestyle(SOLID_LINE, 1, 1); setfillstyle(SOLID_FILL, LIGHTBLUE); rectangle(0, getmaxy() / 2 + 150, getmaxx(), getmaxy()); floodfill(getmaxx() - 10, getmaxy() - 10, LIGHTBLUE); // Rain drops setlinestyle(DASHED_LINE, 1, 2); x1 = 10, i = y1 = 0; x2 = 0, y2 = 70; while (i < 700) { line(x1, y1, x2, y2); x1 = x1 + 30; y2 = y2 + 60; i++; } // Drawing the boat setlinestyle(SOLID_LINE, 1, 1); setcolor(BROWN); setfillstyle(SOLID_FILL, BROWN); sector(x, y, 180, 360, 50, 10); // Body and leg of stic man setcolor(DARKGRAY); setlinestyle(SOLID_LINE, 1, 3); line(x + 40, y - 15, x + 40, y - 40); line(x + 40, y - 15, x + 45, y - 10); line(x + 45, y - 10, x + 45, y); line(x + 40, y - 15, x + 37, y); // Head hands of stick man circle(x + 40, y - 45, 5); line(x + 40, y - 35, x + 52, y - 30); line(x + 40, y - 35, x + 37, y - 32); line(x + 37, y - 32, x + 49, y - 25); line(x + 60, y - 45, x + 27, y + 10); // Forwarding the position of // the boat x++; // Sleep for 250 milliseconds delay(250); // Clears the graphic device cleardevice(); j++; } getch(); // Deallocate memory allocated // for graphic screen closegraph(); return 0;} Output: c-graphics computer-graphics C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ 'this' pointer in C++ Multithreading in C Arrow operator -> in C/C++ with Examples Strings in C Arrow operator -> in C/C++ with Examples Header files in C/C++ and its uses C Program to read contents of Whole File UDP Server-Client implementation in C
[ { "code": null, "e": 25453, "s": 25425, "text": "\n26 Jun, 2021" }, { "code": null, "e": 25825, "s": 25453, "text": "In C graphics, the graphics.h functions are used to draw different shapes like circles, rectangles, etc, display text(any message) in a different format (different fonts and colors). By using the functions in the header graphics.h, programs, animations, and different games can also be made. In this article, we will discuss how to draw a moving boat in C using graphics." }, { "code": null, "e": 25841, "s": 25825, "text": "Functions Used:" }, { "code": null, "e": 25993, "s": 25841, "text": "getmaxx(): The graphics.h header file includes the getmaxx() function, which returns the maximum X coordinate for the current graphics mode and driver." }, { "code": null, "e": 26122, "s": 25993, "text": "setcolor(N): The setcolor() function in the header file graphics.h is used to change the current drawing color to the new color." }, { "code": null, "e": 26331, "s": 26122, "text": "setlinestyle(linestyle, upattern, thickness): The setlinestyle() function in the header file graphics.h sets the style for all lines drawn by using functions like line, lineto, rectangle, drawpoly, and so on." }, { "code": null, "e": 26661, "s": 26331, "text": "rectangle(X1, Y1, X2, Y2): It is employed in the creation of a rectangle. The rectangle must be drawn using the coordinates of the left top and right bottom corners. The X-coordinate and Y-coordinate of the top left corner are X1 and Y1 and the X-coordinate and Y-coordinate of the bottom right corner are X2 and Y2 respectively." }, { "code": null, "e": 26798, "s": 26661, "text": "floodfill(pattern, color): The function is used to fill a confined space. To fill the area, the current fill pattern and color are used." }, { "code": null, "e": 26860, "s": 26798, "text": "Approach: Follow the steps below to generate the moving boat:" }, { "code": null, "e": 26962, "s": 26860, "text": "Pass three arguments to the initgraph() function to initialize the graphics driver and graphics mode." }, { "code": null, "e": 27031, "s": 26962, "text": "Initialize the boat’s position by considering two variables X and Y." }, { "code": null, "e": 27169, "s": 27031, "text": "Create a river/sea on which the boat will move by drawing a rectangle and fill it with light blue paint to make it look like a river/sea." }, { "code": null, "e": 27238, "s": 27169, "text": "Choose the coordinates so that the boat is just above the river/sea." }, { "code": null, "e": 27337, "s": 27238, "text": "Change the boat’s position using a loop continuously so that it appears to be moving in the river." }, { "code": null, "e": 27388, "s": 27337, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27390, "s": 27388, "text": "C" }, { "code": "// C program to draw the moving boat// using c graphics #include <conio.h>#include <dos.h>#include <graphics.h>#include <stdio.h> // Driver Codeint main(){ // Initialize graphic driver int gdriver = DETECT, gmode, err; int i = 0, j, x, y, x1, y1, x2, y2; // Start graphics mode by passing // three arguments to initgraph() // &gdriver is the address of the // gdriver variable. // &gmode is the address of gmode // \"C:Turboc3BGI\" is the directory // path where BGI files are stored initgraph(&gdriver, &gmode, \"C:\\\\Turboc3\\\\BGI\"); err = graphresult(); if (err != grOk) { printf(\"Graphics Error: %s\\n\", grapherrormsg(err)); return 0; } j = 0; // Initialize position for boat x = 50, y = getmaxy() / 2 + 140; while (x + 60 < getmaxx() && (!kbhit())) { // Set the positions for rain x1 = 10, i = y1 = 0; x2 = 0, y2 = 50; // Clears graphic screen cleardevice(); // Set the color of river/sea setcolor(LIGHTBLUE); setlinestyle(SOLID_LINE, 1, 1); setfillstyle(SOLID_FILL, LIGHTBLUE); // Draw the river/sea rectangle(0, getmaxy() / 2 + 150, getmaxx(), getmaxy()); floodfill(getmaxx() - 10, getmaxy() - 10, LIGHTBLUE); // Rain drops setlinestyle(DASHED_LINE, 1, 2); while (i < 700) { line(x1, y1, x2, y2); x1 = x1 + 20; y2 = y2 + 50; i++; } // Drawing the boat setlinestyle(SOLID_LINE, 1, 2); setcolor(BROWN); setfillstyle(SOLID_FILL, BROWN); sector(x, y, 180, 360, 50, 10); setcolor(DARKGRAY); setlinestyle(SOLID_LINE, 1, 3); // Leg and body of stick man line(x + 40, y - 15, x + 40, y - 40); line(x + 40, y - 15, x + 45, y - 10); line(x + 45, y - 10, x + 45, y); line(x + 40, y - 15, x + 37, y); // Head and hand of stick man circle(x + 40, y - 45, 5); line(x + 40, y - 35, x + 50, y - 30); line(x + 40, y - 35, x + 35, y - 32); line(x + 35, y - 32, x + 45, y - 25); line(x + 60, y - 45, x + 27, y + 10); // Moving the position of // boat and stick man x++; setcolor(LIGHTBLUE); delay(250); // Clears the graphic device cleardevice(); // Drawing sea/river setlinestyle(SOLID_LINE, 1, 1); setfillstyle(SOLID_FILL, LIGHTBLUE); rectangle(0, getmaxy() / 2 + 150, getmaxx(), getmaxy()); floodfill(getmaxx() - 10, getmaxy() - 10, LIGHTBLUE); // Rain drops setlinestyle(DASHED_LINE, 1, 2); x1 = 10, i = y1 = 0; x2 = 0, y2 = 70; while (i < 700) { line(x1, y1, x2, y2); x1 = x1 + 30; y2 = y2 + 60; i++; } // Drawing the boat setlinestyle(SOLID_LINE, 1, 1); setcolor(BROWN); setfillstyle(SOLID_FILL, BROWN); sector(x, y, 180, 360, 50, 10); // Body and leg of stic man setcolor(DARKGRAY); setlinestyle(SOLID_LINE, 1, 3); line(x + 40, y - 15, x + 40, y - 40); line(x + 40, y - 15, x + 45, y - 10); line(x + 45, y - 10, x + 45, y); line(x + 40, y - 15, x + 37, y); // Head hands of stick man circle(x + 40, y - 45, 5); line(x + 40, y - 35, x + 52, y - 30); line(x + 40, y - 35, x + 37, y - 32); line(x + 37, y - 32, x + 49, y - 25); line(x + 60, y - 45, x + 27, y + 10); // Forwarding the position of // the boat x++; // Sleep for 250 milliseconds delay(250); // Clears the graphic device cleardevice(); j++; } getch(); // Deallocate memory allocated // for graphic screen closegraph(); return 0;}", "e": 31442, "s": 27390, "text": null }, { "code": null, "e": 31450, "s": 31442, "text": "Output:" }, { "code": null, "e": 31461, "s": 31450, "text": "c-graphics" }, { "code": null, "e": 31479, "s": 31461, "text": "computer-graphics" }, { "code": null, "e": 31490, "s": 31479, "text": "C Language" }, { "code": null, "e": 31501, "s": 31490, "text": "C Programs" }, { "code": null, "e": 31599, "s": 31501, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31637, "s": 31599, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 31663, "s": 31637, "text": "Exception Handling in C++" }, { "code": null, "e": 31685, "s": 31663, "text": "'this' pointer in C++" }, { "code": null, "e": 31705, "s": 31685, "text": "Multithreading in C" }, { "code": null, "e": 31746, "s": 31705, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 31759, "s": 31746, "text": "Strings in C" }, { "code": null, "e": 31800, "s": 31759, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 31835, "s": 31800, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 31876, "s": 31835, "text": "C Program to read contents of Whole File" } ]
multiset count() function in C++ STL
06 Oct, 2021 The multiset::count() function is a built-in function in C++ STL that searches for a specific element in the multiset container and returns the number of occurrences of that element. Syntax: multiset_name.count(val) Parameters: The function accepts a single parameter val which specifies the element to be searched in the multiset container. Return Value: The function returns the count of elements which is equal to val in the multiset container. Below programs illustrates the multiset::count() function: Program 1: C++ // C++ program to demonstrate the// multiset::count() function#include <bits/stdc++.h>using namespace std;int main(){ int arr[] = { 15, 10, 15, 11, 10, 18, 18, 20, 20 }; // initializes the set from an array multiset<int> s(arr, arr + 9); cout << "15 occurs " << s.count(15) << " times in container"; return 0;} 15 occurs 2 times in container Program 2: C++ // C++ program to demonstrate the// multiset::count() function#include <bits/stdc++.h>using namespace std;int main(){ int arr[] = { 15, 10, 15, 11, 10, 18, 18, 18, 18 }; // initializes the set from an array multiset<int> s(arr, arr + 9); cout << "18 occurs " << s.count(18) << " times in container"; return 0;} 18 occurs 4 times in container The time complexity of the multiset::count() function is O(K + log(N)), where K is the total count of integers of the value passed. arorakashish0911 kartikmodi CPP-Functions cpp-multiset STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Oct, 2021" }, { "code": null, "e": 212, "s": 28, "text": "The multiset::count() function is a built-in function in C++ STL that searches for a specific element in the multiset container and returns the number of occurrences of that element. " }, { "code": null, "e": 222, "s": 212, "text": "Syntax: " }, { "code": null, "e": 247, "s": 222, "text": "multiset_name.count(val)" }, { "code": null, "e": 374, "s": 247, "text": "Parameters: The function accepts a single parameter val which specifies the element to be searched in the multiset container. " }, { "code": null, "e": 481, "s": 374, "text": "Return Value: The function returns the count of elements which is equal to val in the multiset container. " }, { "code": null, "e": 541, "s": 481, "text": "Below programs illustrates the multiset::count() function: " }, { "code": null, "e": 554, "s": 541, "text": "Program 1: " }, { "code": null, "e": 558, "s": 554, "text": "C++" }, { "code": "// C++ program to demonstrate the// multiset::count() function#include <bits/stdc++.h>using namespace std;int main(){ int arr[] = { 15, 10, 15, 11, 10, 18, 18, 20, 20 }; // initializes the set from an array multiset<int> s(arr, arr + 9); cout << \"15 occurs \" << s.count(15) << \" times in container\"; return 0;}", "e": 896, "s": 558, "text": null }, { "code": null, "e": 927, "s": 896, "text": "15 occurs 2 times in container" }, { "code": null, "e": 941, "s": 929, "text": "Program 2: " }, { "code": null, "e": 945, "s": 941, "text": "C++" }, { "code": "// C++ program to demonstrate the// multiset::count() function#include <bits/stdc++.h>using namespace std;int main(){ int arr[] = { 15, 10, 15, 11, 10, 18, 18, 18, 18 }; // initializes the set from an array multiset<int> s(arr, arr + 9); cout << \"18 occurs \" << s.count(18) << \" times in container\"; return 0;}", "e": 1283, "s": 945, "text": null }, { "code": null, "e": 1314, "s": 1283, "text": "18 occurs 4 times in container" }, { "code": null, "e": 1448, "s": 1316, "text": "The time complexity of the multiset::count() function is O(K + log(N)), where K is the total count of integers of the value passed." }, { "code": null, "e": 1465, "s": 1448, "text": "arorakashish0911" }, { "code": null, "e": 1476, "s": 1465, "text": "kartikmodi" }, { "code": null, "e": 1490, "s": 1476, "text": "CPP-Functions" }, { "code": null, "e": 1503, "s": 1490, "text": "cpp-multiset" }, { "code": null, "e": 1507, "s": 1503, "text": "STL" }, { "code": null, "e": 1511, "s": 1507, "text": "C++" }, { "code": null, "e": 1515, "s": 1511, "text": "STL" }, { "code": null, "e": 1519, "s": 1515, "text": "CPP" } ]
Maximum number of leaf nodes that can be visited within the given budget
18 Aug, 2021 Given a binary tree and an integer b representing budget. The task is to find the count of maximum number of leaf nodes that can be visited under the given budget if cost of visiting a leaf node is equal to level of that leaf node. Note: Root of the tree is at level 1.Examples: Input: b = 8 10 / \ 8 15 / / \ 3 11 18 \ 13 Output: 2 For the above binary tree, leaf nodes are 3, 13 and 18 at levels 3, 4 and 3 respectively. Cost for visiting leaf node 3 is 3 Cost for visiting leaf node 13 is 4 Cost for visiting leaf node 18 is 3 Thus with given budget = 8, we can at maximum visit two leaf nodes. Input: b = 1 8 / \ 7 10 / 3 Output: 0 For the above binary tree, leaf nodes are 3 and 10 at levels 3 and 2 respectively. Cost for visiting leaf node 3 is 3 Cost for visiting leaf node 10 is 2 In given budget = 1, we can't visit any leaf node. Approach: Traverse the binary tree using level order traversal, and store the level of all the leaf nodes in a priority queue. Remove an element from the priority queue one by one, check if this value is within the budget. If Yes then subtract this value from the budget and update count = count + 1. Else, print the count of maximum leaf nodes that can be visited within the given budget. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to calculate the maximum number of leaf// nodes that can be visited within the given budget#include <bits/stdc++.h>using namespace std; // struct that represents a node of the treestruct Node { Node* left; Node* right; int data; Node(int key) { data = key; this->left = nullptr; this->right = nullptr; }}; Node* newNode(int key){ Node* temp = new Node(key); return temp;} // Priority queue to store the levels// of all the leaf nodesvector<int> pq; // Level order traversal of the binary treevoid levelOrder(Node* root){ vector<Node*> q; int len, level = 0; Node* temp; // If tree is empty if (root == nullptr) return; q.push_back(root); while (true) { len = q.size(); if (len == 0) break; level++; while (len > 0) { temp = q[0]; q.erase(q.begin()); // If left child exists if (temp->left != nullptr) q.push_back(temp->left); // If right child exists if (temp->right != nullptr) q.push_back(temp->right); // If node is a leaf node if (temp->left == nullptr && temp->right == nullptr) { pq.push_back(level); sort(pq.begin(), pq.end()); reverse(pq.begin(), pq.end()); } len--; } }} // Function to calculate the maximum number of leaf nodes// that can be visited within the given budgetint countLeafNodes(Node* root, int budget){ levelOrder(root); int val; // Variable to store the count of // number of leaf nodes possible to visit // within the given budget int count = 0; while (pq.size() != 0) { // Removing element from // min priority queue one by one val = pq[0]; pq.erase(pq.begin()); // If current val is under budget, the // node can be visited // Update the budget afterwards if (val <= budget) { count++; budget -= val; } else break; } return count;} // Driver codeint main(){ Node* root = newNode(10); root->left = newNode(8); root->right = newNode(15); root->left->left = newNode(3); root->left->left->right = newNode(13); root->right->left = newNode(11); root->right->right = newNode(18); int budget = 8; cout << countLeafNodes(root, budget); return 0;} // This code is contributed by decode2207. // Java program to calculate the maximum number of leaf// nodes that can be visited within the given budgetimport java.io.*;import java.util.*;import java.lang.*; // Class that represents a node of the treeclass Node { int data; Node left, right; // Constructor to create a new tree node Node(int key) { data = key; left = right = null; }} class GFG { // Priority queue to store the levels // of all the leaf nodes static PriorityQueue<Integer> pq; // Level order traversal of the binary tree static void levelOrder(Node root) { Queue<Node> q = new LinkedList<>(); int len, level = 0; Node temp; // If tree is empty if (root == null) return; q.add(root); while (true) { len = q.size(); if (len == 0) break; level++; while (len > 0) { temp = q.remove(); // If left child exists if (temp.left != null) q.add(temp.left); // If right child exists if (temp.right != null) q.add(temp.right); // If node is a leaf node if (temp.left == null && temp.right == null) pq.add(level); len--; } } } // Function to calculate the maximum number of leaf nodes // that can be visited within the given budget static int countLeafNodes(Node root, int budget) { pq = new PriorityQueue<>(); levelOrder(root); int val; // Variable to store the count of // number of leaf nodes possible to visit // within the given budget int count = 0; while (pq.size() != 0) { // Removing element from // min priority queue one by one val = pq.poll(); // If current val is under budget, the // node can be visited // Update the budget afterwards if (val <= budget) { count++; budget -= val; } else break; } return count; } // Driver code public static void main(String args[]) { Node root = new Node(10); root.left = new Node(8); root.right = new Node(15); root.left.left = new Node(3); root.left.left.right = new Node(13); root.right.left = new Node(11); root.right.right = new Node(18); int budget = 8; System.out.println(countLeafNodes(root, budget)); }} # Python3 program to calculate the maximum number of leaf# nodes that can be visited within the given budget # struct that represents a node of the treeclass Node: # Constructor to set the data of # the newly created tree node def __init__(self, key): self.data = key self.left = None self.right = None # Priority queue to store the levels# of all the leaf nodespq = [] # Level order traversal of the binary treedef levelOrder(root): q = [] level = 0 # If tree is empty if (root == None): return q.append(root) while (True) : Len = len(q) if (Len == 0): break level+=1 while (Len > 0) : temp = q[0] del q[0] # If left child exists if (temp.left != None): q.append(temp.left) # If right child exists if (temp.right != None): q.append(temp.right) # If node is a leaf node if (temp.left == None and temp.right == None): pq.append(level) pq.sort() pq.reverse() Len-=1 return pq # Function to calculate the maximum number of leaf nodes# that can be visited within the given budgetdef countLeafNodes(root, budget): pq = levelOrder(root) # Variable to store the count of # number of leaf nodes possible to visit # within the given budget count = 0 while (len(pq) != 0) : # Removing element from # min priority queue one by one val = pq[0] del pq[0] # If current val is under budget, the # node can be visited # Update the budget afterwards if (val <= budget) : count+=1 budget -= val else: break return count root = Node(10)root.left = Node(8)root.right = Node(15);root.left.left = Node(3)root.left.left.right = Node(13)root.right.left = Node(11)root.right.right = Node(18) budget = 8 print(countLeafNodes(root, budget)) # This code is contributed by suresh07. // C# program to calculate the maximum number of leaf// nodes that can be visited within the given budgetusing System;using System.Collections.Generic;class GFG { // Class that represents a node of the tree class Node { public Node left, right; public int data; }; static Node newNode(int key) { Node temp = new Node(); temp.data = key; temp.left = temp.right = null; return temp; } // Priority queue to store the levels // of all the leaf nodes static List<int> pq; // Level order traversal of the binary tree static void levelOrder(Node root) { List<Node> q = new List<Node>(); int len, level = 0; Node temp; // If tree is empty if (root == null) return; q.Add(root); while (true) { len = q.Count; if (len == 0) break; level++; while (len > 0) { temp = q[0]; q.RemoveAt(0); // If left child exists if (temp.left != null) q.Add(temp.left); // If right child exists if (temp.right != null) q.Add(temp.right); // If node is a leaf node if (temp.left == null && temp.right == null) { pq.Add(level); pq.Sort(); pq.Reverse(); } len--; } } } // Function to calculate the maximum number of leaf nodes // that can be visited within the given budget static int countLeafNodes(Node root, int budget) { pq = new List<int>(); levelOrder(root); int val; // Variable to store the count of // number of leaf nodes possible to visit // within the given budget int count = 0; while (pq.Count != 0) { // Removing element from // min priority queue one by one val = pq[0]; pq.RemoveAt(0); // If current val is under budget, the // node can be visited // Update the budget afterwards if (val <= budget) { count++; budget -= val; } else break; } return count; } static void Main() { Node root = newNode(10); root.left = newNode(8); root.right = newNode(15); root.left.left = newNode(3); root.left.left.right = newNode(13); root.right.left = newNode(11); root.right.right = newNode(18); int budget = 8; Console.Write(countLeafNodes(root, budget)); }} // This code is contributed by divyeshrabadiya07. <script> // JavaScript program to calculate // the maximum number of leaf // nodes that can be visited within the given budget // Class that represents a node of the tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Priority queue to store the levels // of all the leaf nodes let pq = []; // Level order traversal of the binary tree function levelOrder(root) { let q = []; let len, level = 0; let temp; // If tree is empty if (root == null) return; q.push(root); while (true) { len = q.length; if (len == 0) break; level++; while (len > 0) { temp = q.shift(); // If left child exists if (temp.left != null) q.push(temp.left); // If right child exists if (temp.right != null) q.push(temp.right); // If node is a leaf node if (temp.left == null && temp.right == null) { pq.push(level); pq.sort(function(a, b){return a - b}); pq.reverse(); } len--; } } } // Function to calculate the maximum number of leaf nodes // that can be visited within the given budget function countLeafNodes(root, budget) { pq = []; levelOrder(root); let val; // Variable to store the count of // number of leaf nodes possible to visit // within the given budget let count = 0; while (pq.length != 0) { // Removing element from // min priority queue one by one val = pq[0]; pq.shift(); // If current val is under budget, the // node can be visited // Update the budget afterwards if (val <= budget) { count++; budget -= val; } else break; } return count; } let root = new Node(10); root.left = new Node(8); root.right = new Node(15); root.left.left = new Node(3); root.left.left.right = new Node(13); root.right.left = new Node(11); root.right.right = new Node(18); let budget = 8; document.write(countLeafNodes(root, budget)); </script> 2 rameshtravel07 divyeshrabadiya07 decode2207 suresh07 java-priority-queue priority-queue tree-level-order Data Structures Heap Technical Scripter Tree Data Structures Tree Heap priority-queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Aug, 2021" }, { "code": null, "e": 333, "s": 52, "text": "Given a binary tree and an integer b representing budget. The task is to find the count of maximum number of leaf nodes that can be visited under the given budget if cost of visiting a leaf node is equal to level of that leaf node. Note: Root of the tree is at level 1.Examples: " }, { "code": null, "e": 1067, "s": 333, "text": "Input: b = 8\n 10\n / \\\n 8 15\n / / \\\n 3 11 18 \n \\\n 13\nOutput: 2\nFor the above binary tree, leaf nodes are 3, \n13 and 18 at levels 3, 4 and 3 respectively.\nCost for visiting leaf node 3 is 3\nCost for visiting leaf node 13 is 4\nCost for visiting leaf node 18 is 3\nThus with given budget = 8, we can at maximum\nvisit two leaf nodes.\n\nInput: b = 1\n 8\n / \\\n 7 10\n / \n 3 \n \nOutput: 0 \nFor the above binary tree, leaf nodes are\n3 and 10 at levels 3 and 2 respectively.\nCost for visiting leaf node 3 is 3\nCost for visiting leaf node 10 is 2\nIn given budget = 1, we can't visit\nany leaf node." }, { "code": null, "e": 1081, "s": 1069, "text": "Approach: " }, { "code": null, "e": 1198, "s": 1081, "text": "Traverse the binary tree using level order traversal, and store the level of all the leaf nodes in a priority queue." }, { "code": null, "e": 1294, "s": 1198, "text": "Remove an element from the priority queue one by one, check if this value is within the budget." }, { "code": null, "e": 1372, "s": 1294, "text": "If Yes then subtract this value from the budget and update count = count + 1." }, { "code": null, "e": 1461, "s": 1372, "text": "Else, print the count of maximum leaf nodes that can be visited within the given budget." }, { "code": null, "e": 1513, "s": 1461, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1517, "s": 1513, "text": "C++" }, { "code": null, "e": 1522, "s": 1517, "text": "Java" }, { "code": null, "e": 1530, "s": 1522, "text": "Python3" }, { "code": null, "e": 1533, "s": 1530, "text": "C#" }, { "code": null, "e": 1544, "s": 1533, "text": "Javascript" }, { "code": "// C++ program to calculate the maximum number of leaf// nodes that can be visited within the given budget#include <bits/stdc++.h>using namespace std; // struct that represents a node of the treestruct Node { Node* left; Node* right; int data; Node(int key) { data = key; this->left = nullptr; this->right = nullptr; }}; Node* newNode(int key){ Node* temp = new Node(key); return temp;} // Priority queue to store the levels// of all the leaf nodesvector<int> pq; // Level order traversal of the binary treevoid levelOrder(Node* root){ vector<Node*> q; int len, level = 0; Node* temp; // If tree is empty if (root == nullptr) return; q.push_back(root); while (true) { len = q.size(); if (len == 0) break; level++; while (len > 0) { temp = q[0]; q.erase(q.begin()); // If left child exists if (temp->left != nullptr) q.push_back(temp->left); // If right child exists if (temp->right != nullptr) q.push_back(temp->right); // If node is a leaf node if (temp->left == nullptr && temp->right == nullptr) { pq.push_back(level); sort(pq.begin(), pq.end()); reverse(pq.begin(), pq.end()); } len--; } }} // Function to calculate the maximum number of leaf nodes// that can be visited within the given budgetint countLeafNodes(Node* root, int budget){ levelOrder(root); int val; // Variable to store the count of // number of leaf nodes possible to visit // within the given budget int count = 0; while (pq.size() != 0) { // Removing element from // min priority queue one by one val = pq[0]; pq.erase(pq.begin()); // If current val is under budget, the // node can be visited // Update the budget afterwards if (val <= budget) { count++; budget -= val; } else break; } return count;} // Driver codeint main(){ Node* root = newNode(10); root->left = newNode(8); root->right = newNode(15); root->left->left = newNode(3); root->left->left->right = newNode(13); root->right->left = newNode(11); root->right->right = newNode(18); int budget = 8; cout << countLeafNodes(root, budget); return 0;} // This code is contributed by decode2207.", "e": 4066, "s": 1544, "text": null }, { "code": "// Java program to calculate the maximum number of leaf// nodes that can be visited within the given budgetimport java.io.*;import java.util.*;import java.lang.*; // Class that represents a node of the treeclass Node { int data; Node left, right; // Constructor to create a new tree node Node(int key) { data = key; left = right = null; }} class GFG { // Priority queue to store the levels // of all the leaf nodes static PriorityQueue<Integer> pq; // Level order traversal of the binary tree static void levelOrder(Node root) { Queue<Node> q = new LinkedList<>(); int len, level = 0; Node temp; // If tree is empty if (root == null) return; q.add(root); while (true) { len = q.size(); if (len == 0) break; level++; while (len > 0) { temp = q.remove(); // If left child exists if (temp.left != null) q.add(temp.left); // If right child exists if (temp.right != null) q.add(temp.right); // If node is a leaf node if (temp.left == null && temp.right == null) pq.add(level); len--; } } } // Function to calculate the maximum number of leaf nodes // that can be visited within the given budget static int countLeafNodes(Node root, int budget) { pq = new PriorityQueue<>(); levelOrder(root); int val; // Variable to store the count of // number of leaf nodes possible to visit // within the given budget int count = 0; while (pq.size() != 0) { // Removing element from // min priority queue one by one val = pq.poll(); // If current val is under budget, the // node can be visited // Update the budget afterwards if (val <= budget) { count++; budget -= val; } else break; } return count; } // Driver code public static void main(String args[]) { Node root = new Node(10); root.left = new Node(8); root.right = new Node(15); root.left.left = new Node(3); root.left.left.right = new Node(13); root.right.left = new Node(11); root.right.right = new Node(18); int budget = 8; System.out.println(countLeafNodes(root, budget)); }}", "e": 6677, "s": 4066, "text": null }, { "code": "# Python3 program to calculate the maximum number of leaf# nodes that can be visited within the given budget # struct that represents a node of the treeclass Node: # Constructor to set the data of # the newly created tree node def __init__(self, key): self.data = key self.left = None self.right = None # Priority queue to store the levels# of all the leaf nodespq = [] # Level order traversal of the binary treedef levelOrder(root): q = [] level = 0 # If tree is empty if (root == None): return q.append(root) while (True) : Len = len(q) if (Len == 0): break level+=1 while (Len > 0) : temp = q[0] del q[0] # If left child exists if (temp.left != None): q.append(temp.left) # If right child exists if (temp.right != None): q.append(temp.right) # If node is a leaf node if (temp.left == None and temp.right == None): pq.append(level) pq.sort() pq.reverse() Len-=1 return pq # Function to calculate the maximum number of leaf nodes# that can be visited within the given budgetdef countLeafNodes(root, budget): pq = levelOrder(root) # Variable to store the count of # number of leaf nodes possible to visit # within the given budget count = 0 while (len(pq) != 0) : # Removing element from # min priority queue one by one val = pq[0] del pq[0] # If current val is under budget, the # node can be visited # Update the budget afterwards if (val <= budget) : count+=1 budget -= val else: break return count root = Node(10)root.left = Node(8)root.right = Node(15);root.left.left = Node(3)root.left.left.right = Node(13)root.right.left = Node(11)root.right.right = Node(18) budget = 8 print(countLeafNodes(root, budget)) # This code is contributed by suresh07.", "e": 8782, "s": 6677, "text": null }, { "code": "// C# program to calculate the maximum number of leaf// nodes that can be visited within the given budgetusing System;using System.Collections.Generic;class GFG { // Class that represents a node of the tree class Node { public Node left, right; public int data; }; static Node newNode(int key) { Node temp = new Node(); temp.data = key; temp.left = temp.right = null; return temp; } // Priority queue to store the levels // of all the leaf nodes static List<int> pq; // Level order traversal of the binary tree static void levelOrder(Node root) { List<Node> q = new List<Node>(); int len, level = 0; Node temp; // If tree is empty if (root == null) return; q.Add(root); while (true) { len = q.Count; if (len == 0) break; level++; while (len > 0) { temp = q[0]; q.RemoveAt(0); // If left child exists if (temp.left != null) q.Add(temp.left); // If right child exists if (temp.right != null) q.Add(temp.right); // If node is a leaf node if (temp.left == null && temp.right == null) { pq.Add(level); pq.Sort(); pq.Reverse(); } len--; } } } // Function to calculate the maximum number of leaf nodes // that can be visited within the given budget static int countLeafNodes(Node root, int budget) { pq = new List<int>(); levelOrder(root); int val; // Variable to store the count of // number of leaf nodes possible to visit // within the given budget int count = 0; while (pq.Count != 0) { // Removing element from // min priority queue one by one val = pq[0]; pq.RemoveAt(0); // If current val is under budget, the // node can be visited // Update the budget afterwards if (val <= budget) { count++; budget -= val; } else break; } return count; } static void Main() { Node root = newNode(10); root.left = newNode(8); root.right = newNode(15); root.left.left = newNode(3); root.left.left.right = newNode(13); root.right.left = newNode(11); root.right.right = newNode(18); int budget = 8; Console.Write(countLeafNodes(root, budget)); }} // This code is contributed by divyeshrabadiya07.", "e": 11558, "s": 8782, "text": null }, { "code": "<script> // JavaScript program to calculate // the maximum number of leaf // nodes that can be visited within the given budget // Class that represents a node of the tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Priority queue to store the levels // of all the leaf nodes let pq = []; // Level order traversal of the binary tree function levelOrder(root) { let q = []; let len, level = 0; let temp; // If tree is empty if (root == null) return; q.push(root); while (true) { len = q.length; if (len == 0) break; level++; while (len > 0) { temp = q.shift(); // If left child exists if (temp.left != null) q.push(temp.left); // If right child exists if (temp.right != null) q.push(temp.right); // If node is a leaf node if (temp.left == null && temp.right == null) { pq.push(level); pq.sort(function(a, b){return a - b}); pq.reverse(); } len--; } } } // Function to calculate the maximum number of leaf nodes // that can be visited within the given budget function countLeafNodes(root, budget) { pq = []; levelOrder(root); let val; // Variable to store the count of // number of leaf nodes possible to visit // within the given budget let count = 0; while (pq.length != 0) { // Removing element from // min priority queue one by one val = pq[0]; pq.shift(); // If current val is under budget, the // node can be visited // Update the budget afterwards if (val <= budget) { count++; budget -= val; } else break; } return count; } let root = new Node(10); root.left = new Node(8); root.right = new Node(15); root.left.left = new Node(3); root.left.left.right = new Node(13); root.right.left = new Node(11); root.right.right = new Node(18); let budget = 8; document.write(countLeafNodes(root, budget)); </script>", "e": 14111, "s": 11558, "text": null }, { "code": null, "e": 14113, "s": 14111, "text": "2" }, { "code": null, "e": 14130, "s": 14115, "text": "rameshtravel07" }, { "code": null, "e": 14148, "s": 14130, "text": "divyeshrabadiya07" }, { "code": null, "e": 14159, "s": 14148, "text": "decode2207" }, { "code": null, "e": 14168, "s": 14159, "text": "suresh07" }, { "code": null, "e": 14188, "s": 14168, "text": "java-priority-queue" }, { "code": null, "e": 14203, "s": 14188, "text": "priority-queue" }, { "code": null, "e": 14220, "s": 14203, "text": "tree-level-order" }, { "code": null, "e": 14236, "s": 14220, "text": "Data Structures" }, { "code": null, "e": 14241, "s": 14236, "text": "Heap" }, { "code": null, "e": 14260, "s": 14241, "text": "Technical Scripter" }, { "code": null, "e": 14265, "s": 14260, "text": "Tree" }, { "code": null, "e": 14281, "s": 14265, "text": "Data Structures" }, { "code": null, "e": 14286, "s": 14281, "text": "Tree" }, { "code": null, "e": 14291, "s": 14286, "text": "Heap" }, { "code": null, "e": 14306, "s": 14291, "text": "priority-queue" } ]
How to take screenshot of a div using JavaScript ?
30 Jul, 2021 A screenshot of any element in JavaScript can be taken using the html2canvas library. This library can be downloaded from its official website. The below steps show the method to take a screenshot of a <div> element using JavaScript. Step 1: Create a blank HTML document.Step 2: Include the html2canvas library code by either using the downloaded file or using a link to a CDN version. HTML <!DOCTYPE html><html><head> <title> How to take screenshot of a div using JavaScript? </title> <!-- Include from the CDN --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/html2canvas.min.js"> </script> <!-- Include locally otherwise --> <!-- <script src='html2canvas.js'></script> --></head><body> </body></html> Step 3: Create a <div> that has to be captured in the screenshot and give it an id so that it can be used later. HTML <!DOCTYPE html><html> <head> <title> How to take screenshot of a div using JavaScript? </title> <!-- Include from the CDN --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/html2canvas.min.js"> </script> <!-- Include locally otherwise --> <!-- <script src='html2canvas.js'></script> --> <style> #photo { border: 4px solid green; padding: 4px; } </style></head> <body> <div id="photo"> <h1>GeeksforGeeks</h1> Hello everyone! This is a trial page for taking a screenshot. <br><br> This is a dummy button! <button> Dummy</button> <br><br> Click the button below to take a screenshot of the div. <br><br> </div> <h1>Screenshot:</h1> <div id="output"></div></body> </html> Step 4: Create a button inside <div> element and use an “onclick” handler for the button. HTML <!DOCTYPE html><html> <head> <title> How to take screenshot of a div using JavaScript? </title> <!-- Include from the CDN --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/html2canvas.min.js"> </script> <!-- Include locally otherwise --> <!-- <script src='html2canvas.js'></script> --> <style> #photo { border: 4px solid green; padding: 4px; } </style></head> <body> <div id="photo"> <h1>GeeksforGeeks</h1> Hello everyone! This is a trial page for taking a screenshot. <br><br> This is a dummy button! <button> Dummy</button> <br><br> Click the button below to take a screenshot of the div. <br><br> <!-- Define the button that will be used to take the screenshot --> <button onclick="takeshot()"> Take Screenshot </button> </div> <h1>Screenshot:</h1> <div id="output"></div></body> </html> Step 5: The function to take the screenshot is defined inside the <script> tag. This function will use the html2canvas library to take the screenshot and append it to the body of the page. HTML <!DOCTYPE html><html> <head> <title> How to take screenshot of a div using JavaScript? </title> <!-- Include from the CDN --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/html2canvas.min.js"> </script> <!-- Include locally otherwise --> <!-- <script src='html2canvas.js'></script> --> <style> #photo { border: 4px solid green; padding: 4px; } </style></head> <body> <div id="photo"> <h1>GeeksforGeeks</h1> Hello everyone! This is a trial page for taking a screenshot. <br><br> This is a dummy button! <button> Dummy</button> <br><br> Click the button below to take a screenshot of the div. <br><br> <!-- Define the button that will be used to take the screenshot --> <button onclick="takeshot()"> Take Screenshot </button> </div> <h1>Screenshot:</h1> <div id="output"></div> <script type="text/javascript"> // Define the function // to screenshot the div function takeshot() { let div = document.getElementById('photo'); // Use the html2canvas // function to take a screenshot // and append it // to the output div html2canvas(div).then( function (canvas) { document .getElementById('output') .appendChild(canvas); }) } </script></body> </html> The screenshot can be saved by right-clicking on it and saving it as an image, as shown below. Output: 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. CSS-Misc HTML-Misc JavaScript-Misc Picked CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jul, 2021" }, { "code": null, "e": 262, "s": 28, "text": "A screenshot of any element in JavaScript can be taken using the html2canvas library. This library can be downloaded from its official website. The below steps show the method to take a screenshot of a <div> element using JavaScript." }, { "code": null, "e": 414, "s": 262, "text": "Step 1: Create a blank HTML document.Step 2: Include the html2canvas library code by either using the downloaded file or using a link to a CDN version." }, { "code": null, "e": 419, "s": 414, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> How to take screenshot of a div using JavaScript? </title> <!-- Include from the CDN --> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/html2canvas.min.js\"> </script> <!-- Include locally otherwise --> <!-- <script src='html2canvas.js'></script> --></head><body> </body></html>", "e": 776, "s": 419, "text": null }, { "code": null, "e": 889, "s": 776, "text": "Step 3: Create a <div> that has to be captured in the screenshot and give it an id so that it can be used later." }, { "code": null, "e": 894, "s": 889, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to take screenshot of a div using JavaScript? </title> <!-- Include from the CDN --> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/html2canvas.min.js\"> </script> <!-- Include locally otherwise --> <!-- <script src='html2canvas.js'></script> --> <style> #photo { border: 4px solid green; padding: 4px; } </style></head> <body> <div id=\"photo\"> <h1>GeeksforGeeks</h1> Hello everyone! This is a trial page for taking a screenshot. <br><br> This is a dummy button! <button> Dummy</button> <br><br> Click the button below to take a screenshot of the div. <br><br> </div> <h1>Screenshot:</h1> <div id=\"output\"></div></body> </html>", "e": 1758, "s": 894, "text": null }, { "code": null, "e": 1848, "s": 1758, "text": "Step 4: Create a button inside <div> element and use an “onclick” handler for the button." }, { "code": null, "e": 1853, "s": 1848, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to take screenshot of a div using JavaScript? </title> <!-- Include from the CDN --> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/html2canvas.min.js\"> </script> <!-- Include locally otherwise --> <!-- <script src='html2canvas.js'></script> --> <style> #photo { border: 4px solid green; padding: 4px; } </style></head> <body> <div id=\"photo\"> <h1>GeeksforGeeks</h1> Hello everyone! This is a trial page for taking a screenshot. <br><br> This is a dummy button! <button> Dummy</button> <br><br> Click the button below to take a screenshot of the div. <br><br> <!-- Define the button that will be used to take the screenshot --> <button onclick=\"takeshot()\"> Take Screenshot </button> </div> <h1>Screenshot:</h1> <div id=\"output\"></div></body> </html>", "e": 2893, "s": 1853, "text": null }, { "code": null, "e": 3082, "s": 2893, "text": "Step 5: The function to take the screenshot is defined inside the <script> tag. This function will use the html2canvas library to take the screenshot and append it to the body of the page." }, { "code": null, "e": 3087, "s": 3082, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to take screenshot of a div using JavaScript? </title> <!-- Include from the CDN --> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/html2canvas.min.js\"> </script> <!-- Include locally otherwise --> <!-- <script src='html2canvas.js'></script> --> <style> #photo { border: 4px solid green; padding: 4px; } </style></head> <body> <div id=\"photo\"> <h1>GeeksforGeeks</h1> Hello everyone! This is a trial page for taking a screenshot. <br><br> This is a dummy button! <button> Dummy</button> <br><br> Click the button below to take a screenshot of the div. <br><br> <!-- Define the button that will be used to take the screenshot --> <button onclick=\"takeshot()\"> Take Screenshot </button> </div> <h1>Screenshot:</h1> <div id=\"output\"></div> <script type=\"text/javascript\"> // Define the function // to screenshot the div function takeshot() { let div = document.getElementById('photo'); // Use the html2canvas // function to take a screenshot // and append it // to the output div html2canvas(div).then( function (canvas) { document .getElementById('output') .appendChild(canvas); }) } </script></body> </html>", "e": 4691, "s": 3087, "text": null }, { "code": null, "e": 4786, "s": 4691, "text": "The screenshot can be saved by right-clicking on it and saving it as an image, as shown below." }, { "code": null, "e": 4794, "s": 4786, "text": "Output:" }, { "code": null, "e": 4980, "s": 4794, "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": 4989, "s": 4980, "text": "CSS-Misc" }, { "code": null, "e": 4999, "s": 4989, "text": "HTML-Misc" }, { "code": null, "e": 5015, "s": 4999, "text": "JavaScript-Misc" }, { "code": null, "e": 5022, "s": 5015, "text": "Picked" }, { "code": null, "e": 5026, "s": 5022, "text": "CSS" }, { "code": null, "e": 5031, "s": 5026, "text": "HTML" }, { "code": null, "e": 5042, "s": 5031, "text": "JavaScript" }, { "code": null, "e": 5059, "s": 5042, "text": "Web Technologies" }, { "code": null, "e": 5086, "s": 5059, "text": "Web technologies Questions" }, { "code": null, "e": 5091, "s": 5086, "text": "HTML" } ]
Java 8 Optional Class
19 Feb, 2022 Every Java Programmer is familiar with NullPointerException. It can crash your code. And it is very hard to avoid it without using too many null checks. So, to overcome this, Java 8 has introduced a new class Optional in java.util package. It can help in writing a neat code without using too many null checks. By using Optional, we can specify alternate values to return or alternate code to run. This makes the code more readable because the facts which were hidden are now visible to the developer. Java // Java program without Optional Class public class OptionalDemo { public static void main(String[] args) { String[] words = new String[10]; String word = words[5].toLowerCase(); System.out.print(word); }} Output: Exception in thread "main" java.lang.NullPointerException To avoid abnormal termination, we use the Optional class. In the following example, we are using Optional. So, our program can execute without crashing. The above program using Optional Class Java // Java program with Optional Class import java.util.Optional; public class OptionalDemo { public static void main(String[] args) { String[] words = new String[10]; Optional<String> checkNull = Optional.ofNullable(words[5]); if (checkNull.isPresent()) { String word = words[5].toLowerCase(); System.out.print(word); } else System.out.println("word is null"); }} word is null Optional is a container object which may or may not contain a non-null value. You must import java.util package to use this class. If a value is present, isPresent() will return true and get() will return the value. Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() which returns a default value if the value is not present, and ifPresent() which executes a block of code if the value is present. This is a value-based class, i.e their instances are : Final and immutable (though may contain references to mutable objects). Considered equal solely based on equals(), not based on reference equality(==). Do not have accessible constructors. Static Methods: Static methods are the methods in Java that can be called without creating an object of the class. They are referenced by the class name itself or reference to the object of that class. Syntax : public static void geek(String name) { // code to be executed.... } // Must have static modifier in their declaration. // Return type can be int, float, String or user-defined data type. Important Points: Since Static methods belong to the class, they can be called to without creating the object of the class. Below given are some important points regarding Static Methods : Static method(s) are associated with the class in which they reside i.e. they can be called even without creating an instance of the class. They are designed with the aim to be shared among all objects created from the same class. Static methods can not be overridden. But can be overloaded since they are resolved using static binding by the compiler at compile time. The following table shows the list of Static Methods provided by Optional Class : Instance Methods: Instance methods are methods that require an object of its class to be created before it can be called. To invoke an instance method, we have to create an Object of the class within which it is defined. Syntax : public void geek(String name) { // code to be executed.... } // Return type can be int, float String or user defined data type. Important Points: Instance Methods can be called within the same class in which they reside or from the different classes defined either in the same package or other packages depending on the access type provided to the desired instance method. Below given are some important points regarding Instance Methods : Instance method(s) belong to the Object of the class, not to the class i.e. they can be called after creating the Object of the class. Every individual object created from the class has its own copy of the instance method(s) of that class. They can be overridden since they are resolved using dynamic binding at run time. The following table shows the list of Instance Methods provided by the Optional Class : Concrete Methods: A concrete method means, the method has a complete definition but can be overridden in the inherited class. If we make this method final, then it can not be overridden. Declaring method or class “final” means its implementation is complete. It is compulsory to override abstract methods. Concrete Methods can be overridden in the inherited classes if they are not final. The following table shows the list of Concrete Methods provided by the Optional Class : Below given are some examples : Example 1 : Java // Java program to illustrate// optional class methods import java.util.Optional; class GFG { // Driver code public static void main(String[] args) { // creating a string array String[] str = new String[5]; // Setting value for 2nd index str[2] = "Geeks Classes are coming soon"; // It returns an empty instance of Optional class Optional<String> empty = Optional.empty(); System.out.println(empty); // It returns a non-empty Optional Optional<String> value = Optional.of(str[2]); System.out.println(value); }} Optional.empty Optional[Geeks Classes are coming soon] Example 2 : Java // Java program to illustrate// optional class methods import java.util.Optional; class GFG { // Driver code public static void main(String[] args) { // creating a string array String[] str = new String[5]; // Setting value for 2nd index str[2] = "Geeks Classes are coming soon"; // It returns a non-empty Optional Optional<String> value = Optional.of(str[2]); // It returns value of an Optional. // If value is not present, it throws // an NoSuchElementException System.out.println(value.get()); // It returns hashCode of the value System.out.println(value.hashCode()); // It returns true if value is present, // otherwise false System.out.println(value.isPresent()); }} Geeks Classes are coming soon 1967487235 true This article is contributed by loginakanksha and Sahil Bansal . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Kirti_Mangal nishkarshgandhi Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Feb, 2022" }, { "code": null, "e": 556, "s": 54, "text": "Every Java Programmer is familiar with NullPointerException. It can crash your code. And it is very hard to avoid it without using too many null checks. So, to overcome this, Java 8 has introduced a new class Optional in java.util package. It can help in writing a neat code without using too many null checks. By using Optional, we can specify alternate values to return or alternate code to run. This makes the code more readable because the facts which were hidden are now visible to the developer." }, { "code": null, "e": 561, "s": 556, "text": "Java" }, { "code": "// Java program without Optional Class public class OptionalDemo { public static void main(String[] args) { String[] words = new String[10]; String word = words[5].toLowerCase(); System.out.print(word); }}", "e": 797, "s": 561, "text": null }, { "code": null, "e": 805, "s": 797, "text": "Output:" }, { "code": null, "e": 863, "s": 805, "text": "Exception in thread \"main\" java.lang.NullPointerException" }, { "code": null, "e": 1016, "s": 863, "text": "To avoid abnormal termination, we use the Optional class. In the following example, we are using Optional. So, our program can execute without crashing." }, { "code": null, "e": 1055, "s": 1016, "text": "The above program using Optional Class" }, { "code": null, "e": 1060, "s": 1055, "text": "Java" }, { "code": "// Java program with Optional Class import java.util.Optional; public class OptionalDemo { public static void main(String[] args) { String[] words = new String[10]; Optional<String> checkNull = Optional.ofNullable(words[5]); if (checkNull.isPresent()) { String word = words[5].toLowerCase(); System.out.print(word); } else System.out.println(\"word is null\"); }}", "e": 1510, "s": 1060, "text": null }, { "code": null, "e": 1523, "s": 1510, "text": "word is null" }, { "code": null, "e": 2036, "s": 1523, "text": "Optional is a container object which may or may not contain a non-null value. You must import java.util package to use this class. If a value is present, isPresent() will return true and get() will return the value. Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() which returns a default value if the value is not present, and ifPresent() which executes a block of code if the value is present. This is a value-based class, i.e their instances are : " }, { "code": null, "e": 2108, "s": 2036, "text": "Final and immutable (though may contain references to mutable objects)." }, { "code": null, "e": 2188, "s": 2108, "text": "Considered equal solely based on equals(), not based on reference equality(==)." }, { "code": null, "e": 2225, "s": 2188, "text": "Do not have accessible constructors." }, { "code": null, "e": 2428, "s": 2225, "text": "Static Methods: Static methods are the methods in Java that can be called without creating an object of the class. They are referenced by the class name itself or reference to the object of that class. " }, { "code": null, "e": 2438, "s": 2428, "text": "Syntax : " }, { "code": null, "e": 2627, "s": 2438, "text": "public static void geek(String name)\n{\n // code to be executed....\n}\n\n// Must have static modifier in their declaration.\n// Return type can be int, float, String or user-defined data type." }, { "code": null, "e": 2817, "s": 2627, "text": "Important Points: Since Static methods belong to the class, they can be called to without creating the object of the class. Below given are some important points regarding Static Methods : " }, { "code": null, "e": 2957, "s": 2817, "text": "Static method(s) are associated with the class in which they reside i.e. they can be called even without creating an instance of the class." }, { "code": null, "e": 3048, "s": 2957, "text": "They are designed with the aim to be shared among all objects created from the same class." }, { "code": null, "e": 3186, "s": 3048, "text": "Static methods can not be overridden. But can be overloaded since they are resolved using static binding by the compiler at compile time." }, { "code": null, "e": 3269, "s": 3186, "text": "The following table shows the list of Static Methods provided by Optional Class : " }, { "code": null, "e": 3491, "s": 3269, "text": "Instance Methods: Instance methods are methods that require an object of its class to be created before it can be called. To invoke an instance method, we have to create an Object of the class within which it is defined. " }, { "code": null, "e": 3501, "s": 3491, "text": "Syntax : " }, { "code": null, "e": 3630, "s": 3501, "text": "public void geek(String name)\n{\n // code to be executed....\n}\n// Return type can be int, float String or user defined data type." }, { "code": null, "e": 3943, "s": 3630, "text": "Important Points: Instance Methods can be called within the same class in which they reside or from the different classes defined either in the same package or other packages depending on the access type provided to the desired instance method. Below given are some important points regarding Instance Methods : " }, { "code": null, "e": 4078, "s": 3943, "text": "Instance method(s) belong to the Object of the class, not to the class i.e. they can be called after creating the Object of the class." }, { "code": null, "e": 4183, "s": 4078, "text": "Every individual object created from the class has its own copy of the instance method(s) of that class." }, { "code": null, "e": 4265, "s": 4183, "text": "They can be overridden since they are resolved using dynamic binding at run time." }, { "code": null, "e": 4354, "s": 4265, "text": "The following table shows the list of Instance Methods provided by the Optional Class : " }, { "code": null, "e": 4831, "s": 4354, "text": "Concrete Methods: A concrete method means, the method has a complete definition but can be overridden in the inherited class. If we make this method final, then it can not be overridden. Declaring method or class “final” means its implementation is complete. It is compulsory to override abstract methods. Concrete Methods can be overridden in the inherited classes if they are not final. The following table shows the list of Concrete Methods provided by the Optional Class :" }, { "code": null, "e": 4863, "s": 4831, "text": "Below given are some examples :" }, { "code": null, "e": 4876, "s": 4863, "text": "Example 1 : " }, { "code": null, "e": 4881, "s": 4876, "text": "Java" }, { "code": "// Java program to illustrate// optional class methods import java.util.Optional; class GFG { // Driver code public static void main(String[] args) { // creating a string array String[] str = new String[5]; // Setting value for 2nd index str[2] = \"Geeks Classes are coming soon\"; // It returns an empty instance of Optional class Optional<String> empty = Optional.empty(); System.out.println(empty); // It returns a non-empty Optional Optional<String> value = Optional.of(str[2]); System.out.println(value); }}", "e": 5479, "s": 4881, "text": null }, { "code": null, "e": 5534, "s": 5479, "text": "Optional.empty\nOptional[Geeks Classes are coming soon]" }, { "code": null, "e": 5547, "s": 5534, "text": "Example 2 : " }, { "code": null, "e": 5552, "s": 5547, "text": "Java" }, { "code": "// Java program to illustrate// optional class methods import java.util.Optional; class GFG { // Driver code public static void main(String[] args) { // creating a string array String[] str = new String[5]; // Setting value for 2nd index str[2] = \"Geeks Classes are coming soon\"; // It returns a non-empty Optional Optional<String> value = Optional.of(str[2]); // It returns value of an Optional. // If value is not present, it throws // an NoSuchElementException System.out.println(value.get()); // It returns hashCode of the value System.out.println(value.hashCode()); // It returns true if value is present, // otherwise false System.out.println(value.isPresent()); }}", "e": 6348, "s": 5552, "text": null }, { "code": null, "e": 6394, "s": 6348, "text": "Geeks Classes are coming soon\n1967487235\ntrue" }, { "code": null, "e": 6834, "s": 6394, "text": "This article is contributed by loginakanksha and Sahil Bansal . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 6847, "s": 6834, "text": "Kirti_Mangal" }, { "code": null, "e": 6863, "s": 6847, "text": "nishkarshgandhi" }, { "code": null, "e": 6868, "s": 6863, "text": "Java" }, { "code": null, "e": 6873, "s": 6868, "text": "Java" } ]
p5.Camera move() Method
28 Jul, 2020 The move() method of p5.Camera in p5.js is used to move the camera along its local axes by the specified amount. It maintains the current camera orientation while moving. Syntax: move( x, y, z ) Parameters: This method accepts three parameters as mentioned above and described below: x: It is a number that denotes the amount to move the camera along its left-right axis. y: It is a number that denotes the amount to move the camera along its up-down axis. z: It is a number that denotes the amount to move the camera along its forward-backward axis. The example below illustrates the move() method in p5.js: Example 1: Javascript let currCamera; function setup() { createCanvas(500, 500, WEBGL); helpText = createP( "Click the buttons to move the " + "camera in that direction"); helpText.position(20, 0); currCamera = createCamera(); // Create three buttons for moving the // position camera newCameraBtn = createButton("Move Left"); newCameraBtn.position(20, 40); newCameraBtn.mouseClicked(moveCameraLeft); newCameraBtn = createButton("Move Right"); newCameraBtn.position(120, 40); newCameraBtn.mouseClicked(moveCameraRight); newCameraBtn = createButton("Move Up"); newCameraBtn.position(20, 70); newCameraBtn.mouseClicked(moveCameraUp); newCameraBtn = createButton("Move Down"); newCameraBtn.position(120, 70); newCameraBtn.mouseClicked(moveCameraDown);} function moveCameraLeft() { // Look at the given position // in the world space currCamera.move(-15, 0, 0);} function moveCameraRight() { // Look at the given position // in the world space currCamera.move(15, 0, 0);} function moveCameraUp() { // Look at the given position // in the world space currCamera.move(0, -15, 0);} function moveCameraDown() { // Look at the given position // in the world space currCamera.move(0, 15, 0);} function draw() { clear(); normalMaterial(); // Create three boxes at three positions translate(-150, 0); box(65); translate(150, 0); box(65); translate(150, 0); box(65);} Output: Example 2: Javascript let currCamera; function setup() { createCanvas(500, 500, WEBGL); helpText = createP( "Move the sliders to keep moving " + "the camera in a direction" ); helpText.position(20, 0); // Create the camera currCamera = createCamera(); // Create three sliders for moving the // position of the camera xPosSlider = createSlider(-2, 2, 0); xPosSlider.position(20, 40); yPosSlider = createSlider(-2, 2, 0); yPosSlider.position(20, 70); zPosSlider = createSlider(-2, 2, 0); zPosSlider.position(20, 100);} function draw() { clear(); lights(); normalMaterial(); debugMode(); // Get the x, y, z values from the // sliders let currX = xPosSlider.value(); let currY = yPosSlider.value(); let currZ = zPosSlider.value(); // Keep moving the camera according to // to the given amount currCamera.move(currX, currY, currZ); box(90);} Output: Online editor: https://editor.p5js.org/ Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ Reference: https://p5js.org/reference/#/p5.Camera/move JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jul, 2020" }, { "code": null, "e": 199, "s": 28, "text": "The move() method of p5.Camera in p5.js is used to move the camera along its local axes by the specified amount. It maintains the current camera orientation while moving." }, { "code": null, "e": 207, "s": 199, "text": "Syntax:" }, { "code": null, "e": 223, "s": 207, "text": "move( x, y, z )" }, { "code": null, "e": 312, "s": 223, "text": "Parameters: This method accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 400, "s": 312, "text": "x: It is a number that denotes the amount to move the camera along its left-right axis." }, { "code": null, "e": 485, "s": 400, "text": "y: It is a number that denotes the amount to move the camera along its up-down axis." }, { "code": null, "e": 579, "s": 485, "text": "z: It is a number that denotes the amount to move the camera along its forward-backward axis." }, { "code": null, "e": 637, "s": 579, "text": "The example below illustrates the move() method in p5.js:" }, { "code": null, "e": 648, "s": 637, "text": "Example 1:" }, { "code": null, "e": 659, "s": 648, "text": "Javascript" }, { "code": "let currCamera; function setup() { createCanvas(500, 500, WEBGL); helpText = createP( \"Click the buttons to move the \" + \"camera in that direction\"); helpText.position(20, 0); currCamera = createCamera(); // Create three buttons for moving the // position camera newCameraBtn = createButton(\"Move Left\"); newCameraBtn.position(20, 40); newCameraBtn.mouseClicked(moveCameraLeft); newCameraBtn = createButton(\"Move Right\"); newCameraBtn.position(120, 40); newCameraBtn.mouseClicked(moveCameraRight); newCameraBtn = createButton(\"Move Up\"); newCameraBtn.position(20, 70); newCameraBtn.mouseClicked(moveCameraUp); newCameraBtn = createButton(\"Move Down\"); newCameraBtn.position(120, 70); newCameraBtn.mouseClicked(moveCameraDown);} function moveCameraLeft() { // Look at the given position // in the world space currCamera.move(-15, 0, 0);} function moveCameraRight() { // Look at the given position // in the world space currCamera.move(15, 0, 0);} function moveCameraUp() { // Look at the given position // in the world space currCamera.move(0, -15, 0);} function moveCameraDown() { // Look at the given position // in the world space currCamera.move(0, 15, 0);} function draw() { clear(); normalMaterial(); // Create three boxes at three positions translate(-150, 0); box(65); translate(150, 0); box(65); translate(150, 0); box(65);}", "e": 2065, "s": 659, "text": null }, { "code": null, "e": 2073, "s": 2065, "text": "Output:" }, { "code": null, "e": 2084, "s": 2073, "text": "Example 2:" }, { "code": null, "e": 2095, "s": 2084, "text": "Javascript" }, { "code": "let currCamera; function setup() { createCanvas(500, 500, WEBGL); helpText = createP( \"Move the sliders to keep moving \" + \"the camera in a direction\" ); helpText.position(20, 0); // Create the camera currCamera = createCamera(); // Create three sliders for moving the // position of the camera xPosSlider = createSlider(-2, 2, 0); xPosSlider.position(20, 40); yPosSlider = createSlider(-2, 2, 0); yPosSlider.position(20, 70); zPosSlider = createSlider(-2, 2, 0); zPosSlider.position(20, 100);} function draw() { clear(); lights(); normalMaterial(); debugMode(); // Get the x, y, z values from the // sliders let currX = xPosSlider.value(); let currY = yPosSlider.value(); let currZ = zPosSlider.value(); // Keep moving the camera according to // to the given amount currCamera.move(currX, currY, currZ); box(90);}", "e": 2959, "s": 2095, "text": null }, { "code": null, "e": 2967, "s": 2959, "text": "Output:" }, { "code": null, "e": 3007, "s": 2967, "text": "Online editor: https://editor.p5js.org/" }, { "code": null, "e": 3105, "s": 3007, "text": "Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/" }, { "code": null, "e": 3160, "s": 3105, "text": "Reference: https://p5js.org/reference/#/p5.Camera/move" }, { "code": null, "e": 3177, "s": 3160, "text": "JavaScript-p5.js" }, { "code": null, "e": 3188, "s": 3177, "text": "JavaScript" }, { "code": null, "e": 3205, "s": 3188, "text": "Web Technologies" } ]
How to Highlight the Searched String Result using JavaScript ?
10 Dec, 2020 Given below is an HTML document which is basically about how to highlight the searched string result. In this article, we are using HTML, CSS, JavaScript, Bootstrap and mark.js to make our website more effective. Moreover, exclusively for highlighting the searched string among a given context or paragraph, mark.js plays a vital role in this particular code. Before approaching this problem, keep a mark of my words that, the problem can be solved by many other approaches but I think this can also be a way better approach towards this given problem. What is mark.js? mark.js is a simple JavaScript tool that is used to highlight the text. Which is used to dynamically mark search terms or custom regular expression and offer some built-in options like diacritics support, separate word search etc. Approach: First thing first when you are entering some string on the search box and press the search button then a simple JavaScript function will call named as highlight() which has the main role is to highlight the search text that you had entered in the search box. In this small, we are going to use mark.js code to highlight the text. There are many built-in functions in mark.js but we are using two functions for our requirement that is mark() and unmark() function respectively. Here mark() is used to highlight the search text and unmark() is used to remove highlighting the text that is highlighted before. Syntax of mark(): var context = document.querySelector(".context"); var obj = new Mark(context); obj.mark(searchkeyword [, options]); Let’s understand this code in a bit of technical manner,First we declare a variable which contains context from which it is going to find and highlight the searched text. Create an object of the mark and then call the mark() method through the obj that you create previously.It takes two parameters with it i.e, one is searched keyword and another is optional. First we declare a variable which contains context from which it is going to find and highlight the searched text. Create an object of the mark and then call the mark() method through the obj that you create previously. It takes two parameters with it i.e, one is searched keyword and another is optional. Syntax of unmark(): var context = document.querySelector(".context"); var obj = new Mark(context); obj.unmark(options); This is near about same as the above technique but the only minute difference is that unmark() method takes only one argument with it i.e, optional. Further, if you want to change the color and padding of highlighter then we need to make slight changes in the CSS code inside mark which is given below:mark { color: black; background: green; padding: 5px; } mark { color: black; background: green; padding: 5px; } Hope you have successfully followed the above steps in order to make changes in the color of the particular highlighted text. But here make sure that there should not be any string left highlighted with any particular color if it is so then don’t forget to un-highlight the text which was searched previously. Thereafter, mark the new string which is to be searched and you can change its color according to your convenience. For more information follow this page. Example: HTML <!DOCTYPE html><html> <head> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <!-- CDN of fontawsome --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <!-- CDN of Bootstrap --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous"> <!-- CDN of mark.js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/mark.min.js" integrity="sha512-5CYOlHXGh6QpOFA/TeTylKLWfB3ftPsde7AnmhuitiTX4K5SqCLBeKro6sPS8ilsz1Q4NRx3v8Ko2IBiszzdww==" crossorigin="anonymous"> </script> <!-- CDN of google font --> <style> @import url('https://fonts.googleapis.com/css2?family=Roboto+Slab:wght@500&display=swap' ); </style> <style> mark.a0 { color: black; padding: 5px; background: greenyellow; } mark.a1 { color: black; padding: 5px; background: cyan; } mark.a2 { color: black; padding: 5px; background: red; } mark.a3 { color: white; padding: 5px; background: green; } mark.a4 { color: black; padding: 5px; background: pink; } </style></head> <body style="border:4px solid rgb(0, 128, 28);"> <h1 style="font-family: 'Roboto Slab', serif;text-align: center;color:green;"> GeeksForGeeks </h1> <br><br> <form> <div class="container-fluid" align="center"> <input type="text" size="30" placeholder="search..." id="searched" style="border: 1px solid green; width:300px;height:30px;"> <button type="button" class="btn-primary btn-sm" style="margin-left:-5px;height:32px;width:35px; background-color:rgb(12, 138, 12); border:0px;" onclick="highlight('0');"> <i class="fa fa-search"></i> </button> </div> </form> <br><br> <div align="center"> <div> <b><i>Choose the color of highlighter:</i></b> </div> <br> <div style="background-color: cyan; width: 20px; height: 20px; display: inline-block; margin-left: -30px;" onmouseover="highlight('1')"> </div> <div style="background-color: red; width: 20px; height: 20px; display: inline-block; margin-left: 10px;" onmouseover="highlight('2')"> </div> <div style="background-color: green; width: 20px; height: 20px; display: inline-block; margin-left: 10px;" onmouseover="highlight('3')"> </div> <div style="background-color: pink; width: 20px; height: 20px; display: inline-block; margin-left: 10px;" onmouseover="highlight('4')"> </div> </div> <div class="container-fluid" style= "padding-left: 30%; padding-right: 30%; padding-top: 5%;"> <p class="select"> GeeksforGeeks.org was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions.The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. </p> </div> <script> function highlight(param) { // Select the whole paragraph var ob = new Mark(document.querySelector(".select")); // First unmark the highlighted word or letter ob.unmark(); // Highlight letter or word ob.mark( document.getElementById("searched").value, { className: 'a' + param } ); } </script></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc Picked Technical Scripter 2020 CSS HTML JavaScript Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Dec, 2020" }, { "code": null, "e": 607, "s": 54, "text": "Given below is an HTML document which is basically about how to highlight the searched string result. In this article, we are using HTML, CSS, JavaScript, Bootstrap and mark.js to make our website more effective. Moreover, exclusively for highlighting the searched string among a given context or paragraph, mark.js plays a vital role in this particular code. Before approaching this problem, keep a mark of my words that, the problem can be solved by many other approaches but I think this can also be a way better approach towards this given problem." }, { "code": null, "e": 624, "s": 607, "text": "What is mark.js?" }, { "code": null, "e": 855, "s": 624, "text": "mark.js is a simple JavaScript tool that is used to highlight the text. Which is used to dynamically mark search terms or custom regular expression and offer some built-in options like diacritics support, separate word search etc." }, { "code": null, "e": 865, "s": 855, "text": "Approach:" }, { "code": null, "e": 1195, "s": 865, "text": "First thing first when you are entering some string on the search box and press the search button then a simple JavaScript function will call named as highlight() which has the main role is to highlight the search text that you had entered in the search box. In this small, we are going to use mark.js code to highlight the text." }, { "code": null, "e": 1472, "s": 1195, "text": "There are many built-in functions in mark.js but we are using two functions for our requirement that is mark() and unmark() function respectively. Here mark() is used to highlight the search text and unmark() is used to remove highlighting the text that is highlighted before." }, { "code": null, "e": 1490, "s": 1472, "text": "Syntax of mark():" }, { "code": null, "e": 1606, "s": 1490, "text": "var context = document.querySelector(\".context\");\nvar obj = new Mark(context);\nobj.mark(searchkeyword [, options]);" }, { "code": null, "e": 1967, "s": 1606, "text": "Let’s understand this code in a bit of technical manner,First we declare a variable which contains context from which it is going to find and highlight the searched text. Create an object of the mark and then call the mark() method through the obj that you create previously.It takes two parameters with it i.e, one is searched keyword and another is optional." }, { "code": null, "e": 2083, "s": 1967, "text": "First we declare a variable which contains context from which it is going to find and highlight the searched text. " }, { "code": null, "e": 2188, "s": 2083, "text": "Create an object of the mark and then call the mark() method through the obj that you create previously." }, { "code": null, "e": 2274, "s": 2188, "text": "It takes two parameters with it i.e, one is searched keyword and another is optional." }, { "code": null, "e": 2294, "s": 2274, "text": "Syntax of unmark():" }, { "code": null, "e": 2394, "s": 2294, "text": "var context = document.querySelector(\".context\");\nvar obj = new Mark(context);\nobj.unmark(options);" }, { "code": null, "e": 2764, "s": 2394, "text": "This is near about same as the above technique but the only minute difference is that unmark() method takes only one argument with it i.e, optional. Further, if you want to change the color and padding of highlighter then we need to make slight changes in the CSS code inside mark which is given below:mark {\n color: black;\n background: green;\n padding: 5px;\n}" }, { "code": null, "e": 2832, "s": 2764, "text": "mark {\n color: black;\n background: green;\n padding: 5px;\n}" }, { "code": null, "e": 3259, "s": 2832, "text": "Hope you have successfully followed the above steps in order to make changes in the color of the particular highlighted text. But here make sure that there should not be any string left highlighted with any particular color if it is so then don’t forget to un-highlight the text which was searched previously. Thereafter, mark the new string which is to be searched and you can change its color according to your convenience. " }, { "code": null, "e": 3298, "s": 3259, "text": "For more information follow this page." }, { "code": null, "e": 3307, "s": 3298, "text": "Example:" }, { "code": null, "e": 3312, "s": 3307, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <!-- CDN of fontawsome --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"> <!-- CDN of Bootstrap --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css\" integrity=\"sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ\" crossorigin=\"anonymous\"> <!-- CDN of mark.js --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/mark.min.js\" integrity=\"sha512-5CYOlHXGh6QpOFA/TeTylKLWfB3ftPsde7AnmhuitiTX4K5SqCLBeKro6sPS8ilsz1Q4NRx3v8Ko2IBiszzdww==\" crossorigin=\"anonymous\"> </script> <!-- CDN of google font --> <style> @import url('https://fonts.googleapis.com/css2?family=Roboto+Slab:wght@500&display=swap' ); </style> <style> mark.a0 { color: black; padding: 5px; background: greenyellow; } mark.a1 { color: black; padding: 5px; background: cyan; } mark.a2 { color: black; padding: 5px; background: red; } mark.a3 { color: white; padding: 5px; background: green; } mark.a4 { color: black; padding: 5px; background: pink; } </style></head> <body style=\"border:4px solid rgb(0, 128, 28);\"> <h1 style=\"font-family: 'Roboto Slab', serif;text-align: center;color:green;\"> GeeksForGeeks </h1> <br><br> <form> <div class=\"container-fluid\" align=\"center\"> <input type=\"text\" size=\"30\" placeholder=\"search...\" id=\"searched\" style=\"border: 1px solid green; width:300px;height:30px;\"> <button type=\"button\" class=\"btn-primary btn-sm\" style=\"margin-left:-5px;height:32px;width:35px; background-color:rgb(12, 138, 12); border:0px;\" onclick=\"highlight('0');\"> <i class=\"fa fa-search\"></i> </button> </div> </form> <br><br> <div align=\"center\"> <div> <b><i>Choose the color of highlighter:</i></b> </div> <br> <div style=\"background-color: cyan; width: 20px; height: 20px; display: inline-block; margin-left: -30px;\" onmouseover=\"highlight('1')\"> </div> <div style=\"background-color: red; width: 20px; height: 20px; display: inline-block; margin-left: 10px;\" onmouseover=\"highlight('2')\"> </div> <div style=\"background-color: green; width: 20px; height: 20px; display: inline-block; margin-left: 10px;\" onmouseover=\"highlight('3')\"> </div> <div style=\"background-color: pink; width: 20px; height: 20px; display: inline-block; margin-left: 10px;\" onmouseover=\"highlight('4')\"> </div> </div> <div class=\"container-fluid\" style= \"padding-left: 30%; padding-right: 30%; padding-top: 5%;\"> <p class=\"select\"> GeeksforGeeks.org was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions.The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. </p> </div> <script> function highlight(param) { // Select the whole paragraph var ob = new Mark(document.querySelector(\".select\")); // First unmark the highlighted word or letter ob.unmark(); // Highlight letter or word ob.mark( document.getElementById(\"searched\").value, { className: 'a' + param } ); } </script></body> </html>", "e": 7548, "s": 3312, "text": null }, { "code": null, "e": 7556, "s": 7548, "text": "Output:" }, { "code": null, "e": 7565, "s": 7556, "text": "CSS-Misc" }, { "code": null, "e": 7575, "s": 7565, "text": "HTML-Misc" }, { "code": null, "e": 7591, "s": 7575, "text": "JavaScript-Misc" }, { "code": null, "e": 7598, "s": 7591, "text": "Picked" }, { "code": null, "e": 7622, "s": 7598, "text": "Technical Scripter 2020" }, { "code": null, "e": 7626, "s": 7622, "text": "CSS" }, { "code": null, "e": 7631, "s": 7626, "text": "HTML" }, { "code": null, "e": 7642, "s": 7631, "text": "JavaScript" }, { "code": null, "e": 7661, "s": 7642, "text": "Technical Scripter" }, { "code": null, "e": 7678, "s": 7661, "text": "Web Technologies" }, { "code": null, "e": 7683, "s": 7678, "text": "HTML" } ]
Java Program to Iterate Over Arrays Using for and foreach Loop
15 Sep, 2021 An array is a group of like-typed variables that are referred to by a common name. Arrays in Java work differently than they do in C/C++. Here, we have explained the for loop and foreach loop to display the elements of an array in Java. For-loop provides a concise way of writing the loop structure. A for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping. Syntax: for (initialization; test condition; increment/decrement) { // statements } Initialization: Executed before the execution of the code block. An already declared variable can be used or a variable can be declared, local to loop only. Test Condition: Testing the exit condition for a loop and return a boolean value. The test condition is checked prior to the execution of the loop statements. Statement execution: Once the condition is evaluated to true, the statements in the loop body are executed. Increment/ Decrement: It is used for updating the variable for the next iteration. Time Complexity: If the statements are O(1), the total time for the for loop: N*O(1), O(N) overall. For-each is an array traversing technique like for loop, while loop, do-while loop introduced in Java5. It starts with the keyword for like a normal for-loop.Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name.In the loop body, you can use the loop variable you created rather than using an indexed array element.It’s commonly used to iterate over an array or a Collections class (eg, ArrayList). It starts with the keyword for like a normal for-loop. Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name. In the loop body, you can use the loop variable you created rather than using an indexed array element. It’s commonly used to iterate over an array or a Collections class (eg, ArrayList). Syntax for (type var : array) { //statements } Time Complexity: O(n) where n is the number of elements iterated. Difference between for loop and for-each() loop in Java. For Loop For Each Loop 1. Increment/Decrement statement is required. e.g i=i+3 Iteration in List: Java // Java for and foreach loop in listimport java.util.ArrayList;import java.util.Arrays;import java.util.List; public class App { public static void main(String args[]) { // creating array list List<String> tech = new ArrayList<>(Arrays.asList( "Mac", "Samsung Gear ", "iPhone 12+")); // iterating over List using for loop System.out.println( "iterating over a List using for loop in Java:"); for (int i = 0; i < tech.size(); i++) { System.out.println(tech.get(i)); } // iterating over List using for Eachloop() System.out.println( "iterating over a List using forEach() loop in Java:"); for (String gadget : tech) { System.out.println(gadget); } }} iterating over a List using for loop in Java: Mac Samsung Gear iPhone 12+ iterating over a List using forEach() loop in Java: Mac Samsung Gear iPhone 12+ Iteration in an array: Java // Java Program for Iteration in Arraypublic class GFG { public static void main(String args[]) { // created array int[] element = {1, 9, 27, 28, 48}; // iterating over an array using for loop System.out.println( "iterating over an array using for loop in Java:"); for (int i = 0; i < element.length; i++) { System.out.println(element[i]); } // iterating over an array using forEach() loop System.out.println( "iterating over an array using forEach() loop in Java:"); for (int var : element) { // syntax forEach() loop // var is variable. System.out.println(var); } }} iterating over an array using for loop in Java: 1 9 27 28 48 iterating over an array using forEach() loop in Java: 1 9 27 28 48 akshaysingh98088 Java-Array-Programs Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Sep, 2021" }, { "code": null, "e": 265, "s": 28, "text": "An array is a group of like-typed variables that are referred to by a common name. Arrays in Java work differently than they do in C/C++. Here, we have explained the for loop and foreach loop to display the elements of an array in Java." }, { "code": null, "e": 485, "s": 265, "text": "For-loop provides a concise way of writing the loop structure. A for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping." }, { "code": null, "e": 493, "s": 485, "text": "Syntax:" }, { "code": null, "e": 604, "s": 493, "text": "for (initialization; test condition; \n increment/decrement)\n{\n // statements\n}" }, { "code": null, "e": 761, "s": 604, "text": "Initialization: Executed before the execution of the code block. An already declared variable can be used or a variable can be declared, local to loop only." }, { "code": null, "e": 920, "s": 761, "text": "Test Condition: Testing the exit condition for a loop and return a boolean value. The test condition is checked prior to the execution of the loop statements." }, { "code": null, "e": 1028, "s": 920, "text": "Statement execution: Once the condition is evaluated to true, the statements in the loop body are executed." }, { "code": null, "e": 1111, "s": 1028, "text": "Increment/ Decrement: It is used for updating the variable for the next iteration." }, { "code": null, "e": 1211, "s": 1111, "text": "Time Complexity: If the statements are O(1), the total time for the for loop: N*O(1), O(N) overall." }, { "code": null, "e": 1315, "s": 1211, "text": "For-each is an array traversing technique like for loop, while loop, do-while loop introduced in Java5." }, { "code": null, "e": 1757, "s": 1315, "text": "It starts with the keyword for like a normal for-loop.Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name.In the loop body, you can use the loop variable you created rather than using an indexed array element.It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)." }, { "code": null, "e": 1812, "s": 1757, "text": "It starts with the keyword for like a normal for-loop." }, { "code": null, "e": 2014, "s": 1812, "text": "Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name." }, { "code": null, "e": 2118, "s": 2014, "text": "In the loop body, you can use the loop variable you created rather than using an indexed array element." }, { "code": null, "e": 2202, "s": 2118, "text": "It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)." }, { "code": null, "e": 2209, "s": 2202, "text": "Syntax" }, { "code": null, "e": 2255, "s": 2209, "text": "for (type var : array) \n{ \n //statements\n}" }, { "code": null, "e": 2321, "s": 2255, "text": "Time Complexity: O(n) where n is the number of elements iterated." }, { "code": null, "e": 2378, "s": 2321, "text": "Difference between for loop and for-each() loop in Java." }, { "code": null, "e": 2387, "s": 2378, "text": "For Loop" }, { "code": null, "e": 2401, "s": 2387, "text": "For Each Loop" }, { "code": null, "e": 2447, "s": 2401, "text": "1. Increment/Decrement statement is required." }, { "code": null, "e": 2457, "s": 2447, "text": "e.g i=i+3" }, { "code": null, "e": 2476, "s": 2457, "text": "Iteration in List:" }, { "code": null, "e": 2481, "s": 2476, "text": "Java" }, { "code": "// Java for and foreach loop in listimport java.util.ArrayList;import java.util.Arrays;import java.util.List; public class App { public static void main(String args[]) { // creating array list List<String> tech = new ArrayList<>(Arrays.asList( \"Mac\", \"Samsung Gear \", \"iPhone 12+\")); // iterating over List using for loop System.out.println( \"iterating over a List using for loop in Java:\"); for (int i = 0; i < tech.size(); i++) { System.out.println(tech.get(i)); } // iterating over List using for Eachloop() System.out.println( \"iterating over a List using forEach() loop in Java:\"); for (String gadget : tech) { System.out.println(gadget); } }}", "e": 3268, "s": 2481, "text": null }, { "code": null, "e": 3428, "s": 3271, "text": "iterating over a List using for loop in Java:\nMac\nSamsung Gear \niPhone 12+\niterating over a List using forEach() loop in Java:\nMac\nSamsung Gear \niPhone 12+" }, { "code": null, "e": 3451, "s": 3428, "text": "Iteration in an array:" }, { "code": null, "e": 3458, "s": 3453, "text": "Java" }, { "code": "// Java Program for Iteration in Arraypublic class GFG { public static void main(String args[]) { // created array int[] element = {1, 9, 27, 28, 48}; // iterating over an array using for loop System.out.println( \"iterating over an array using for loop in Java:\"); for (int i = 0; i < element.length; i++) { System.out.println(element[i]); } // iterating over an array using forEach() loop System.out.println( \"iterating over an array using forEach() loop in Java:\"); for (int var : element) { // syntax forEach() loop // var is variable. System.out.println(var); } }}", "e": 4207, "s": 3458, "text": null }, { "code": null, "e": 4338, "s": 4210, "text": "iterating over an array using for loop in Java:\n1\n9\n27\n28\n48\niterating over an array using forEach() loop in Java:\n1\n9\n27\n28\n48" }, { "code": null, "e": 4357, "s": 4340, "text": "akshaysingh98088" }, { "code": null, "e": 4377, "s": 4357, "text": "Java-Array-Programs" }, { "code": null, "e": 4384, "s": 4377, "text": "Picked" }, { "code": null, "e": 4389, "s": 4384, "text": "Java" }, { "code": null, "e": 4403, "s": 4389, "text": "Java Programs" }, { "code": null, "e": 4408, "s": 4403, "text": "Java" } ]
C# | Abstraction
01 Oct, 2021 Data Abstraction is the property by virtue of which only the essential details are exhibited to the user. The trivial or the non-essentials units aren’t exhibited to the user. Data Abstraction may also be defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details. The properties and behaviors of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects. Example: Consider a real-life scenario of withdrawing money from ATM. The user only knows that in ATM machine first enter ATM card, then enter the pin code of ATM card, and then enter the amount which he/she wants to withdraw and at last, he/she gets their money. The user does not know about the inner mechanism of the ATM or the implementation of withdrawing money etc. The user just simply knows how to operate the ATM machine, this is called abstraction. In C# abstraction is achieved with the help of Abstract classes. Abstract Classes An abstract class is declared with the help of abstract keyword. In C#, you are not allowed to create objects of the abstract class. Or in other words, you cannot use the abstract class directly with the new operator. Class that contains the abstract keyword with some of its methods(not all abstract method) is known as an Abstract Base Class. Class that contains the abstract keyword with all of its methods is known as pure Abstract Base Class. You are not allowed to declare the abstract methods outside the abstract class. You are not allowed to declare an abstract class as Sealed Class. There are situations in which we want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. That is, sometimes we want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. Consider a classic “shape” example, perhaps used in a computer-aided design system or game simulation. The base type is “shape” and each shape has a color, size and so on. From this, specific types of shapes are derived(inherited)-circle, square, triangle, and so on – each of which may have additional characteristics and behaviors. For example, certain shapes can be flipped. Some behaviors may be different, such as when you want to calculate the area of a square. Example: C# // C# program to calculate the area// of a square using the concept of// data abstractionusing System; namespace Demoabstraction { // abstract classabstract class Shape { // abstract method public abstract int area();} // square class inheriting// the Shape classclass Square : Shape { // private data member private int side; // method of square class public Square(int x = 0) { side = x; } // overriding of the abstract method of Shape // class using the override keyword public override int area() { Console.Write("Area of Square: "); return (side * side); }} // Driver Classclass GFG { // Main Method static void Main(string[] args) { // creating reference of Shape class // which refer to Square class instance Shape sh = new Square(4); // calling the method double result = sh.area(); Console.Write("{0}", result); }}} Area of Square: 16 Encapsulation is data hiding(information hiding) while Abstraction is detail hiding(implementation hiding). While encapsulation groups together data and methods that act upon the data, data abstraction deal with exposing to the user and hiding the details of implementation. It reduces the complexity of viewing things. Avoids code duplication and increases reusability. Helps to increase the security of an application or program as only important details are provided to the user. gabaa406 CSharp-OOP C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Oct, 2021" }, { "code": null, "e": 520, "s": 52, "text": "Data Abstraction is the property by virtue of which only the essential details are exhibited to the user. The trivial or the non-essentials units aren’t exhibited to the user. Data Abstraction may also be defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details. The properties and behaviors of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects." }, { "code": null, "e": 979, "s": 520, "text": "Example: Consider a real-life scenario of withdrawing money from ATM. The user only knows that in ATM machine first enter ATM card, then enter the pin code of ATM card, and then enter the amount which he/she wants to withdraw and at last, he/she gets their money. The user does not know about the inner mechanism of the ATM or the implementation of withdrawing money etc. The user just simply knows how to operate the ATM machine, this is called abstraction." }, { "code": null, "e": 1044, "s": 979, "text": "In C# abstraction is achieved with the help of Abstract classes." }, { "code": null, "e": 1062, "s": 1044, "text": "Abstract Classes " }, { "code": null, "e": 1127, "s": 1062, "text": "An abstract class is declared with the help of abstract keyword." }, { "code": null, "e": 1280, "s": 1127, "text": "In C#, you are not allowed to create objects of the abstract class. Or in other words, you cannot use the abstract class directly with the new operator." }, { "code": null, "e": 1407, "s": 1280, "text": "Class that contains the abstract keyword with some of its methods(not all abstract method) is known as an Abstract Base Class." }, { "code": null, "e": 1510, "s": 1407, "text": "Class that contains the abstract keyword with all of its methods is known as pure Abstract Base Class." }, { "code": null, "e": 1590, "s": 1510, "text": "You are not allowed to declare the abstract methods outside the abstract class." }, { "code": null, "e": 1656, "s": 1590, "text": "You are not allowed to declare an abstract class as Sealed Class." }, { "code": null, "e": 2014, "s": 1656, "text": "There are situations in which we want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. That is, sometimes we want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details." }, { "code": null, "e": 2483, "s": 2014, "text": "Consider a classic “shape” example, perhaps used in a computer-aided design system or game simulation. The base type is “shape” and each shape has a color, size and so on. From this, specific types of shapes are derived(inherited)-circle, square, triangle, and so on – each of which may have additional characteristics and behaviors. For example, certain shapes can be flipped. Some behaviors may be different, such as when you want to calculate the area of a square. " }, { "code": null, "e": 2493, "s": 2483, "text": "Example: " }, { "code": null, "e": 2496, "s": 2493, "text": "C#" }, { "code": "// C# program to calculate the area// of a square using the concept of// data abstractionusing System; namespace Demoabstraction { // abstract classabstract class Shape { // abstract method public abstract int area();} // square class inheriting// the Shape classclass Square : Shape { // private data member private int side; // method of square class public Square(int x = 0) { side = x; } // overriding of the abstract method of Shape // class using the override keyword public override int area() { Console.Write(\"Area of Square: \"); return (side * side); }} // Driver Classclass GFG { // Main Method static void Main(string[] args) { // creating reference of Shape class // which refer to Square class instance Shape sh = new Square(4); // calling the method double result = sh.area(); Console.Write(\"{0}\", result); }}}", "e": 3482, "s": 2496, "text": null }, { "code": null, "e": 3501, "s": 3482, "text": "Area of Square: 16" }, { "code": null, "e": 3611, "s": 3503, "text": "Encapsulation is data hiding(information hiding) while Abstraction is detail hiding(implementation hiding)." }, { "code": null, "e": 3778, "s": 3611, "text": "While encapsulation groups together data and methods that act upon the data, data abstraction deal with exposing to the user and hiding the details of implementation." }, { "code": null, "e": 3823, "s": 3778, "text": "It reduces the complexity of viewing things." }, { "code": null, "e": 3874, "s": 3823, "text": "Avoids code duplication and increases reusability." }, { "code": null, "e": 3986, "s": 3874, "text": "Helps to increase the security of an application or program as only important details are provided to the user." }, { "code": null, "e": 3995, "s": 3986, "text": "gabaa406" }, { "code": null, "e": 4006, "s": 3995, "text": "CSharp-OOP" }, { "code": null, "e": 4009, "s": 4006, "text": "C#" } ]
Automating Machine Learning Workflows with Amazon Glue, Amazon SageMaker and AWS Step Functions Data Science SDK | by Olalekan Elesin | Towards Data Science
Automating machine learning workflows helps to build repeatable and reproducible machine learning models. It is a key step of in putting machine learning projects in production as we want to make sure our models are up-to-date and performant on new data. Amazon Glue, Amazon SageMaker and AWS Step Functions can help automate machine learning workflows from data processing to model deployment in a managed environment. In this post, I will use the AWS services mentioned above to develop and automate a machine learning workflow with PySpark on AWS Glue for data preparation and processing, and Amazon SageMaker for model training and batch predictions. The purpose of this is to show how engineers, and data scientists can quickly and easily create automated machine learning workflows. AWS Glue is a fully managed extract, transform, and load (ETL) service that makes it easy for customers to prepare and load their data for analytics. Amazon SageMaker is a fully managed service that enables data scientists to build, train, tune, and deploy machine learning models at any scale. This service provides a powerful and scalable compute environment that is also easy to use. Amazon Step Functions lets you coordinate multiple AWS services into serverless workflows so you can build and update apps quickly. AWS Step Functions Data Science SDK is an open source library that allows data scientists to easily create workflows that process and publish machine learning models using Amazon SageMaker and Amazon Step Functions. Orchestrating machine learning workflows is pivotal to productionizing ML. To this, I created a a simple end-to-end tutorial with AWS Step Functions and Amazon SageMaker using the AWS Data Science Step Functions SDK. You can find the full examples on the Amazon SageMaker Samples GitHub repository. In this post, we will follow the steps below to create a machine learning workflow: Write PySpark script for data processing on AWS Glue Train a model, using Amazon SageMaker XGboost Algorithm Deploy the model Make batch predictions with Amazon SageMaker Batch Transform To complete this example, I recommend that you launch an Amazon SageMaker Notebook instance by following the steps on the Amazon SageMaker workshop website. We also recommend you read how to create IAM roles and permissions required for running Amazon Glue Jobs. I assume you are already familiar with writing PySpark jobs. This example touches on the Glue basics, for more complex data transformations kindly read up on Amazon Glue and PySpark. The code snippet below shows simple data transformations in AWS Glue. After creating the PySpark script, the script has to be uploaded to an S3 location which is accessible to Amazon Glue: $ aws s3 cp glue-etl-processing.py s3://my-code-bucket/glue/glue-etl-processing.py Once the above are completed successfully, we will use the AWS Python SDK, Boto3, to create a Glue job. See example below: In this post, we will use the Amazon SageMaker built-in XGBoost algorithm to train and host a regression model. The dataset is from the Video Game Sales Prediction Amazon SageMaker Workshop example. However, we will not delve into the complete details, since they are available on the Amazon SageMaker Workshop Website. To prepare the workflow, I will use the AWS Step Functions Data Science SDK which makes it easier and quicker to create step function state machines on AWS. In the steps below, I will show how to create a Glue step for data processing, Amazon SageMaker model training and deployment steps, and Amazon SageMaker Batch Transform step. Finally, we will chain these steps together to create a workflow which is then executed with AWS Step Functions. Glue Job Step Amazon SageMaker Estimator and Train Step Finally, let’s chain the steps together to create a workflow In this tutorial, we demonstrated how run orchestrate batch inference machine learning learning pipeline with AWS Step Functions SDK, starting from data processing with Amazon Glue for PySpark to model creation and batch inference on Amazon SageMaker. In this example, I demonstrated how you can create a machine learning workflow using Amazon Step Functions. You could automate model retraining with Amazon CloudWatch Scheduled events. Since, you could be making batch predictions daily, you could prepare your data with AWS Glue, run batch predictions and chain the entire step together with the Step Functions SDK. You could also add an SNSStep so that you get notified via email, slack or SMS on the status of your ML workflows. Many possibilities... Amazon Step Functions Amazon Step Functions Developer Guide AWS Step Functions Data Science SDK Amazon Glue Kindly share your thoughts and comments — looking forward to your feedback. You can reach me via email, follow me on Twitter or connect with me on LinkedIn. Can’t wait to hear from you!!
[ { "code": null, "e": 592, "s": 172, "text": "Automating machine learning workflows helps to build repeatable and reproducible machine learning models. It is a key step of in putting machine learning projects in production as we want to make sure our models are up-to-date and performant on new data. Amazon Glue, Amazon SageMaker and AWS Step Functions can help automate machine learning workflows from data processing to model deployment in a managed environment." }, { "code": null, "e": 961, "s": 592, "text": "In this post, I will use the AWS services mentioned above to develop and automate a machine learning workflow with PySpark on AWS Glue for data preparation and processing, and Amazon SageMaker for model training and batch predictions. The purpose of this is to show how engineers, and data scientists can quickly and easily create automated machine learning workflows." }, { "code": null, "e": 1111, "s": 961, "text": "AWS Glue is a fully managed extract, transform, and load (ETL) service that makes it easy for customers to prepare and load their data for analytics." }, { "code": null, "e": 1348, "s": 1111, "text": "Amazon SageMaker is a fully managed service that enables data scientists to build, train, tune, and deploy machine learning models at any scale. This service provides a powerful and scalable compute environment that is also easy to use." }, { "code": null, "e": 1480, "s": 1348, "text": "Amazon Step Functions lets you coordinate multiple AWS services into serverless workflows so you can build and update apps quickly." }, { "code": null, "e": 1696, "s": 1480, "text": "AWS Step Functions Data Science SDK is an open source library that allows data scientists to easily create workflows that process and publish machine learning models using Amazon SageMaker and Amazon Step Functions." }, { "code": null, "e": 1995, "s": 1696, "text": "Orchestrating machine learning workflows is pivotal to productionizing ML. To this, I created a a simple end-to-end tutorial with AWS Step Functions and Amazon SageMaker using the AWS Data Science Step Functions SDK. You can find the full examples on the Amazon SageMaker Samples GitHub repository." }, { "code": null, "e": 2079, "s": 1995, "text": "In this post, we will follow the steps below to create a machine learning workflow:" }, { "code": null, "e": 2132, "s": 2079, "text": "Write PySpark script for data processing on AWS Glue" }, { "code": null, "e": 2188, "s": 2132, "text": "Train a model, using Amazon SageMaker XGboost Algorithm" }, { "code": null, "e": 2205, "s": 2188, "text": "Deploy the model" }, { "code": null, "e": 2266, "s": 2205, "text": "Make batch predictions with Amazon SageMaker Batch Transform" }, { "code": null, "e": 2529, "s": 2266, "text": "To complete this example, I recommend that you launch an Amazon SageMaker Notebook instance by following the steps on the Amazon SageMaker workshop website. We also recommend you read how to create IAM roles and permissions required for running Amazon Glue Jobs." }, { "code": null, "e": 2782, "s": 2529, "text": "I assume you are already familiar with writing PySpark jobs. This example touches on the Glue basics, for more complex data transformations kindly read up on Amazon Glue and PySpark. The code snippet below shows simple data transformations in AWS Glue." }, { "code": null, "e": 2901, "s": 2782, "text": "After creating the PySpark script, the script has to be uploaded to an S3 location which is accessible to Amazon Glue:" }, { "code": null, "e": 2984, "s": 2901, "text": "$ aws s3 cp glue-etl-processing.py s3://my-code-bucket/glue/glue-etl-processing.py" }, { "code": null, "e": 3107, "s": 2984, "text": "Once the above are completed successfully, we will use the AWS Python SDK, Boto3, to create a Glue job. See example below:" }, { "code": null, "e": 3427, "s": 3107, "text": "In this post, we will use the Amazon SageMaker built-in XGBoost algorithm to train and host a regression model. The dataset is from the Video Game Sales Prediction Amazon SageMaker Workshop example. However, we will not delve into the complete details, since they are available on the Amazon SageMaker Workshop Website." }, { "code": null, "e": 3873, "s": 3427, "text": "To prepare the workflow, I will use the AWS Step Functions Data Science SDK which makes it easier and quicker to create step function state machines on AWS. In the steps below, I will show how to create a Glue step for data processing, Amazon SageMaker model training and deployment steps, and Amazon SageMaker Batch Transform step. Finally, we will chain these steps together to create a workflow which is then executed with AWS Step Functions." }, { "code": null, "e": 3887, "s": 3873, "text": "Glue Job Step" }, { "code": null, "e": 3929, "s": 3887, "text": "Amazon SageMaker Estimator and Train Step" }, { "code": null, "e": 3990, "s": 3929, "text": "Finally, let’s chain the steps together to create a workflow" }, { "code": null, "e": 4242, "s": 3990, "text": "In this tutorial, we demonstrated how run orchestrate batch inference machine learning learning pipeline with AWS Step Functions SDK, starting from data processing with Amazon Glue for PySpark to model creation and batch inference on Amazon SageMaker." }, { "code": null, "e": 4745, "s": 4242, "text": "In this example, I demonstrated how you can create a machine learning workflow using Amazon Step Functions. You could automate model retraining with Amazon CloudWatch Scheduled events. Since, you could be making batch predictions daily, you could prepare your data with AWS Glue, run batch predictions and chain the entire step together with the Step Functions SDK. You could also add an SNSStep so that you get notified via email, slack or SMS on the status of your ML workflows. Many possibilities..." }, { "code": null, "e": 4767, "s": 4745, "text": "Amazon Step Functions" }, { "code": null, "e": 4805, "s": 4767, "text": "Amazon Step Functions Developer Guide" }, { "code": null, "e": 4841, "s": 4805, "text": "AWS Step Functions Data Science SDK" }, { "code": null, "e": 4853, "s": 4841, "text": "Amazon Glue" } ]
Array element moved by k using single moves - GeeksforGeeks
09 May, 2022 Given a list of n integers containing numbers 1-n in a shuffled way and a integer K. N people are standing in a queue to play badminton. At first, the first two players in the queue play a game. Then the loser goes to the end of the queue, and the one who wins plays with the next person from the line, and so on. They play until someone wins k games consecutively. This player becomes the winner. Examples : Input: arr[] = {2, 1, 3, 4, 5} k = 2 Output: 5 Explanation: 2 plays with 1, 1 goes to end of queue. 2 plays with 3, 3 wins, 2 goes to end of queue. 3 plays with 4, so 3 goes to the end of the queue. 5 plays with everyone and wins as it is the largest of all elements. Input: arr[] = {3, 1, 2} k = 2 Output: 3 Explanation : 3 plays with 1. 3 wins. 1 goes to the end of the line. 3 plays with 2. 3 wins. 3 wins twice in a row. A naive approach is to run two nested for loops and check for every element which one is more from i to n being the first loop and the second being from i+1 to n and then from 0 to n-1 and count the number of continuous smaller elements and get the answer. This will not be efficient enough as it takes O(n*n) . An efficient approach will be to run a loop from 1 to n and keep track of best (or maximum element) so far and number of smaller elements than this maximum. If current best loose, initialize the greater value to the best and the count to 1, as the winner won 1 time already. If at any step it has won k times, you get your answer. But if k >= n-1, then the maximum number will be the only answer as it will the most number of times being the greatest. If while iterating you don’t find any player that has won k times, then the maximum number which is in the list will always be our answer. Below is the implementation to the above approach C++ Java Python3 C# PHP Javascript // C++ program to find winner of game#include <iostream>using namespace std; int winner(int a[], int n, int k){ // if the number of steps is more than // n-1, if (k >= n - 1) return n; // initially the best is 0 and no of // wins is 0. int best = 0, times = 0; // traverse through all the numbers for (int i = 0; i < n; i++) { // if the value of array is more // than that of previous best if (a[i] > best) { // best is replaced by a[i] best = a[i]; // if not the first index if (i) times = 1; // no of wins is 1 now } else times += 1; // if it wins // if any position has more than k wins // then return if (times >= k) return best; } // Maximum element will be winner because // we move smaller element at end and repeat // the process. return best;} // driver program to test the above functionint main(){ int a[] = { 2, 1, 3, 4, 5 }; int n = sizeof(a) / sizeof(a[0]); int k = 2; cout << winner(a, n, k); return 0;} // Java program to find winner of gameimport java.io.*; class GFG { static int winner(int a[], int n, int k) { // if the number of steps is more than // n-1, if (k >= n - 1) return n; // initially the best is 0 and no of // wins is 0. int best = 0, times = 0; // traverse through all the numbers for (int i = 0; i < n; i++) { // if the value of array is more // than that of previous best if (a[i] > best) { // best is replaced by a[i] best = a[i]; // if not the first index if (i == 1) // no of wins is 1 now times = 1; } else // if it wins times += 1; // if any position has more than // k wins then return if (times >= k) return best; } // Maximum element will be winner // because we move smaller element // at end and repeat the process. return best; } // driver program to test the above function public static void main(String args[]) { int a[] = { 2, 1, 3, 4, 5 }; int n = a.length; int k = 2; System.out.println(winner(a, n, k)); }} /*This code is contributed by Nikita Tiwari.*/ # Python3 code to find# winner of game # function to find the winnerdef winner( a, n, k): # if the number of steps is # more than n-1 if k >= n - 1: return n # initially the best is 0 # and no of wins is 0. best = 0 times = 0 # traverse through all the numbers for i in range(n): # if the value of array is more # than that of previous best if a[i] > best: # best is replaced by a[i] best = a[i] # if not the first index if i == True: # no of wins is 1 now times = 1 else: times += 1 # if it wins # if any position has more # than k wins then return if times >= k: return best # Maximum element will be winner # because we move smaller element # at end and repeat the process. return best # driver codea = [ 2, 1, 3, 4, 5 ]n = len(a)k = 2print(winner(a, n, k)) # This code is contributed by "Abhishek Sharma 44" // C# program to find winner of gameusing System; class GFG { static int winner(int[] a, int n, int k) { // if the number of steps is more // than n-1, if (k >= n - 1) return n; // initially the best is 0 and no of // wins is 0. int best = 0, times = 0; // traverse through all the numbers for (int i = 0; i < n; i++) { // if the value of array is more // than that of previous best if (a[i] > best) { // best is replaced by a[i] best = a[i]; // if not the first index if (i == 1) // no of wins is 1 now times = 1; } else // if it wins times += 1; // if any position has more // than k wins then return if (times >= k) return best; } // Maximum element will be winner // because we move smaller element // at end and repeat the process. return best; } // driver program to test the above // function public static void Main() { int[] a = { 2, 1, 3, 4, 5 }; int n = a.Length; int k = 2; Console.WriteLine(winner(a, n, k)); }} // This code is contributed by vt_m. <?php// PHP program to find winner of game function winner($a, $n, $k){ // if the number of steps // is more than n-1, if ($k >= $n - 1) return $n; // initially the best is 0 // and no. of wins is 0. $best = 0; $times = 0; // traverse through all the numbers for ($i = 0; $i < $n; $i++) { // if the value of array is more // than that of previous best if ($a[$i] > $best) { // best is replaced by a[i] $best = $a[$i]; // if not the first index if ($i) // no of wins is 1 now $times = 1; } else // if it wins $times += 1; // if any position has more than // k wins then return if ($times >= $k) return $best; } // Maximum element will be winner // because we move smaller element // at end and repeat the process. return $best;} // Driver Code$a = array( 2, 1, 3, 4, 5 );$n = sizeof($a);$k = 2;echo(winner($a, $n, $k)); // This code is contributed by Ajit.?> <script> // Javascript program to find winner of game function winner(a, n, k){ // If the number of steps is more than // n-1, if (k >= n - 1) return n; // Initially the best is 0 and no of // wins is 0. let best = 0, times = 0; // Traverse through all the numbers for(let i = 0; i < n; i++) { // If the value of array is more // than that of previous best if (a[i] > best) { // best is replaced by a[i] best = a[i]; // If not the first index if (i) // No of wins is 1 now times = 1; } else // If it wins times += 1; // If any position has more // than k wins then return if (times >= k) return best; } // Maximum element will be winner because // we move smaller element at end and repeat // the process. return best;} // Driver codelet a = [ 2, 1, 3, 4, 5 ];let n = a.length;let k = 2; document.write(winner(a, n, k)); // This code is contributed by Mayank Tyagi </script> Output : 5 Time complexity : O(n) vt_m jit_t mayanktyagi1709 simmytarika5 surinderdawra388 Arrays Greedy Arrays Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Huffman Coding | Greedy Algo-3 Write a program to print all permutations of a given string
[ { "code": null, "e": 26615, "s": 26587, "text": "\n09 May, 2022" }, { "code": null, "e": 27013, "s": 26615, "text": "Given a list of n integers containing numbers 1-n in a shuffled way and a integer K. N people are standing in a queue to play badminton. At first, the first two players in the queue play a game. Then the loser goes to the end of the queue, and the one who wins plays with the next person from the line, and so on. They play until someone wins k games consecutively. This player becomes the winner." }, { "code": null, "e": 27026, "s": 27013, "text": "Examples : " }, { "code": null, "e": 27475, "s": 27026, "text": "Input: arr[] = {2, 1, 3, 4, 5}\n k = 2 \nOutput: 5 \nExplanation: \n2 plays with 1, 1 goes to end of queue.\n2 plays with 3, 3 wins, 2 goes to end of queue.\n3 plays with 4, so 3 goes to the end of the queue.\n5 plays with everyone and wins as it is the \nlargest of all elements.\n\nInput: arr[] = {3, 1, 2} \n k = 2\nOutput: 3\nExplanation : \n3 plays with 1. 3 wins. 1 goes to the end of the line. \n3 plays with 2. 3 wins. 3 wins twice in a row." }, { "code": null, "e": 27787, "s": 27475, "text": "A naive approach is to run two nested for loops and check for every element which one is more from i to n being the first loop and the second being from i+1 to n and then from 0 to n-1 and count the number of continuous smaller elements and get the answer. This will not be efficient enough as it takes O(n*n) ." }, { "code": null, "e": 28378, "s": 27787, "text": "An efficient approach will be to run a loop from 1 to n and keep track of best (or maximum element) so far and number of smaller elements than this maximum. If current best loose, initialize the greater value to the best and the count to 1, as the winner won 1 time already. If at any step it has won k times, you get your answer. But if k >= n-1, then the maximum number will be the only answer as it will the most number of times being the greatest. If while iterating you don’t find any player that has won k times, then the maximum number which is in the list will always be our answer." }, { "code": null, "e": 28430, "s": 28378, "text": "Below is the implementation to the above approach " }, { "code": null, "e": 28434, "s": 28430, "text": "C++" }, { "code": null, "e": 28439, "s": 28434, "text": "Java" }, { "code": null, "e": 28447, "s": 28439, "text": "Python3" }, { "code": null, "e": 28450, "s": 28447, "text": "C#" }, { "code": null, "e": 28454, "s": 28450, "text": "PHP" }, { "code": null, "e": 28465, "s": 28454, "text": "Javascript" }, { "code": "// C++ program to find winner of game#include <iostream>using namespace std; int winner(int a[], int n, int k){ // if the number of steps is more than // n-1, if (k >= n - 1) return n; // initially the best is 0 and no of // wins is 0. int best = 0, times = 0; // traverse through all the numbers for (int i = 0; i < n; i++) { // if the value of array is more // than that of previous best if (a[i] > best) { // best is replaced by a[i] best = a[i]; // if not the first index if (i) times = 1; // no of wins is 1 now } else times += 1; // if it wins // if any position has more than k wins // then return if (times >= k) return best; } // Maximum element will be winner because // we move smaller element at end and repeat // the process. return best;} // driver program to test the above functionint main(){ int a[] = { 2, 1, 3, 4, 5 }; int n = sizeof(a) / sizeof(a[0]); int k = 2; cout << winner(a, n, k); return 0;}", "e": 29590, "s": 28465, "text": null }, { "code": "// Java program to find winner of gameimport java.io.*; class GFG { static int winner(int a[], int n, int k) { // if the number of steps is more than // n-1, if (k >= n - 1) return n; // initially the best is 0 and no of // wins is 0. int best = 0, times = 0; // traverse through all the numbers for (int i = 0; i < n; i++) { // if the value of array is more // than that of previous best if (a[i] > best) { // best is replaced by a[i] best = a[i]; // if not the first index if (i == 1) // no of wins is 1 now times = 1; } else // if it wins times += 1; // if any position has more than // k wins then return if (times >= k) return best; } // Maximum element will be winner // because we move smaller element // at end and repeat the process. return best; } // driver program to test the above function public static void main(String args[]) { int a[] = { 2, 1, 3, 4, 5 }; int n = a.length; int k = 2; System.out.println(winner(a, n, k)); }} /*This code is contributed by Nikita Tiwari.*/", "e": 30974, "s": 29590, "text": null }, { "code": "# Python3 code to find# winner of game # function to find the winnerdef winner( a, n, k): # if the number of steps is # more than n-1 if k >= n - 1: return n # initially the best is 0 # and no of wins is 0. best = 0 times = 0 # traverse through all the numbers for i in range(n): # if the value of array is more # than that of previous best if a[i] > best: # best is replaced by a[i] best = a[i] # if not the first index if i == True: # no of wins is 1 now times = 1 else: times += 1 # if it wins # if any position has more # than k wins then return if times >= k: return best # Maximum element will be winner # because we move smaller element # at end and repeat the process. return best # driver codea = [ 2, 1, 3, 4, 5 ]n = len(a)k = 2print(winner(a, n, k)) # This code is contributed by \"Abhishek Sharma 44\"", "e": 32067, "s": 30974, "text": null }, { "code": "// C# program to find winner of gameusing System; class GFG { static int winner(int[] a, int n, int k) { // if the number of steps is more // than n-1, if (k >= n - 1) return n; // initially the best is 0 and no of // wins is 0. int best = 0, times = 0; // traverse through all the numbers for (int i = 0; i < n; i++) { // if the value of array is more // than that of previous best if (a[i] > best) { // best is replaced by a[i] best = a[i]; // if not the first index if (i == 1) // no of wins is 1 now times = 1; } else // if it wins times += 1; // if any position has more // than k wins then return if (times >= k) return best; } // Maximum element will be winner // because we move smaller element // at end and repeat the process. return best; } // driver program to test the above // function public static void Main() { int[] a = { 2, 1, 3, 4, 5 }; int n = a.Length; int k = 2; Console.WriteLine(winner(a, n, k)); }} // This code is contributed by vt_m.", "e": 33436, "s": 32067, "text": null }, { "code": "<?php// PHP program to find winner of game function winner($a, $n, $k){ // if the number of steps // is more than n-1, if ($k >= $n - 1) return $n; // initially the best is 0 // and no. of wins is 0. $best = 0; $times = 0; // traverse through all the numbers for ($i = 0; $i < $n; $i++) { // if the value of array is more // than that of previous best if ($a[$i] > $best) { // best is replaced by a[i] $best = $a[$i]; // if not the first index if ($i) // no of wins is 1 now $times = 1; } else // if it wins $times += 1; // if any position has more than // k wins then return if ($times >= $k) return $best; } // Maximum element will be winner // because we move smaller element // at end and repeat the process. return $best;} // Driver Code$a = array( 2, 1, 3, 4, 5 );$n = sizeof($a);$k = 2;echo(winner($a, $n, $k)); // This code is contributed by Ajit.?>", "e": 34543, "s": 33436, "text": null }, { "code": "<script> // Javascript program to find winner of game function winner(a, n, k){ // If the number of steps is more than // n-1, if (k >= n - 1) return n; // Initially the best is 0 and no of // wins is 0. let best = 0, times = 0; // Traverse through all the numbers for(let i = 0; i < n; i++) { // If the value of array is more // than that of previous best if (a[i] > best) { // best is replaced by a[i] best = a[i]; // If not the first index if (i) // No of wins is 1 now times = 1; } else // If it wins times += 1; // If any position has more // than k wins then return if (times >= k) return best; } // Maximum element will be winner because // we move smaller element at end and repeat // the process. return best;} // Driver codelet a = [ 2, 1, 3, 4, 5 ];let n = a.length;let k = 2; document.write(winner(a, n, k)); // This code is contributed by Mayank Tyagi </script>", "e": 35696, "s": 34543, "text": null }, { "code": null, "e": 35706, "s": 35696, "text": "Output : " }, { "code": null, "e": 35708, "s": 35706, "text": "5" }, { "code": null, "e": 35732, "s": 35708, "text": "Time complexity : O(n) " }, { "code": null, "e": 35737, "s": 35732, "text": "vt_m" }, { "code": null, "e": 35743, "s": 35737, "text": "jit_t" }, { "code": null, "e": 35759, "s": 35743, "text": "mayanktyagi1709" }, { "code": null, "e": 35772, "s": 35759, "text": "simmytarika5" }, { "code": null, "e": 35789, "s": 35772, "text": "surinderdawra388" }, { "code": null, "e": 35796, "s": 35789, "text": "Arrays" }, { "code": null, "e": 35803, "s": 35796, "text": "Greedy" }, { "code": null, "e": 35810, "s": 35803, "text": "Arrays" }, { "code": null, "e": 35817, "s": 35810, "text": "Greedy" }, { "code": null, "e": 35915, "s": 35817, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35983, "s": 35915, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 36006, "s": 35983, "text": "Introduction to Arrays" }, { "code": null, "e": 36038, "s": 36006, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 36052, "s": 36038, "text": "Linear Search" }, { "code": null, "e": 36073, "s": 36052, "text": "Linked List vs Array" }, { "code": null, "e": 36124, "s": 36073, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 36182, "s": 36124, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 36233, "s": 36182, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 36264, "s": 36233, "text": "Huffman Coding | Greedy Algo-3" } ]
Bootstrap Confidence intervals for performance metrics in Machine Learning | by David B Rosen | Towards Data Science
If you report your classifier’s performance as having Accuracy=94.8% and F1=92.3% on a test set, this doesn’t mean much without knowing something about the size and composition of the test set. The margin of error of those performance measurements will vary a lot depending on the size of the test set, or, for an imbalanced dataset, primarily depending on how many independent instances of the minority class it contains (more copies of the same instances from oversampling doesn’t help for this purpose). If you were able to collect another, independent test set of similar origin, the Accuracy and F1 of your model on this dataset are unlikely to be the same, but how much different might they plausibly be? A question similar to this is answered in statistics as the confidence interval of the measurement. If we were to draw many independent sample datasets from the underlying population, then for 95% of those datasets, the true underlying population value of the metric would be within the 95% confidence interval that we would calculate for that particular sample dataset. In this article we will show you how to calculate confidence intervals for any number of Machine Learning performance metrics at once, with a bootstrap method that automatically determines how many boot sample datasets to generate by default. If you just want to see how to invoke this code to calculate confidence intervals, skip to the section “Calculate the results!” down below. If we were able to draw additional test datasets from the true distribution underlying the data, we would be able to see the distribution of the performance metric(s) of interest across those datasets. (When drawing those datasets we would not do anything to prevent drawing an identical or similar instance multiple times, although this might only happen rarely.) Since we can’t do that, the next best thing is to draw additional datasets from the empirical distribution of this test dataset, which means sampling, with replacement, from its instances to generate new bootstrap sample datasets. Sampling with replacement means once we draw a particular instance, we put it back in so that we might draw it again for the same sample dataset. Therefore, each such dataset generally has multiple copies of some of the instances, and does not include all of the instances that are in the base test set. If we sampled without replacement, then we would simply get an identical copy of the original dataset every time, shuffled in a different random order, which would not be of any use. The percentile bootstrap methodology for estimating the confidence interval is as follows: Generate nboots “bootstrap sample” datasets, each the same size as the original test set. Each sample dataset is obtained by drawing instances at random from the test set with replacement.On each of the sample datasets, calculate the metric and save it.The 95% confidence interval is given by the 2.5th to the 97.5th percentile among the nboots calculated values of the metric. If nboots=1001 and you sorted the values in a series/array/list X of length 1001, the 0th percentile is X[0] and the 100th percentile is X[1000], so the confidence interval would be given by X[25] to X[975]. Generate nboots “bootstrap sample” datasets, each the same size as the original test set. Each sample dataset is obtained by drawing instances at random from the test set with replacement. On each of the sample datasets, calculate the metric and save it. The 95% confidence interval is given by the 2.5th to the 97.5th percentile among the nboots calculated values of the metric. If nboots=1001 and you sorted the values in a series/array/list X of length 1001, the 0th percentile is X[0] and the 100th percentile is X[1000], so the confidence interval would be given by X[25] to X[975]. Of course you can calculate as many metrics as you like for each sample dataset in step 2, but in step 3 you would find the percentiles for each metric separately. We will use results from this prior article as an example: How To Deal With Imbalanced Classification, Without Re-balancing the Data: Before considering oversampling your skewed data, try adjusting your classification decision threshold. In that article we used the highly-imbalanced two-class Kaggle credit card fraud identification data set. We chose to use a classification threshold quite different from the default 0.5 threshold that is implicit in using the predict() method, making it unnecessary to balance the data. This approach is sometimes termed threshold moving, in which our classifier assigns the class by applying the chosen threshold to the predicted class probability provided by the predict_proba() method. We will limit the scope of this article (and code) to binary classification: classes 0 and 1, with class 1 by convention being the “positive” class and specifically the minority class for imbalanced data, although the code should work for regression (single continuous target) as well. Although our confidence interval code can handle various numbers of data arguments to be passed to the metric functions, we will focus on sklearn-style metrics, which always accept two data arguments, y_true and y_pred, where y_pred will be either binary class predictions (0 or 1), or continuous class-probability or decision function predictions, or even continuous regression predictions if y_true is continuous as well. The following function generates a single boot sample dataset. It accepts any data_args but in our case these arguments will be ytest(our actual/true test set target values in the prior article) and hardpredtst_tuned_thresh (the predicted class). Both contain zeros and ones to indicate the true or predicted class for each instance. We will define a custom metric function for Specificity, which is just another name for the Recall of the negative class (class 0). Also a calc_metrics function which which applies a sequence of metrics of interest to our data, and a couple of utility functions for it: Here we make our list of metrics and apply them to the data. We did not consider Accuracy to be a relevant metric because a false negative (misclassifying a true fraud as legit) is much more costly to the business than a false positive (misclassifying a true legit as a fraud), whereas Accuracy treats both types of misclassification are equally bad and therefore favors correctly-classifying those whose true class is the majority class because these occur much more often and so contribute much more to the overall Accuracy. met=[ metrics.recall_score, specificity_score, metrics.balanced_accuracy_score ]calc_metrics(met, ytest, hardpredtst_tuned_thresh) In raw_metric_samples() we will actually generate multiple sample datasets one by one and save the metrics of each: You give raw_metric_samples() a list of metrics (or just one metric) of interest as well as the true and predicted class data, and it obtains nboots sample datasets and returns a dataframe with just the metrics’ values calculated from each dataset. Through _boot_generator() it invokes one_boot() one at a time in a generator expression rather than storing all the datasets at once as a potentially-huge list. We make our list of metric functions and invoke raw_metric_samples() to get the results for just 7 sample datasets. We are invoking raw_metric_samples() here for understanding — it is not necessary in order to get confidence intervals using ci_auto() below, although specifying a list of metrics (or just one metric) for ci_auto() is necessary. np.random.seed(13)raw_metric_samples(met, ytest, hardpredtst_tuned_thresh, nboots=7).style.format('{:.2%}') #optional #style Each column above contains the metrics calculated from one boot sample dataset (numbered 0 to 6), so the calculated metric values vary due to the random sampling. In our implementation, by default the number of boot datasets nboots will be calculated automatically from the desired confidence level (e.g. 95%) so as to meet the recommendation by North, Curtis, and Sham to have a minimum number of boot results in each tail of the distribution. (Actually this recommendation applies to p-values and thus hypothesis test acceptance regions, but confidence intervals are similar enough to those to use this as a rule of thumb.) Although those authors recommend a minimum of 10 boot results in the tail, Davidson & MacKinnon recommend at least 399 boots for 95% confidence, which requires 11 boots in the tail, so we use this more-conservative recommendation. We specify alpha which is 1 − confidence level. E.g. 95% confidence becomes 0.95 and alpha=0.05. If you specify an explicit number of boots (perhaps a smaller nboots because you want faster results) but it is not enough for your requested alpha, a higher alpha will be chosen automatically in order to get an accurate confidence interval for that number of boots. A minimum of 51 boots will be used because any less can only accurately calculate bizarrely-small confidence levels (such as 40% confidence which gives an interval from the 30th percentile to the 70th percentile, which has 40% inside the interval but 60% outside it) and it is not clear that the minimum-boots recommendation even contemplated such a case. The function get_alpha_nboots() sets the default nboots or modifies the requested alpha and nboots per above: Let’s show the default nboots for various values of alpha: g = get_alpha_nboots pd.DataFrame( [ g(0.40), g(0.20, None), g(0.10), g(), g(alpha=0.02), g(alpha=0.01, nboots=None), g(0.005, nboots=None) ], columns=['alpha', 'default nboots'] ).set_index('alpha') Here’s what happens if we request an explicit nboots: req=[(0.01,3000), (0.01,401), (0.01,2)]out=[get_alpha_nboots(*args) for args in req]mydf = lambda x: pd.DataFrame(x, columns=['alpha', 'nboots'])pd.concat([mydf(req),mydf(out)],axis=1, keys=('Requested','Using')) Small nboots values increased alpha to 0.05 and 0.40, and nboots=2 gets changed to the minimum of 51. Again we don’t need to do this in order to get the confidence intervals below by invoking ci_auto(). np.random.seed(13)metric_boot_histogram\ (metrics.balanced_accuracy_score, ytest, hardpredtst_tuned_thresh) Here is the main function that invokes the above and calculates the confidence intervals from the percentiles of the metric results, and inserts the point estimates as the first column of its output dataframe of results. This is all we really needed to do: invoke ci_auto() as follows with a list of metrics (met assigned above) to get their confidence intervals. The percentage formatting is optional: np.random.seed(13)ci_auto( met, ytest, hardpredtst_tuned_thresh ).style.format('{:.2%}') Here’s the confusion matrix from the original article. Class 0 is the negatives (majority class) and Class 1 is the positives (very rare class) The Recall (True Positive Rate) of 134/(134+14) has the widest confidence interval because this is a binomial proportion involving small counts. The Specificity (True Negative Rate) is 80,388/(80,388+4,907), which involves much larger counts, so it has an extremely narrow confidence interval of just [94.11% to 94.40%]. Since the Balanced Accuracy is calculated as simply an average of the Recall and the Specificity, the width of its confidence interval is intermediate between theirs’. Here we have not considered the variability in the model based on the randomness of our training data (although that can also be of interest for some purposes, e.g. if you have automated repeated re-training and want to know how much the performance of future models might vary), but rather only the variability in the measurement of the performance of this particular model (created from some particular training data) due to the randomness of our test data. If we had enough independent test data, we could measure the performance of this particular model on the underlying population very precisely, and we would know how it will perform if this model is deployed, irrespective of how we built the model and of whether we might obtain a better or worse model with a different training sample dataset. The bootstrap method assumes that each of your instances (cases, observations) is drawn independently from an underlying population. If your test set has groups of rows that are not independent of each other, for example repeated observations of the same entity that are likely to be correlated with one another, or instances that are oversampled/replicated/generated-from other instances in your test set, the results might not be valid. You might need to use grouped sampling, where you draw entire groups together at random rather than individual rows, while avoiding breaking up any group or just using part of it. Also you want to make sure you don’t have groups that were split across the training and test set, because then the test set is not necessarily independent and you might get undetected overfitting. For example if you use oversampling you should generally only do only after it has been split from the test set, not before. And normally you would oversample the training set but not the test set, since the test set must remain representative of instances the model will see upon future deployment. And for cross-validation you would want to use scikit-learn’s model_selection.GroupKFold(). You can always calculate confidence intervals for your evaluation metric(s) to see how precisely your test data enables you to measure your model’s performance. I’m planning another article to demonstrate confidence intervals for metrics that evaluate probability predictions (or confidence scores — no relation to statistical confidence), i.e. soft classification, such as Log Loss or ROC AUC, rather than the metrics we used here which evaluate the discrete choice of class by the model (hard classification). The same code works for both, as well as for regression (predicting a continuous target variable) — you just have to pass it a different kind of prediction (and different kind of true targets in the case of regression). This jupyter notebook is available in github: bootConfIntAutoV1o_standalone.ipynb Was this article informative and/or useful? Please post a response (speech bubble icon to the left or down below, next to the black/white👏claps icon) if you have any comments or questions about this article or about confidence intervals, the bootstrap, number of boots, this implementation, dataset, model, threshold moving, or results. In addition to the aforementioned prior article, you might also be interested in my How to Auto-Detect the Date/Datetime Columns and Set Their Datatype When Reading a CSV File in Pandas, though it’s not directly related to the present article. Some rights reserved
[ { "code": null, "e": 678, "s": 171, "text": "If you report your classifier’s performance as having Accuracy=94.8% and F1=92.3% on a test set, this doesn’t mean much without knowing something about the size and composition of the test set. The margin of error of those performance measurements will vary a lot depending on the size of the test set, or, for an imbalanced dataset, primarily depending on how many independent instances of the minority class it contains (more copies of the same instances from oversampling doesn’t help for this purpose)." }, { "code": null, "e": 982, "s": 678, "text": "If you were able to collect another, independent test set of similar origin, the Accuracy and F1 of your model on this dataset are unlikely to be the same, but how much different might they plausibly be? A question similar to this is answered in statistics as the confidence interval of the measurement." }, { "code": null, "e": 1253, "s": 982, "text": "If we were to draw many independent sample datasets from the underlying population, then for 95% of those datasets, the true underlying population value of the metric would be within the 95% confidence interval that we would calculate for that particular sample dataset." }, { "code": null, "e": 1496, "s": 1253, "text": "In this article we will show you how to calculate confidence intervals for any number of Machine Learning performance metrics at once, with a bootstrap method that automatically determines how many boot sample datasets to generate by default." }, { "code": null, "e": 1636, "s": 1496, "text": "If you just want to see how to invoke this code to calculate confidence intervals, skip to the section “Calculate the results!” down below." }, { "code": null, "e": 2001, "s": 1636, "text": "If we were able to draw additional test datasets from the true distribution underlying the data, we would be able to see the distribution of the performance metric(s) of interest across those datasets. (When drawing those datasets we would not do anything to prevent drawing an identical or similar instance multiple times, although this might only happen rarely.)" }, { "code": null, "e": 2536, "s": 2001, "text": "Since we can’t do that, the next best thing is to draw additional datasets from the empirical distribution of this test dataset, which means sampling, with replacement, from its instances to generate new bootstrap sample datasets. Sampling with replacement means once we draw a particular instance, we put it back in so that we might draw it again for the same sample dataset. Therefore, each such dataset generally has multiple copies of some of the instances, and does not include all of the instances that are in the base test set." }, { "code": null, "e": 2719, "s": 2536, "text": "If we sampled without replacement, then we would simply get an identical copy of the original dataset every time, shuffled in a different random order, which would not be of any use." }, { "code": null, "e": 2810, "s": 2719, "text": "The percentile bootstrap methodology for estimating the confidence interval is as follows:" }, { "code": null, "e": 3396, "s": 2810, "text": "Generate nboots “bootstrap sample” datasets, each the same size as the original test set. Each sample dataset is obtained by drawing instances at random from the test set with replacement.On each of the sample datasets, calculate the metric and save it.The 95% confidence interval is given by the 2.5th to the 97.5th percentile among the nboots calculated values of the metric. If nboots=1001 and you sorted the values in a series/array/list X of length 1001, the 0th percentile is X[0] and the 100th percentile is X[1000], so the confidence interval would be given by X[25] to X[975]." }, { "code": null, "e": 3585, "s": 3396, "text": "Generate nboots “bootstrap sample” datasets, each the same size as the original test set. Each sample dataset is obtained by drawing instances at random from the test set with replacement." }, { "code": null, "e": 3651, "s": 3585, "text": "On each of the sample datasets, calculate the metric and save it." }, { "code": null, "e": 3984, "s": 3651, "text": "The 95% confidence interval is given by the 2.5th to the 97.5th percentile among the nboots calculated values of the metric. If nboots=1001 and you sorted the values in a series/array/list X of length 1001, the 0th percentile is X[0] and the 100th percentile is X[1000], so the confidence interval would be given by X[25] to X[975]." }, { "code": null, "e": 4148, "s": 3984, "text": "Of course you can calculate as many metrics as you like for each sample dataset in step 2, but in step 3 you would find the percentiles for each metric separately." }, { "code": null, "e": 4386, "s": 4148, "text": "We will use results from this prior article as an example: How To Deal With Imbalanced Classification, Without Re-balancing the Data: Before considering oversampling your skewed data, try adjusting your classification decision threshold." }, { "code": null, "e": 4875, "s": 4386, "text": "In that article we used the highly-imbalanced two-class Kaggle credit card fraud identification data set. We chose to use a classification threshold quite different from the default 0.5 threshold that is implicit in using the predict() method, making it unnecessary to balance the data. This approach is sometimes termed threshold moving, in which our classifier assigns the class by applying the chosen threshold to the predicted class probability provided by the predict_proba() method." }, { "code": null, "e": 5161, "s": 4875, "text": "We will limit the scope of this article (and code) to binary classification: classes 0 and 1, with class 1 by convention being the “positive” class and specifically the minority class for imbalanced data, although the code should work for regression (single continuous target) as well." }, { "code": null, "e": 5919, "s": 5161, "text": "Although our confidence interval code can handle various numbers of data arguments to be passed to the metric functions, we will focus on sklearn-style metrics, which always accept two data arguments, y_true and y_pred, where y_pred will be either binary class predictions (0 or 1), or continuous class-probability or decision function predictions, or even continuous regression predictions if y_true is continuous as well. The following function generates a single boot sample dataset. It accepts any data_args but in our case these arguments will be ytest(our actual/true test set target values in the prior article) and hardpredtst_tuned_thresh (the predicted class). Both contain zeros and ones to indicate the true or predicted class for each instance." }, { "code": null, "e": 6189, "s": 5919, "text": "We will define a custom metric function for Specificity, which is just another name for the Recall of the negative class (class 0). Also a calc_metrics function which which applies a sequence of metrics of interest to our data, and a couple of utility functions for it:" }, { "code": null, "e": 6716, "s": 6189, "text": "Here we make our list of metrics and apply them to the data. We did not consider Accuracy to be a relevant metric because a false negative (misclassifying a true fraud as legit) is much more costly to the business than a false positive (misclassifying a true legit as a fraud), whereas Accuracy treats both types of misclassification are equally bad and therefore favors correctly-classifying those whose true class is the majority class because these occur much more often and so contribute much more to the overall Accuracy." }, { "code": null, "e": 6856, "s": 6716, "text": "met=[ metrics.recall_score, specificity_score, metrics.balanced_accuracy_score ]calc_metrics(met, ytest, hardpredtst_tuned_thresh)" }, { "code": null, "e": 6972, "s": 6856, "text": "In raw_metric_samples() we will actually generate multiple sample datasets one by one and save the metrics of each:" }, { "code": null, "e": 7382, "s": 6972, "text": "You give raw_metric_samples() a list of metrics (or just one metric) of interest as well as the true and predicted class data, and it obtains nboots sample datasets and returns a dataframe with just the metrics’ values calculated from each dataset. Through _boot_generator() it invokes one_boot() one at a time in a generator expression rather than storing all the datasets at once as a potentially-huge list." }, { "code": null, "e": 7727, "s": 7382, "text": "We make our list of metric functions and invoke raw_metric_samples() to get the results for just 7 sample datasets. We are invoking raw_metric_samples() here for understanding — it is not necessary in order to get confidence intervals using ci_auto() below, although specifying a list of metrics (or just one metric) for ci_auto() is necessary." }, { "code": null, "e": 7863, "s": 7727, "text": "np.random.seed(13)raw_metric_samples(met, ytest, hardpredtst_tuned_thresh, nboots=7).style.format('{:.2%}') #optional #style" }, { "code": null, "e": 8026, "s": 7863, "text": "Each column above contains the metrics calculated from one boot sample dataset (numbered 0 to 6), so the calculated metric values vary due to the random sampling." }, { "code": null, "e": 8720, "s": 8026, "text": "In our implementation, by default the number of boot datasets nboots will be calculated automatically from the desired confidence level (e.g. 95%) so as to meet the recommendation by North, Curtis, and Sham to have a minimum number of boot results in each tail of the distribution. (Actually this recommendation applies to p-values and thus hypothesis test acceptance regions, but confidence intervals are similar enough to those to use this as a rule of thumb.) Although those authors recommend a minimum of 10 boot results in the tail, Davidson & MacKinnon recommend at least 399 boots for 95% confidence, which requires 11 boots in the tail, so we use this more-conservative recommendation." }, { "code": null, "e": 9440, "s": 8720, "text": "We specify alpha which is 1 − confidence level. E.g. 95% confidence becomes 0.95 and alpha=0.05. If you specify an explicit number of boots (perhaps a smaller nboots because you want faster results) but it is not enough for your requested alpha, a higher alpha will be chosen automatically in order to get an accurate confidence interval for that number of boots. A minimum of 51 boots will be used because any less can only accurately calculate bizarrely-small confidence levels (such as 40% confidence which gives an interval from the 30th percentile to the 70th percentile, which has 40% inside the interval but 60% outside it) and it is not clear that the minimum-boots recommendation even contemplated such a case." }, { "code": null, "e": 9550, "s": 9440, "text": "The function get_alpha_nboots() sets the default nboots or modifies the requested alpha and nboots per above:" }, { "code": null, "e": 9609, "s": 9550, "text": "Let’s show the default nboots for various values of alpha:" }, { "code": null, "e": 9849, "s": 9609, "text": "g = get_alpha_nboots pd.DataFrame( [ g(0.40), g(0.20, None), g(0.10), g(), g(alpha=0.02), g(alpha=0.01, nboots=None), g(0.005, nboots=None) ], columns=['alpha', 'default nboots'] ).set_index('alpha')" }, { "code": null, "e": 9903, "s": 9849, "text": "Here’s what happens if we request an explicit nboots:" }, { "code": null, "e": 10116, "s": 9903, "text": "req=[(0.01,3000), (0.01,401), (0.01,2)]out=[get_alpha_nboots(*args) for args in req]mydf = lambda x: pd.DataFrame(x, columns=['alpha', 'nboots'])pd.concat([mydf(req),mydf(out)],axis=1, keys=('Requested','Using'))" }, { "code": null, "e": 10218, "s": 10116, "text": "Small nboots values increased alpha to 0.05 and 0.40, and nboots=2 gets changed to the minimum of 51." }, { "code": null, "e": 10319, "s": 10218, "text": "Again we don’t need to do this in order to get the confidence intervals below by invoking ci_auto()." }, { "code": null, "e": 10428, "s": 10319, "text": "np.random.seed(13)metric_boot_histogram\\ (metrics.balanced_accuracy_score, ytest, hardpredtst_tuned_thresh)" }, { "code": null, "e": 10649, "s": 10428, "text": "Here is the main function that invokes the above and calculates the confidence intervals from the percentiles of the metric results, and inserts the point estimates as the first column of its output dataframe of results." }, { "code": null, "e": 10831, "s": 10649, "text": "This is all we really needed to do: invoke ci_auto() as follows with a list of metrics (met assigned above) to get their confidence intervals. The percentage formatting is optional:" }, { "code": null, "e": 10926, "s": 10831, "text": "np.random.seed(13)ci_auto( met, ytest, hardpredtst_tuned_thresh ).style.format('{:.2%}')" }, { "code": null, "e": 11070, "s": 10926, "text": "Here’s the confusion matrix from the original article. Class 0 is the negatives (majority class) and Class 1 is the positives (very rare class)" }, { "code": null, "e": 11215, "s": 11070, "text": "The Recall (True Positive Rate) of 134/(134+14) has the widest confidence interval because this is a binomial proportion involving small counts." }, { "code": null, "e": 11391, "s": 11215, "text": "The Specificity (True Negative Rate) is 80,388/(80,388+4,907), which involves much larger counts, so it has an extremely narrow confidence interval of just [94.11% to 94.40%]." }, { "code": null, "e": 11559, "s": 11391, "text": "Since the Balanced Accuracy is calculated as simply an average of the Recall and the Specificity, the width of its confidence interval is intermediate between theirs’." }, { "code": null, "e": 12019, "s": 11559, "text": "Here we have not considered the variability in the model based on the randomness of our training data (although that can also be of interest for some purposes, e.g. if you have automated repeated re-training and want to know how much the performance of future models might vary), but rather only the variability in the measurement of the performance of this particular model (created from some particular training data) due to the randomness of our test data." }, { "code": null, "e": 12363, "s": 12019, "text": "If we had enough independent test data, we could measure the performance of this particular model on the underlying population very precisely, and we would know how it will perform if this model is deployed, irrespective of how we built the model and of whether we might obtain a better or worse model with a different training sample dataset." }, { "code": null, "e": 12982, "s": 12363, "text": "The bootstrap method assumes that each of your instances (cases, observations) is drawn independently from an underlying population. If your test set has groups of rows that are not independent of each other, for example repeated observations of the same entity that are likely to be correlated with one another, or instances that are oversampled/replicated/generated-from other instances in your test set, the results might not be valid. You might need to use grouped sampling, where you draw entire groups together at random rather than individual rows, while avoiding breaking up any group or just using part of it." }, { "code": null, "e": 13572, "s": 12982, "text": "Also you want to make sure you don’t have groups that were split across the training and test set, because then the test set is not necessarily independent and you might get undetected overfitting. For example if you use oversampling you should generally only do only after it has been split from the test set, not before. And normally you would oversample the training set but not the test set, since the test set must remain representative of instances the model will see upon future deployment. And for cross-validation you would want to use scikit-learn’s model_selection.GroupKFold()." }, { "code": null, "e": 14304, "s": 13572, "text": "You can always calculate confidence intervals for your evaluation metric(s) to see how precisely your test data enables you to measure your model’s performance. I’m planning another article to demonstrate confidence intervals for metrics that evaluate probability predictions (or confidence scores — no relation to statistical confidence), i.e. soft classification, such as Log Loss or ROC AUC, rather than the metrics we used here which evaluate the discrete choice of class by the model (hard classification). The same code works for both, as well as for regression (predicting a continuous target variable) — you just have to pass it a different kind of prediction (and different kind of true targets in the case of regression)." }, { "code": null, "e": 14386, "s": 14304, "text": "This jupyter notebook is available in github: bootConfIntAutoV1o_standalone.ipynb" }, { "code": null, "e": 14723, "s": 14386, "text": "Was this article informative and/or useful? Please post a response (speech bubble icon to the left or down below, next to the black/white👏claps icon) if you have any comments or questions about this article or about confidence intervals, the bootstrap, number of boots, this implementation, dataset, model, threshold moving, or results." }, { "code": null, "e": 14967, "s": 14723, "text": "In addition to the aforementioned prior article, you might also be interested in my How to Auto-Detect the Date/Datetime Columns and Set Their Datatype When Reading a CSV File in Pandas, though it’s not directly related to the present article." } ]
Understanding the Spark insertInto function | by Ronald Ángel | Towards Data Science
Raw Data Ingestion into a Data Lake with spark is a common currently used ETL approach. In some cases, the raw data is cleaned, serialized and exposed as Hive tables used by the analytics team to perform SQL like operations. Thus, spark provides two options for tables creation: managed and external tables. The difference between these is that unlike the manage tables where spark controls the storage and the metadata, on an external table spark does not control the data location and only manages the metadata. In addition, often a retry strategy to overwrite some failed partitions is needed. For instance, a batch job (timestamp partitioned) failed for the partition 22/10/2019 and we need to re-run the job writing the correct data. Therefore, there are two options: a) regenerate and overwrite all the data, or b) process and overwrite the data for the needed partition. Option two is discarded due to performance issues, imagine that you have to process an entire month of data. Consequently, the option first option is used and fortunately spark has the option dynamic partitionOverwriteMode that overwrites data only for partitions present in the current batch. This option works perfectly while writing data to an external data store like HDFS or S3; cases, where is possible to reload the external table metadata by a simple, CREATE EXTERNAL TABLE command. However, for Hive tables stored in the meta store with dynamic partitions, there are some behaviors that we need to understand in order to keep the data quality and consistency. First of all, even when spark provides two functions to store data in a table saveAsTable and insertInto, there is an important difference between them: SaveAsTable: creates the table structure and stores the first version of the data. However, the overwrite save mode works over all the partitions even when dynamic is configured. insertInto: does not create the table structure, however, the overwrite save mode works only the needed partitions when dynamic is configured. So, SaveAsTable could be used to create the table from a raw dataframe definition and then after the table is created, overwrites are done using the insertInto function in a straightforward pattern. Nevertheless, the insertInto presents some not well-documented behaviors while writing the partitioned data and some challenges while working with data that contains schema changes. Let’s write a simple unit test where a table is created from a data frame. it should "Store table and insert into new record on new partitions" in { val spark = ss import spark.implicits._ val targetTable = "companies_table" val companiesDF = Seq(("A", "Company1"), ("B", "Company2")).toDF("id", "company") companiesDF.write.mode(SaveMode.Overwrite).partitionBy("id").saveAsTable(targetTable) val companiesHiveDF = ss.sql(s"SELECT * FROM ${targetTable}") So far, the table was created correctly. Then, let’s overwrite some data using insertInto and perform some asserts. val secondCompaniesDF = Seq(("C", "Company3"), ("D", "Company4")) .toDF("id", "company")secondCompaniesDF.write.mode(SaveMode.Append).insertInto(targetTable) val companiesHiveAfterInsertDF = ss.sql(s"SELECT * FROM ${targetTable}") companiesDF.count() should equal(2) companiesHiveAfterInsertDF.count() should equal(4) companiesHiveDF.select("id").collect().map(_.get(0)) should contain allOf("A", "B") companiesHiveAfterInsertDF.select("id").collect() should contain allOf("A", "B", "C", "D")} This should work properly. However, look at the following data print: As you can see the asserts failed due to the positions of the columns. There are two reasons: a) saveAsTable uses the partition column and adds it at the end. b) insertInto works using the order of the columns (exactly as calling an SQL insertInto) instead of the columns name. In consequence, adding the partition column at the end fixes the issue as shown here: //partition column should be at the end to match table schema. val secondCompaniesDF = Seq(("Company3", "C"), ("Company4", "D")) .toDF("company", "id") secondCompaniesDF.write.mode(SaveMode.Append).insertInto(targetTable) val companiesHiveAfterInsertDF = ss.sql(s"SELECT * FROM ${targetTable}") companiesHiveAfterInsertDF.printSchema() companiesHiveAfterInsertDF.show(false) companiesDF.count() should equal(2) companiesHiveAfterInsertDF.count() should equal(4) companiesHiveDF.select("id").collect().map(_.get(0)) should contain allOf("A", "B") companiesHiveAfterInsertDF.select("id").collect().map(_.get(0)) should contain allOf("A", "B", "C", "D")} Now the tests pass and the data is overwritten properly. As described previously the order of the columns is important for the insertInto function. Besides, let’s image you are ingesting data that has a changing schema and you receive a new batch with a different number of columns. Let’s test first the case when more columns are added. //again adding the partition column at the end and trying to overwrite partition C.val thirdCompaniesDF = Seq(("Company4", 10, "C"), ("Company5", 20, "F")) .toDF("company", "size", "id")thirdCompaniesDF.write.mode(SaveMode.Overwrite).insertInto(targetTable) While trying to call insertInto the following error is shown: Hence, a function that returns the missing columns in the table is needed: def getMissingTableColumnsAgainstDataFrameSchema(df: DataFrame, tableDF: DataFrame): Set[String] = { val dfSchema = df.schema.fields.map(v => (v.name, v.dataType)).toMap val tableSchema = tableDF.schema.fields.map(v => (v.name, v.dataType)).toMap val columnsMissingInTable = dfSchema.keys.toSet.diff(tableSchema.keys.toSet).map(x => x.concat(s" ${dfSchema.get(x).get.sql}")) columnsMissingInTable} Then, the SQL ALTER TABLE command is executed. After this, the insertInto function works properly and the table schema is merged as you can see here: val tableFlatDF = ss.sql(s"SELECT * FROM $targetTable limit 1")val columnsMissingInTable = DataFrameSchemaUtils.getMissingTableColumnsAgainstDataFrameSchema(thirdCompaniesDF, tableFlatDF)if (columnsMissingInTable.size > 0) { ss.sql((s"ALTER TABLE $targetTable " + s"ADD COLUMNS (${columnsMissingInTable.mkString(" , ")})"))}thirdCompaniesDF.write.mode(SaveMode.Overwrite).insertInto(targetTable)val companiesHiveAfterInsertNewSchemaDF = ss.sql(s"SELECT * FROM $targetTable")companiesHiveAfterInsertNewSchemaDF.printSchema()companiesHiveAfterInsertNewSchemaDF.show(false) Let’s test now the case when fewer columns are received. val fourthCompaniesDF = Seq("G", "H") .toDF("id")fourthCompaniesDF.write.mode(SaveMode.Overwrite).insertInto(targetTable) The following error is shown: Hence, a function that adds the missing columns to the data frame is needed: def mergeDataFrameSchemaAgainstTable(tableDF: DataFrame)(df: DataFrame): DataFrame = { val dfSchema = df.schema.fields.map(v => (v.name, v.dataType)).toMap val tableSchema = tableDF.schema.fields.map(v => (v.name, v.dataType)).toMap val columnMissingInDF = tableSchema.keys.toSet.diff(dfSchema.keys.toSet).toList val mergedDFWithNewColumns = columnMissingInDF.foldLeft(df) { (currentDF, colName) => currentDF.withColumn( colName, lit(null).cast(tableSchema.get(colName).get.typeName) ) } mergedDFWithNewColumns} Then, the merged data frame is written and works properly as you can see here: val mergedFlatDF = fourthCompaniesDF.transform(DataFrameSchemaUtils.mergeDataFrameSchemaAgainstTable(companiesHiveDF))mergedFlatDF.write.mode(SaveMode.Overwrite).insertInto(targetTable)mergedFlatDF.printSchema()mergedFlatDF.show(false) Spark provides multiple functions to integrate our data pipelines with Hive. However, a good understanding of how they work under the hood is needed to avoid errors while writing our data. Specifically, the insertInto function has two important characteristics that should be considered while working with dynamic partitions: The partition columns should be always at the end to match the Hive table schema definitions.InsertInto uses the order of the columns instead of the names. So, you should guarantee that always have the same number of columns and keep them in the same insertion order. The partition columns should be always at the end to match the Hive table schema definitions. InsertInto uses the order of the columns instead of the names. So, you should guarantee that always have the same number of columns and keep them in the same insertion order.
[ { "code": null, "e": 561, "s": 47, "text": "Raw Data Ingestion into a Data Lake with spark is a common currently used ETL approach. In some cases, the raw data is cleaned, serialized and exposed as Hive tables used by the analytics team to perform SQL like operations. Thus, spark provides two options for tables creation: managed and external tables. The difference between these is that unlike the manage tables where spark controls the storage and the metadata, on an external table spark does not control the data location and only manages the metadata." }, { "code": null, "e": 1034, "s": 561, "text": "In addition, often a retry strategy to overwrite some failed partitions is needed. For instance, a batch job (timestamp partitioned) failed for the partition 22/10/2019 and we need to re-run the job writing the correct data. Therefore, there are two options: a) regenerate and overwrite all the data, or b) process and overwrite the data for the needed partition. Option two is discarded due to performance issues, imagine that you have to process an entire month of data." }, { "code": null, "e": 1416, "s": 1034, "text": "Consequently, the option first option is used and fortunately spark has the option dynamic partitionOverwriteMode that overwrites data only for partitions present in the current batch. This option works perfectly while writing data to an external data store like HDFS or S3; cases, where is possible to reload the external table metadata by a simple, CREATE EXTERNAL TABLE command." }, { "code": null, "e": 1747, "s": 1416, "text": "However, for Hive tables stored in the meta store with dynamic partitions, there are some behaviors that we need to understand in order to keep the data quality and consistency. First of all, even when spark provides two functions to store data in a table saveAsTable and insertInto, there is an important difference between them:" }, { "code": null, "e": 1926, "s": 1747, "text": "SaveAsTable: creates the table structure and stores the first version of the data. However, the overwrite save mode works over all the partitions even when dynamic is configured." }, { "code": null, "e": 2069, "s": 1926, "text": "insertInto: does not create the table structure, however, the overwrite save mode works only the needed partitions when dynamic is configured." }, { "code": null, "e": 2450, "s": 2069, "text": "So, SaveAsTable could be used to create the table from a raw dataframe definition and then after the table is created, overwrites are done using the insertInto function in a straightforward pattern. Nevertheless, the insertInto presents some not well-documented behaviors while writing the partitioned data and some challenges while working with data that contains schema changes." }, { "code": null, "e": 2525, "s": 2450, "text": "Let’s write a simple unit test where a table is created from a data frame." }, { "code": null, "e": 2914, "s": 2525, "text": "it should \"Store table and insert into new record on new partitions\" in { val spark = ss import spark.implicits._ val targetTable = \"companies_table\" val companiesDF = Seq((\"A\", \"Company1\"), (\"B\", \"Company2\")).toDF(\"id\", \"company\") companiesDF.write.mode(SaveMode.Overwrite).partitionBy(\"id\").saveAsTable(targetTable) val companiesHiveDF = ss.sql(s\"SELECT * FROM ${targetTable}\")" }, { "code": null, "e": 3030, "s": 2914, "text": "So far, the table was created correctly. Then, let’s overwrite some data using insertInto and perform some asserts." }, { "code": null, "e": 3533, "s": 3030, "text": " val secondCompaniesDF = Seq((\"C\", \"Company3\"), (\"D\", \"Company4\")) .toDF(\"id\", \"company\")secondCompaniesDF.write.mode(SaveMode.Append).insertInto(targetTable) val companiesHiveAfterInsertDF = ss.sql(s\"SELECT * FROM ${targetTable}\") companiesDF.count() should equal(2) companiesHiveAfterInsertDF.count() should equal(4) companiesHiveDF.select(\"id\").collect().map(_.get(0)) should contain allOf(\"A\", \"B\") companiesHiveAfterInsertDF.select(\"id\").collect() should contain allOf(\"A\", \"B\", \"C\", \"D\")}" }, { "code": null, "e": 3603, "s": 3533, "text": "This should work properly. However, look at the following data print:" }, { "code": null, "e": 3967, "s": 3603, "text": "As you can see the asserts failed due to the positions of the columns. There are two reasons: a) saveAsTable uses the partition column and adds it at the end. b) insertInto works using the order of the columns (exactly as calling an SQL insertInto) instead of the columns name. In consequence, adding the partition column at the end fixes the issue as shown here:" }, { "code": null, "e": 4632, "s": 3967, "text": " //partition column should be at the end to match table schema. val secondCompaniesDF = Seq((\"Company3\", \"C\"), (\"Company4\", \"D\")) .toDF(\"company\", \"id\") secondCompaniesDF.write.mode(SaveMode.Append).insertInto(targetTable) val companiesHiveAfterInsertDF = ss.sql(s\"SELECT * FROM ${targetTable}\") companiesHiveAfterInsertDF.printSchema() companiesHiveAfterInsertDF.show(false) companiesDF.count() should equal(2) companiesHiveAfterInsertDF.count() should equal(4) companiesHiveDF.select(\"id\").collect().map(_.get(0)) should contain allOf(\"A\", \"B\") companiesHiveAfterInsertDF.select(\"id\").collect().map(_.get(0)) should contain allOf(\"A\", \"B\", \"C\", \"D\")}" }, { "code": null, "e": 4689, "s": 4632, "text": "Now the tests pass and the data is overwritten properly." }, { "code": null, "e": 4915, "s": 4689, "text": "As described previously the order of the columns is important for the insertInto function. Besides, let’s image you are ingesting data that has a changing schema and you receive a new batch with a different number of columns." }, { "code": null, "e": 4970, "s": 4915, "text": "Let’s test first the case when more columns are added." }, { "code": null, "e": 5230, "s": 4970, "text": "//again adding the partition column at the end and trying to overwrite partition C.val thirdCompaniesDF = Seq((\"Company4\", 10, \"C\"), (\"Company5\", 20, \"F\")) .toDF(\"company\", \"size\", \"id\")thirdCompaniesDF.write.mode(SaveMode.Overwrite).insertInto(targetTable)" }, { "code": null, "e": 5292, "s": 5230, "text": "While trying to call insertInto the following error is shown:" }, { "code": null, "e": 5367, "s": 5292, "text": "Hence, a function that returns the missing columns in the table is needed:" }, { "code": null, "e": 5769, "s": 5367, "text": "def getMissingTableColumnsAgainstDataFrameSchema(df: DataFrame, tableDF: DataFrame): Set[String] = { val dfSchema = df.schema.fields.map(v => (v.name, v.dataType)).toMap val tableSchema = tableDF.schema.fields.map(v => (v.name, v.dataType)).toMap val columnsMissingInTable = dfSchema.keys.toSet.diff(tableSchema.keys.toSet).map(x => x.concat(s\" ${dfSchema.get(x).get.sql}\")) columnsMissingInTable}" }, { "code": null, "e": 5919, "s": 5769, "text": "Then, the SQL ALTER TABLE command is executed. After this, the insertInto function works properly and the table schema is merged as you can see here:" }, { "code": null, "e": 6494, "s": 5919, "text": "val tableFlatDF = ss.sql(s\"SELECT * FROM $targetTable limit 1\")val columnsMissingInTable = DataFrameSchemaUtils.getMissingTableColumnsAgainstDataFrameSchema(thirdCompaniesDF, tableFlatDF)if (columnsMissingInTable.size > 0) { ss.sql((s\"ALTER TABLE $targetTable \" + s\"ADD COLUMNS (${columnsMissingInTable.mkString(\" , \")})\"))}thirdCompaniesDF.write.mode(SaveMode.Overwrite).insertInto(targetTable)val companiesHiveAfterInsertNewSchemaDF = ss.sql(s\"SELECT * FROM $targetTable\")companiesHiveAfterInsertNewSchemaDF.printSchema()companiesHiveAfterInsertNewSchemaDF.show(false)" }, { "code": null, "e": 6551, "s": 6494, "text": "Let’s test now the case when fewer columns are received." }, { "code": null, "e": 6674, "s": 6551, "text": "val fourthCompaniesDF = Seq(\"G\", \"H\") .toDF(\"id\")fourthCompaniesDF.write.mode(SaveMode.Overwrite).insertInto(targetTable)" }, { "code": null, "e": 6704, "s": 6674, "text": "The following error is shown:" }, { "code": null, "e": 6781, "s": 6704, "text": "Hence, a function that adds the missing columns to the data frame is needed:" }, { "code": null, "e": 7315, "s": 6781, "text": "def mergeDataFrameSchemaAgainstTable(tableDF: DataFrame)(df: DataFrame): DataFrame = { val dfSchema = df.schema.fields.map(v => (v.name, v.dataType)).toMap val tableSchema = tableDF.schema.fields.map(v => (v.name, v.dataType)).toMap val columnMissingInDF = tableSchema.keys.toSet.diff(dfSchema.keys.toSet).toList val mergedDFWithNewColumns = columnMissingInDF.foldLeft(df) { (currentDF, colName) => currentDF.withColumn( colName, lit(null).cast(tableSchema.get(colName).get.typeName) ) } mergedDFWithNewColumns}" }, { "code": null, "e": 7394, "s": 7315, "text": "Then, the merged data frame is written and works properly as you can see here:" }, { "code": null, "e": 7630, "s": 7394, "text": "val mergedFlatDF = fourthCompaniesDF.transform(DataFrameSchemaUtils.mergeDataFrameSchemaAgainstTable(companiesHiveDF))mergedFlatDF.write.mode(SaveMode.Overwrite).insertInto(targetTable)mergedFlatDF.printSchema()mergedFlatDF.show(false)" }, { "code": null, "e": 7956, "s": 7630, "text": "Spark provides multiple functions to integrate our data pipelines with Hive. However, a good understanding of how they work under the hood is needed to avoid errors while writing our data. Specifically, the insertInto function has two important characteristics that should be considered while working with dynamic partitions:" }, { "code": null, "e": 8224, "s": 7956, "text": "The partition columns should be always at the end to match the Hive table schema definitions.InsertInto uses the order of the columns instead of the names. So, you should guarantee that always have the same number of columns and keep them in the same insertion order." }, { "code": null, "e": 8318, "s": 8224, "text": "The partition columns should be always at the end to match the Hive table schema definitions." } ]
How to Create Multiple User Accounts in Linux?
Adding a single new user to a Linux system can be achieved through the useradd command. But system admins often get request to add many users. So Linux provides a different to do a bulk addition of many users to a system.This is the newusers command. sudo newusers user_deatils.txt user_details.txt is the file containing the details of all the usernames to be added. Below we see the structure of user_details.txt file. UserName:Password:UID:GID:comments:HomeDirectory:UserShell So we create a file with below details to add many usres. ~$ cat MoreUsers.txt uname1:pwd#@1:2112:3421:storefront:/home/uname1:/bin/bash uname3:pwd#!@3:2112:3525:backend:/home/uname3:/bin/bash uname4:pwd#$$9:9002:4721:HR:/home/uname4:/bin/bash Before we sue the user details file to add new users, we should give permission to it to be read by other processes. sudo chmod 0600 MoreUsers.txt Lets verify the existing users in the system by going to the /etc/passwd file. ubuntu@ubuntu:~$ tail -5 /etc/passwd Running the above code gives us the following result − pulse:x:117:124:PulseAudio daemon,,,:/var/run/pulse:/bin/false rtkit:x:118:126:RealtimeKit,,,:/proc:/bin/false saned:x:119:127::/var/lib/saned:/bin/false usbmux:x:120:46:usbmux daemon,,,:/var/lib/usbmux:/bin/false ubuntu:x:1000:1000:ubuntu16LTS,,,:/home/ubuntu:/bin/bash next we run the newusers command to add these usernames. sudo newusers MoreUsers.txt Now we verify that indeed those users are added , by going again to the /etc/passwd file. cat /etc/passwd Running the above code gives us the following result − ........... ............. ubuntu:x:1000:1000:ubuntu16LTS,,,:/home/ubuntu:/bin/bash uname1:x:2112:3421:storefront:/home/uname1:/bin/bash uname3:x:2112:3525:backend:/home/uname3:/bin/bash uname4:x:9002:4721:HR:/home/uname4:/bin/bash
[ { "code": null, "e": 1313, "s": 1062, "text": "Adding a single new user to a Linux system can be achieved through the useradd command. But system admins often get request to add many users. So Linux provides a different to do a bulk addition of many users to a system.This is the newusers command." }, { "code": null, "e": 1430, "s": 1313, "text": "sudo newusers user_deatils.txt\nuser_details.txt is the file containing the details of all the usernames to be added." }, { "code": null, "e": 1483, "s": 1430, "text": "Below we see the structure of user_details.txt file." }, { "code": null, "e": 1542, "s": 1483, "text": "UserName:Password:UID:GID:comments:HomeDirectory:UserShell" }, { "code": null, "e": 1600, "s": 1542, "text": "So we create a file with below details to add many usres." }, { "code": null, "e": 1786, "s": 1600, "text": "~$ cat MoreUsers.txt\nuname1:pwd#@1:2112:3421:storefront:/home/uname1:/bin/bash\nuname3:pwd#!@3:2112:3525:backend:/home/uname3:/bin/bash\nuname4:pwd#$$9:9002:4721:HR:/home/uname4:/bin/bash" }, { "code": null, "e": 1903, "s": 1786, "text": "Before we sue the user details file to add new users, we should give permission to it to be read by other processes." }, { "code": null, "e": 1933, "s": 1903, "text": "sudo chmod 0600 MoreUsers.txt" }, { "code": null, "e": 2012, "s": 1933, "text": "Lets verify the existing users in the system by going to the /etc/passwd file." }, { "code": null, "e": 2049, "s": 2012, "text": "ubuntu@ubuntu:~$ tail -5 /etc/passwd" }, { "code": null, "e": 2104, "s": 2049, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2375, "s": 2104, "text": "pulse:x:117:124:PulseAudio daemon,,,:/var/run/pulse:/bin/false\nrtkit:x:118:126:RealtimeKit,,,:/proc:/bin/false\nsaned:x:119:127::/var/lib/saned:/bin/false\nusbmux:x:120:46:usbmux daemon,,,:/var/lib/usbmux:/bin/false\nubuntu:x:1000:1000:ubuntu16LTS,,,:/home/ubuntu:/bin/bash" }, { "code": null, "e": 2432, "s": 2375, "text": "next we run the newusers command to add these usernames." }, { "code": null, "e": 2460, "s": 2432, "text": "sudo newusers MoreUsers.txt" }, { "code": null, "e": 2550, "s": 2460, "text": "Now we verify that indeed those users are added , by going again to the /etc/passwd file." }, { "code": null, "e": 2566, "s": 2550, "text": "cat /etc/passwd" }, { "code": null, "e": 2621, "s": 2566, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2852, "s": 2621, "text": "...........\n.............\nubuntu:x:1000:1000:ubuntu16LTS,,,:/home/ubuntu:/bin/bash\nuname1:x:2112:3421:storefront:/home/uname1:/bin/bash\nuname3:x:2112:3525:backend:/home/uname3:/bin/bash\nuname4:x:9002:4721:HR:/home/uname4:/bin/bash" } ]
Check If It Is a Straight Line in C++
Suppose we have a list of data-points consisting of (x, y) coordinates, we have to check whether the data-points are forming straight line or not. So if the points are like [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)], then they are forming straight line. To solve this, we will take the differences between each consecutive datapoints, and find the slope. For the first one find the slope. For all other points check whether the slope is same or not. if they are same, then simply return true, otherwise false Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int gcd(int a, int b){ return !b?a:gcd(b,a%b); } bool checkStraightLine(vector<vector<int>>& c) { bool ans =true; bool samex = true; bool samey = true; int a = c[1][0]-c[0][0]; int b = c[1][1]-c[0][1]; int cc = gcd(a,b); a/=cc; b/=cc; for(int i =1;i<c.size();i++){ int x = c[i][0]-c[i-1][0]; int y = c[i][1]-c[i-1][1]; int z = gcd(x,y); x/=z; y/=z; ans =ans &&(x == a )&& (y == b ); } return ans; } }; main(){ Solution ob; vector<vector<int>> c = {{1,2},{2,3},{3,4},{4,5},{5,6},{6,7}}; cout << ob.checkStraightLine(c); } [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] 1 (1 indicates true)
[ { "code": null, "e": 1322, "s": 1062, "text": "Suppose we have a list of data-points consisting of (x, y) coordinates, we have to check whether the data-points are forming straight line or not. So if the points are like [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)], then they are forming straight line." }, { "code": null, "e": 1577, "s": 1322, "text": "To solve this, we will take the differences between each consecutive datapoints, and find the slope. For the first one find the slope. For all other points check whether the slope is same or not. if they are same, then simply return true, otherwise false" }, { "code": null, "e": 1649, "s": 1577, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 1660, "s": 1649, "text": " Live Demo" }, { "code": null, "e": 2393, "s": 1660, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int gcd(int a, int b){\n return !b?a:gcd(b,a%b);\n }\n bool checkStraightLine(vector<vector<int>>& c) {\n bool ans =true;\n bool samex = true;\n bool samey = true;\n int a = c[1][0]-c[0][0];\n int b = c[1][1]-c[0][1];\n int cc = gcd(a,b);\n a/=cc;\n b/=cc;\n for(int i =1;i<c.size();i++){\n int x = c[i][0]-c[i-1][0];\n int y = c[i][1]-c[i-1][1];\n int z = gcd(x,y);\n x/=z;\n y/=z;\n ans =ans &&(x == a )&& (y == b );\n }\n return ans;\n }\n};\nmain(){\nSolution ob;\nvector<vector<int>> c = {{1,2},{2,3},{3,4},{4,5},{5,6},{6,7}};\ncout << ob.checkStraightLine(c);\n}" }, { "code": null, "e": 2431, "s": 2393, "text": "[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]" }, { "code": null, "e": 2452, "s": 2431, "text": "1\n(1 indicates true)" } ]
How To Use Python To Buy Options From Robinhood | by Melvynn Fernandez | Towards Data Science
Just really want to test out my programming skills to mess with stocks. So what are options in trading? They are contracts which give you the right to buy or sell that asset at a price for a period of time. Some people view options as some sort of lottery ticket but I view it like blackjack, where you can do certain strategies to reduce your risk. In this article I will create Python code that will look at stock and purchase it. In order to do that let’s look at how an option looks like. Here is an example of how a standard quote of an option looks. ABC FEBRUARY 14, 2020 $69 CALL AT $4.20 Let’s break this down. ABC is the stock that the option is based on and it usually represents 100 shares of said stock. FEBRUARY 14, 2020 represents the month when the option is going to expire. 69 is the strike price for the stock. CALL would be one the option types, puts can also be filled here. $4.20 is the premium of the stock. So Microsoft stock has been really good to me so far in options trading. So far I have gained a significant amount. You can see my gains and losses here. We will use Microsoft to purchase an option on Robinhood. What I am using to pull data from Robinhood is called robin_stocks. I have an article showing how to set it up below. towardsdatascience.com So for my trading strategy for Microsoft stock is I usually buy an option call 30 days ahead of the current date and then I select a strike price that is above the current stock price. robin_stocks makes it simple where we can already pull the available stock options that we can send to them using find_tradable_options_for_stock. I have set it up where it already pulls just the calls below. r.options.find_tradable_options_for_stock(‘MSFT’, optionType=’call’) I like viewing the results in a DataFrame so I will transfer all this data over. Results will look like this: Now that we know what expiration dates are available we can now send an option order with the correct information. We will use this line of code to send orders in robin_stocks.orders.order_buy_option_limit(price, symbol, quantity, expirationDate, strike, optionType='both', timeInForce='gfd') For price, we can just fill in with the current option price. For symbol, we are going to be using MSFT . Quantity we will just be purchasing 1 contract order. For date, we will use 30 days from today (2/13/2020). So we will try to pick a date close to 30 days(3/13/2020). Strike we will choose a price that is closest and above the current stock price. Option type we want a call. Time in force is good for day (gfd). So our code will look like this and its translation in Robinhood: robin_stocks.orders.order_buy_option_limit(4.20, 'MSFT', 1, 2020-03-13, 185.00, optionType='call', timeInForce='gfd') MSFT MARCH 13, 2020 185 CALL AT $4.20 If we run this code in Python the order will be sent. However, it does not necessarily that the order executed. Here’s the full code below: Access to my Microsoft gains and losses here! I also have tutoring and career guidance available here! Don’t forget to connect with me on LinkedIn if you guys have any questions, comments or concerns!
[ { "code": null, "e": 119, "s": 47, "text": "Just really want to test out my programming skills to mess with stocks." }, { "code": null, "e": 397, "s": 119, "text": "So what are options in trading? They are contracts which give you the right to buy or sell that asset at a price for a period of time. Some people view options as some sort of lottery ticket but I view it like blackjack, where you can do certain strategies to reduce your risk." }, { "code": null, "e": 603, "s": 397, "text": "In this article I will create Python code that will look at stock and purchase it. In order to do that let’s look at how an option looks like. Here is an example of how a standard quote of an option looks." }, { "code": null, "e": 643, "s": 603, "text": "ABC FEBRUARY 14, 2020 $69 CALL AT $4.20" }, { "code": null, "e": 977, "s": 643, "text": "Let’s break this down. ABC is the stock that the option is based on and it usually represents 100 shares of said stock. FEBRUARY 14, 2020 represents the month when the option is going to expire. 69 is the strike price for the stock. CALL would be one the option types, puts can also be filled here. $4.20 is the premium of the stock." }, { "code": null, "e": 1189, "s": 977, "text": "So Microsoft stock has been really good to me so far in options trading. So far I have gained a significant amount. You can see my gains and losses here. We will use Microsoft to purchase an option on Robinhood." }, { "code": null, "e": 1307, "s": 1189, "text": "What I am using to pull data from Robinhood is called robin_stocks. I have an article showing how to set it up below." }, { "code": null, "e": 1330, "s": 1307, "text": "towardsdatascience.com" }, { "code": null, "e": 1515, "s": 1330, "text": "So for my trading strategy for Microsoft stock is I usually buy an option call 30 days ahead of the current date and then I select a strike price that is above the current stock price." }, { "code": null, "e": 1724, "s": 1515, "text": "robin_stocks makes it simple where we can already pull the available stock options that we can send to them using find_tradable_options_for_stock. I have set it up where it already pulls just the calls below." }, { "code": null, "e": 1793, "s": 1724, "text": "r.options.find_tradable_options_for_stock(‘MSFT’, optionType=’call’)" }, { "code": null, "e": 1903, "s": 1793, "text": "I like viewing the results in a DataFrame so I will transfer all this data over. Results will look like this:" }, { "code": null, "e": 2196, "s": 1903, "text": "Now that we know what expiration dates are available we can now send an option order with the correct information. We will use this line of code to send orders in robin_stocks.orders.order_buy_option_limit(price, symbol, quantity, expirationDate, strike, optionType='both', timeInForce='gfd')" }, { "code": null, "e": 2681, "s": 2196, "text": "For price, we can just fill in with the current option price. For symbol, we are going to be using MSFT . Quantity we will just be purchasing 1 contract order. For date, we will use 30 days from today (2/13/2020). So we will try to pick a date close to 30 days(3/13/2020). Strike we will choose a price that is closest and above the current stock price. Option type we want a call. Time in force is good for day (gfd). So our code will look like this and its translation in Robinhood:" }, { "code": null, "e": 2799, "s": 2681, "text": "robin_stocks.orders.order_buy_option_limit(4.20, 'MSFT', 1, 2020-03-13, 185.00, optionType='call', timeInForce='gfd')" }, { "code": null, "e": 2837, "s": 2799, "text": "MSFT MARCH 13, 2020 185 CALL AT $4.20" }, { "code": null, "e": 2977, "s": 2837, "text": "If we run this code in Python the order will be sent. However, it does not necessarily that the order executed. Here’s the full code below:" }, { "code": null, "e": 3023, "s": 2977, "text": "Access to my Microsoft gains and losses here!" }, { "code": null, "e": 3080, "s": 3023, "text": "I also have tutoring and career guidance available here!" } ]
Python - Change column names and row indexes in Pandas DataFrame
Pandas is a python library offering many features for data analysis which is not available in python standard library. One such feature is the use of Data Frames. They are rectangular grids representing columns and rows. While creating a Data frame, we decide on the names of the columns and refer them in subsequent data manipulation. But there may be a situation when we need to change the name of the columns after the data frame has been created. In this article, we will see how to achieve that. This is the most preferred method as we can change both the column and row index using this method. We just pass in the old and new values as a dictionary of key-value pairs to this method and save the data frame with a new name. Live Demo import pandas as pd df = pd.DataFrame({ 'ColumnA': [23, 92, 32], 'ColumnB': [54, 76, 43], 'ColumnC': [16, 45, 10] }, index=['10-20', '20-30', '30-40']) df_renamed = df.rename(columns={'ColumnA': 'Col1', 'ColumnB': 'Col2', 'ColumnC': 'Col3'}, index={'10-20': '1', '20-30': '2', '30-40': '3'}) print(df) print("\n",df_renamed) Running the above code gives us the following result: ColumnA ColumnB ColumnC 10-20 23 54 16 20-30 92 76 45 30-40 32 43 10 Col1 Col2 Col3 1 23 54 16 2 92 76 45 3 32 43 10 The df.columns can be assigned new column names directly. When the Data frame is used again, the new column names are referred. Live Demo import pandas as pd df = pd.DataFrame({ 'ColumnA': [23, 92, 32], 'ColumnB': [54, 76, 43], 'ColumnC': [16, 45, 10] }, index=['10-20', '20-30', '30-40']) df.columns=["Length","Breadth","Depth"] print(df) Running the above code gives us the following result: Length Breadth Depth 10-20 23 54 16 20-30 92 76 45 30-40 32 43 10 Pandas dataframe provides methods for adding prefix and suffix to the column names. We simply use this method to add the desired prefix which gets appended to each column names. Live Demo import pandas as pd df = pd.DataFrame({ 'ColA': [23, 92, 32], 'ColB': [54, 76, 43], 'ColC': [16, 45, 10] }, index=['10-20', '20-30', '30-40']) print(df.add_prefix('Jan-')) Running the above code gives us the following result: Jan-ColA Jan-ColB Jan-ColC 10-20 23 54 16 20-30 92 76 45 30-40 32 43 10
[ { "code": null, "e": 1563, "s": 1062, "text": "Pandas is a python library offering many features for data analysis which is not available in python standard library. One such feature is the use of Data Frames. They are rectangular grids representing columns and rows. While creating a Data frame, we decide on the names of the columns and refer them in subsequent data manipulation. But there may be a situation when we need to change the name of the columns after the data frame has been created. In this article, we will see how to achieve that." }, { "code": null, "e": 1793, "s": 1563, "text": "This is the most preferred method as we can change both the column and row index using this method. We just pass in the old and new values as a dictionary of key-value pairs to this method and save the data frame with a new name." }, { "code": null, "e": 1804, "s": 1793, "text": " Live Demo" }, { "code": null, "e": 2140, "s": 1804, "text": "import pandas as pd\n\ndf = pd.DataFrame({\n 'ColumnA': [23, 92, 32],\n 'ColumnB': [54, 76, 43],\n 'ColumnC': [16, 45, 10]\n},\nindex=['10-20', '20-30', '30-40'])\n\ndf_renamed = df.rename(columns={'ColumnA': 'Col1', 'ColumnB': 'Col2', 'ColumnC': 'Col3'},\nindex={'10-20': '1', '20-30': '2', '30-40': '3'})\nprint(df)\nprint(\"\\n\",df_renamed)" }, { "code": null, "e": 2194, "s": 2140, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 2512, "s": 2194, "text": " ColumnA ColumnB ColumnC\n10-20 23 54 16\n20-30 92 76 45\n30-40 32 43 10\n\n Col1 Col2 Col3\n1 23 54 16\n2 92 76 45\n3 32 43 10" }, { "code": null, "e": 2640, "s": 2512, "text": "The df.columns can be assigned new column names directly. When the Data frame is used again, the new column names are referred." }, { "code": null, "e": 2651, "s": 2640, "text": " Live Demo" }, { "code": null, "e": 2864, "s": 2651, "text": "import pandas as pd\n\ndf = pd.DataFrame({\n 'ColumnA': [23, 92, 32],\n 'ColumnB': [54, 76, 43],\n 'ColumnC': [16, 45, 10]\n},\nindex=['10-20', '20-30', '30-40'])\n\ndf.columns=[\"Length\",\"Breadth\",\"Depth\"]\nprint(df)" }, { "code": null, "e": 2918, "s": 2864, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 2999, "s": 2918, "text": " Length Breadth Depth\n10-20 23 54 16\n20-30 92 76 45\n30-40 32 43 10" }, { "code": null, "e": 3177, "s": 2999, "text": "Pandas dataframe provides methods for adding prefix and suffix to the column names. We simply use this method to add the desired prefix which gets appended to each column names." }, { "code": null, "e": 3188, "s": 3177, "text": " Live Demo" }, { "code": null, "e": 3371, "s": 3188, "text": "import pandas as pd\n\ndf = pd.DataFrame({\n 'ColA': [23, 92, 32],\n 'ColB': [54, 76, 43],\n 'ColC': [16, 45, 10]\n},\nindex=['10-20', '20-30', '30-40'])\n\nprint(df.add_prefix('Jan-'))" }, { "code": null, "e": 3425, "s": 3371, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 3593, "s": 3425, "text": " Jan-ColA Jan-ColB Jan-ColC\n10-20 23 54 16\n20-30 92 76 45\n30-40 32 43 10" } ]
Chaining of Array Methods in JavaScript - GeeksforGeeks
09 Jul, 2020 There are some methods in JavaScript that can loop through the array. We already have a knowledge about these array methods. Filter method ( filter())Map method ( map())Reduce method ( reduce())Find method ( find())Sort method ( sort()) Filter method ( filter()) Map method ( map()) Reduce method ( reduce()) Find method ( find()) Sort method ( sort()) We will learn how to chain all the array methods together. Example: const products = [ // Here we create an object and each // object has a name and a price { name: 'dress', price: 600 }, { name: 'cream', price: 60 }, { name: 'book', price: 200 }, { name: 'bottle', price: 50 }, { name: 'bedsheet', price: 350 }]; We want to do two things. Filter those elements whose price is greater than 100 using filter() method.Map those elements to a new array with a new sale price(50% off). Filter those elements whose price is greater than 100 using filter() method. Map those elements to a new array with a new sale price(50% off). Example: <script> const products = [ // Here we create an object and each // object has a name and a price { name: 'dress', price: 600 }, { name: 'cream', price: 60 }, { name: 'book', price: 200 }, { name: 'bottle', price: 50 }, { name: 'bedsheet', price: 350 } ]; // Filters the elements with // price above 100 const filtered = products.filter( product => product.price > 100); const sale = filtered.map(product => { return `the ${product.name} is ${product.price / 2} rupees`; }); // log the sale price to console console.log(sale);</script> Output: A quicker way to achieve this is by using array method chaining. All the array methods work on arrays and return arrays. So we can easily chain these methods. Example: <script> const products = [ { name: 'dress', price: 600 }, { name: 'cream', price: 60 }, { name: 'book', price: 200 }, { name: 'bottle', price: 50 }, { name: 'bedsheet', price: 350 } ]; // Writing the different array methods // on different lines increases the // readability const sale = products .filter(product => product.price > 100) .map(product => `the ${product.name} is ${product.price / 2} rupees`); document.write(sale);</script> Output: Conclusion: The output in both the cases remains same. The second method is called chaining of array methods which makes the code a little more concise.Since the filter method returns an array we can chain it to the map method which works on an array and vice-versa.This process can be applied to all the array methods which makes the code concise.This method is not only applicable for arrays, but we can use them on strings also, as long as the methods return and work on strings. The same principle will be applied. The output in both the cases remains same. The second method is called chaining of array methods which makes the code a little more concise. Since the filter method returns an array we can chain it to the map method which works on an array and vice-versa. This process can be applied to all the array methods which makes the code concise. This method is not only applicable for arrays, but we can use them on strings also, as long as the methods return and work on strings. The same principle will be applied. javascript-basics JavaScript-Misc JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request 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": 24474, "s": 24446, "text": "\n09 Jul, 2020" }, { "code": null, "e": 24599, "s": 24474, "text": "There are some methods in JavaScript that can loop through the array. We already have a knowledge about these array methods." }, { "code": null, "e": 24711, "s": 24599, "text": "Filter method ( filter())Map method ( map())Reduce method ( reduce())Find method ( find())Sort method ( sort())" }, { "code": null, "e": 24737, "s": 24711, "text": "Filter method ( filter())" }, { "code": null, "e": 24757, "s": 24737, "text": "Map method ( map())" }, { "code": null, "e": 24783, "s": 24757, "text": "Reduce method ( reduce())" }, { "code": null, "e": 24805, "s": 24783, "text": "Find method ( find())" }, { "code": null, "e": 24827, "s": 24805, "text": "Sort method ( sort())" }, { "code": null, "e": 24886, "s": 24827, "text": "We will learn how to chain all the array methods together." }, { "code": null, "e": 24895, "s": 24886, "text": "Example:" }, { "code": "const products = [ // Here we create an object and each // object has a name and a price { name: 'dress', price: 600 }, { name: 'cream', price: 60 }, { name: 'book', price: 200 }, { name: 'bottle', price: 50 }, { name: 'bedsheet', price: 350 }];", "e": 25164, "s": 24895, "text": null }, { "code": null, "e": 25190, "s": 25164, "text": "We want to do two things." }, { "code": null, "e": 25332, "s": 25190, "text": "Filter those elements whose price is greater than 100 using filter() method.Map those elements to a new array with a new sale price(50% off)." }, { "code": null, "e": 25409, "s": 25332, "text": "Filter those elements whose price is greater than 100 using filter() method." }, { "code": null, "e": 25475, "s": 25409, "text": "Map those elements to a new array with a new sale price(50% off)." }, { "code": null, "e": 25484, "s": 25475, "text": "Example:" }, { "code": "<script> const products = [ // Here we create an object and each // object has a name and a price { name: 'dress', price: 600 }, { name: 'cream', price: 60 }, { name: 'book', price: 200 }, { name: 'bottle', price: 50 }, { name: 'bedsheet', price: 350 } ]; // Filters the elements with // price above 100 const filtered = products.filter( product => product.price > 100); const sale = filtered.map(product => { return `the ${product.name} is ${product.price / 2} rupees`; }); // log the sale price to console console.log(sale);</script>", "e": 26127, "s": 25484, "text": null }, { "code": null, "e": 26135, "s": 26127, "text": "Output:" }, { "code": null, "e": 26294, "s": 26135, "text": "A quicker way to achieve this is by using array method chaining. All the array methods work on arrays and return arrays. So we can easily chain these methods." }, { "code": null, "e": 26303, "s": 26294, "text": "Example:" }, { "code": "<script> const products = [ { name: 'dress', price: 600 }, { name: 'cream', price: 60 }, { name: 'book', price: 200 }, { name: 'bottle', price: 50 }, { name: 'bedsheet', price: 350 } ]; // Writing the different array methods // on different lines increases the // readability const sale = products .filter(product => product.price > 100) .map(product => `the ${product.name} is ${product.price / 2} rupees`); document.write(sale);</script>", "e": 26829, "s": 26303, "text": null }, { "code": null, "e": 26837, "s": 26829, "text": "Output:" }, { "code": null, "e": 26849, "s": 26837, "text": "Conclusion:" }, { "code": null, "e": 27356, "s": 26849, "text": "The output in both the cases remains same. The second method is called chaining of array methods which makes the code a little more concise.Since the filter method returns an array we can chain it to the map method which works on an array and vice-versa.This process can be applied to all the array methods which makes the code concise.This method is not only applicable for arrays, but we can use them on strings also, as long as the methods return and work on strings. The same principle will be applied." }, { "code": null, "e": 27497, "s": 27356, "text": "The output in both the cases remains same. The second method is called chaining of array methods which makes the code a little more concise." }, { "code": null, "e": 27612, "s": 27497, "text": "Since the filter method returns an array we can chain it to the map method which works on an array and vice-versa." }, { "code": null, "e": 27695, "s": 27612, "text": "This process can be applied to all the array methods which makes the code concise." }, { "code": null, "e": 27866, "s": 27695, "text": "This method is not only applicable for arrays, but we can use them on strings also, as long as the methods return and work on strings. The same principle will be applied." }, { "code": null, "e": 27884, "s": 27866, "text": "javascript-basics" }, { "code": null, "e": 27900, "s": 27884, "text": "JavaScript-Misc" }, { "code": null, "e": 27911, "s": 27900, "text": "JavaScript" }, { "code": null, "e": 27928, "s": 27911, "text": "Web Technologies" }, { "code": null, "e": 28026, "s": 27928, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28071, "s": 28026, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28132, "s": 28071, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28204, "s": 28132, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28250, "s": 28204, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 28291, "s": 28250, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28333, "s": 28291, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28366, "s": 28333, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28409, "s": 28366, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28459, "s": 28409, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
JDBC - Statements, PreparedStatement and CallableStatement
Once a connection is obtained we can interact with the database. The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enable you to send SQL or PL/SQL commands and receive data from your database. They also define methods that help bridge data type differences between Java and SQL data types used in a database. The following table provides a summary of each interface's purpose to decide on the interface to use. Before you can use a Statement object to execute a SQL statement, you need to create one using the Connection object's createStatement( ) method, as in the following example − Statement stmt = null; try { stmt = conn.createStatement( ); . . . } catch (SQLException e) { . . . } finally { . . . } Once you've created a Statement object, you can then use it to execute an SQL statement with one of its three execute methods. boolean execute (String SQL): Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL. boolean execute (String SQL): Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL. int executeUpdate (String SQL) − Returns the number of rows affected by the execution of the SQL statement. Use this method to execute SQL statements for which you expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE statement. int executeUpdate (String SQL) − Returns the number of rows affected by the execution of the SQL statement. Use this method to execute SQL statements for which you expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE statement. ResultSet executeQuery (String SQL) − Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement. ResultSet executeQuery (String SQL) − Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement. Just as you close a Connection object to save database resources, for the same reason you should also close the Statement object. A simple call to the close() method will do the job. If you close the Connection object first, it will close the Statement object as well. However, you should always explicitly close the Statement object to ensure proper cleanup. Statement stmt = null; try { stmt = conn.createStatement( ); . . . } catch (SQLException e) { . . . } finally { stmt.close(); } For a better understanding, we suggest you to study the Statement - Example tutorial. The PreparedStatement interface extends the Statement interface, which gives you added functionality with a couple of advantages over a generic Statement object. This statement gives you the flexibility of supplying arguments dynamically. PreparedStatement pstmt = null; try { String SQL = "Update Employees SET age = ? WHERE id = ?"; pstmt = conn.prepareStatement(SQL); . . . } catch (SQLException e) { . . . } finally { . . . } All parameters in JDBC are represented by the ? symbol, which is known as the parameter marker. You must supply values for every parameter before executing the SQL statement. The setXXX() methods bind values to the parameters, where XXX represents the Java data type of the value you wish to bind to the input parameter. If you forget to supply the values, you will receive an SQLException. Each parameter marker is referred by its ordinal position. The first marker represents position 1, the next position 2, and so forth. This method differs from that of Java array indices, which starts at 0. All of the Statement object's methods for interacting with the database (a) execute(), (b) executeQuery(), and (c) executeUpdate() also work with the PreparedStatement object. However, the methods are modified to use SQL statements that can input the parameters. Just as you close a Statement object, for the same reason you should also close the PreparedStatement object. A simple call to the close() method will do the job. If you close the Connection object first, it will close the PreparedStatement object as well. However, you should always explicitly close the PreparedStatement object to ensure proper cleanup. PreparedStatement pstmt = null; try { String SQL = "Update Employees SET age = ? WHERE id = ?"; pstmt = conn.prepareStatement(SQL); . . . } catch (SQLException e) { . . . } finally { pstmt.close(); } For a better understanding, let us study Prepare - Example Code. Just as a Connection object creates the Statement and PreparedStatement objects, it also creates the CallableStatement object, which would be used to execute a call to a database stored procedure. Suppose, you need to execute the following Oracle stored procedure − CREATE OR REPLACE PROCEDURE getEmpName (EMP_ID IN NUMBER, EMP_FIRST OUT VARCHAR) AS BEGIN SELECT first INTO EMP_FIRST FROM Employees WHERE ID = EMP_ID; END; NOTE − Above stored procedure has been written for Oracle, but we are working with MySQL database so, let us write same stored procedure for MySQL as follows to create it in EMP database − DELIMITER $$ DROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$ CREATE PROCEDURE `EMP`.`getEmpName` (IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255)) BEGIN SELECT first INTO EMP_FIRST FROM Employees WHERE ID = EMP_ID; END $$ DELIMITER ; Three types of parameters exist: IN, OUT, and INOUT. The PreparedStatement object only uses the IN parameter. The CallableStatement object can use all the three. Here are the definitions of each − The following code snippet shows how to employ the Connection.prepareCall() method to instantiate a CallableStatement object based on the preceding stored procedure − CallableStatement cstmt = null; try { String SQL = "{call getEmpName (?, ?)}"; cstmt = conn.prepareCall (SQL); . . . } catch (SQLException e) { . . . } finally { . . . } The String variable SQL, represents the stored procedure, with parameter placeholders. Using the CallableStatement objects is much like using the PreparedStatement objects. You must bind values to all the parameters before executing the statement, or you will receive an SQLException. If you have IN parameters, just follow the same rules and techniques that apply to a PreparedStatement object; use the setXXX() method that corresponds to the Java data type you are binding. When you use OUT and INOUT parameters you must employ an additional CallableStatement method, registerOutParameter(). The registerOutParameter() method binds the JDBC data type, to the data type that the stored procedure is expected to return. Once you call your stored procedure, you retrieve the value from the OUT parameter with the appropriate getXXX() method. This method casts the retrieved value of SQL type to a Java data type. Just as you close other Statement object, for the same reason you should also close the CallableStatement object. A simple call to the close() method will do the job. If you close the Connection object first, it will close the CallableStatement object as well. However, you should always explicitly close the CallableStatement object to ensure proper cleanup. CallableStatement cstmt = null; try { String SQL = "{call getEmpName (?, ?)}"; cstmt = conn.prepareCall (SQL); . . . } catch (SQLException e) { . . . } finally { cstmt.close(); } For a better understanding, I would suggest to study Callable - Example Code. 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2417, "s": 2162, "text": "Once a connection is obtained we can interact with the database. The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enable you to send SQL or PL/SQL commands and receive data from your database." }, { "code": null, "e": 2533, "s": 2417, "text": "They also define methods that help bridge data type differences between Java and SQL data types used in a database." }, { "code": null, "e": 2635, "s": 2533, "text": "The following table provides a summary of each interface's purpose to decide on the interface to use." }, { "code": null, "e": 2811, "s": 2635, "text": "Before you can use a Statement object to execute a SQL statement, you need to create one using the Connection object's createStatement( ) method, as in the following example −" }, { "code": null, "e": 2943, "s": 2811, "text": "Statement stmt = null;\ntry {\n stmt = conn.createStatement( );\n . . .\n}\ncatch (SQLException e) {\n . . .\n}\nfinally {\n . . .\n}" }, { "code": null, "e": 3070, "s": 2943, "text": "Once you've created a Statement object, you can then use it to execute an SQL statement with one of its three execute methods." }, { "code": null, "e": 3290, "s": 3070, "text": "boolean execute (String SQL): Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL." }, { "code": null, "e": 3510, "s": 3290, "text": "boolean execute (String SQL): Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL." }, { "code": null, "e": 3769, "s": 3510, "text": "int executeUpdate (String SQL) − Returns the number of rows affected by the execution of the SQL statement. Use this method to execute SQL statements for which you expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE statement." }, { "code": null, "e": 4028, "s": 3769, "text": "int executeUpdate (String SQL) − Returns the number of rows affected by the execution of the SQL statement. Use this method to execute SQL statements for which you expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE statement." }, { "code": null, "e": 4185, "s": 4028, "text": "ResultSet executeQuery (String SQL) − Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement." }, { "code": null, "e": 4342, "s": 4185, "text": "ResultSet executeQuery (String SQL) − Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement." }, { "code": null, "e": 4473, "s": 4342, "text": "Just as you close a Connection object to save database resources, for the same reason you should also close the Statement object." }, { "code": null, "e": 4703, "s": 4473, "text": "A simple call to the close() method will do the job. If you close the Connection object first, it will close the Statement object as well. However, you should always explicitly close the Statement object to ensure proper cleanup." }, { "code": null, "e": 4843, "s": 4703, "text": "Statement stmt = null;\ntry {\n stmt = conn.createStatement( );\n . . .\n}\ncatch (SQLException e) {\n . . .\n}\nfinally {\n stmt.close();\n}" }, { "code": null, "e": 4929, "s": 4843, "text": "For a better understanding, we suggest you to study the Statement - Example tutorial." }, { "code": null, "e": 5091, "s": 4929, "text": "The PreparedStatement interface extends the Statement interface, which gives you added functionality with a couple of advantages over a generic Statement object." }, { "code": null, "e": 5168, "s": 5091, "text": "This statement gives you the flexibility of supplying arguments dynamically." }, { "code": null, "e": 5374, "s": 5168, "text": "PreparedStatement pstmt = null;\ntry {\n String SQL = \"Update Employees SET age = ? WHERE id = ?\";\n pstmt = conn.prepareStatement(SQL);\n . . .\n}\ncatch (SQLException e) {\n . . .\n}\nfinally {\n . . .\n}" }, { "code": null, "e": 5549, "s": 5374, "text": "All parameters in JDBC are represented by the ? symbol, which is known as the parameter marker. You must supply values for every parameter before executing the SQL statement." }, { "code": null, "e": 5765, "s": 5549, "text": "The setXXX() methods bind values to the parameters, where XXX represents the Java data type of the value you wish to bind to the input parameter. If you forget to supply the values, you will receive an SQLException." }, { "code": null, "e": 5971, "s": 5765, "text": "Each parameter marker is referred by its ordinal position. The first marker represents position 1, the next position 2, and so forth. This method differs from that of Java array indices, which starts at 0." }, { "code": null, "e": 6234, "s": 5971, "text": "All of the Statement object's methods for interacting with the database (a) execute(), (b) executeQuery(), and (c) executeUpdate() also work with the PreparedStatement object. However, the methods are modified to use SQL statements that can input the parameters." }, { "code": null, "e": 6344, "s": 6234, "text": "Just as you close a Statement object, for the same reason you should also close the PreparedStatement object." }, { "code": null, "e": 6590, "s": 6344, "text": "A simple call to the close() method will do the job. If you close the Connection object first, it will close the PreparedStatement object as well. However, you should always explicitly close the PreparedStatement object to ensure proper cleanup." }, { "code": null, "e": 6805, "s": 6590, "text": "PreparedStatement pstmt = null;\ntry {\n String SQL = \"Update Employees SET age = ? WHERE id = ?\";\n pstmt = conn.prepareStatement(SQL);\n . . .\n}\ncatch (SQLException e) {\n . . .\n}\nfinally {\n pstmt.close();\n}" }, { "code": null, "e": 6870, "s": 6805, "text": "For a better understanding, let us study Prepare - Example Code." }, { "code": null, "e": 7067, "s": 6870, "text": "Just as a Connection object creates the Statement and PreparedStatement objects, it also creates the CallableStatement object, which would be used to execute a call to a database stored procedure." }, { "code": null, "e": 7136, "s": 7067, "text": "Suppose, you need to execute the following Oracle stored procedure −" }, { "code": null, "e": 7306, "s": 7136, "text": "CREATE OR REPLACE PROCEDURE getEmpName \n (EMP_ID IN NUMBER, EMP_FIRST OUT VARCHAR) AS\nBEGIN\n SELECT first INTO EMP_FIRST\n FROM Employees\n WHERE ID = EMP_ID;\nEND;" }, { "code": null, "e": 7495, "s": 7306, "text": "NOTE − Above stored procedure has been written for Oracle, but we are working with MySQL database so, let us write same stored procedure for MySQL as follows to create it in EMP database −" }, { "code": null, "e": 7737, "s": 7495, "text": "DELIMITER $$\n\nDROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$\nCREATE PROCEDURE `EMP`.`getEmpName` \n (IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))\nBEGIN\n SELECT first INTO EMP_FIRST\n FROM Employees\n WHERE ID = EMP_ID;\nEND $$\n\nDELIMITER ;" }, { "code": null, "e": 7899, "s": 7737, "text": "Three types of parameters exist: IN, OUT, and INOUT. The PreparedStatement object only uses the IN parameter. The CallableStatement object can use all the three." }, { "code": null, "e": 7934, "s": 7899, "text": "Here are the definitions of each −" }, { "code": null, "e": 8101, "s": 7934, "text": "The following code snippet shows how to employ the Connection.prepareCall() method to instantiate a CallableStatement object based on the preceding stored procedure −" }, { "code": null, "e": 8286, "s": 8101, "text": "CallableStatement cstmt = null;\ntry {\n String SQL = \"{call getEmpName (?, ?)}\";\n cstmt = conn.prepareCall (SQL);\n . . .\n}\ncatch (SQLException e) {\n . . .\n}\nfinally {\n . . .\n}" }, { "code": null, "e": 8373, "s": 8286, "text": "The String variable SQL, represents the stored procedure, with parameter placeholders." }, { "code": null, "e": 8571, "s": 8373, "text": "Using the CallableStatement objects is much like using the PreparedStatement objects. You must bind values to all the parameters before executing the statement, or you will receive an SQLException." }, { "code": null, "e": 8762, "s": 8571, "text": "If you have IN parameters, just follow the same rules and techniques that apply to a PreparedStatement object; use the setXXX() method that corresponds to the Java data type you are binding." }, { "code": null, "e": 9006, "s": 8762, "text": "When you use OUT and INOUT parameters you must employ an additional CallableStatement method, registerOutParameter(). The registerOutParameter() method binds the JDBC data type, to the data type that the stored procedure is expected to return." }, { "code": null, "e": 9198, "s": 9006, "text": "Once you call your stored procedure, you retrieve the value from the OUT parameter with the appropriate getXXX() method. This method casts the retrieved value of SQL type to a Java data type." }, { "code": null, "e": 9312, "s": 9198, "text": "Just as you close other Statement object, for the same reason you should also close the CallableStatement object." }, { "code": null, "e": 9558, "s": 9312, "text": "A simple call to the close() method will do the job. If you close the Connection object first, it will close the CallableStatement object as well. However, you should always explicitly close the CallableStatement object to ensure proper cleanup." }, { "code": null, "e": 9752, "s": 9558, "text": "CallableStatement cstmt = null;\ntry {\n String SQL = \"{call getEmpName (?, ?)}\";\n cstmt = conn.prepareCall (SQL);\n . . .\n}\ncatch (SQLException e) {\n . . .\n}\nfinally {\n cstmt.close();\n}" }, { "code": null, "e": 9830, "s": 9752, "text": "For a better understanding, I would suggest to study Callable - Example Code." }, { "code": null, "e": 9863, "s": 9830, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 9879, "s": 9863, "text": " Malhar Lathkar" }, { "code": null, "e": 9912, "s": 9879, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 9928, "s": 9912, "text": " Malhar Lathkar" }, { "code": null, "e": 9963, "s": 9928, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9977, "s": 9963, "text": " Anadi Sharma" }, { "code": null, "e": 10011, "s": 9977, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 10025, "s": 10011, "text": " Tushar Kale" }, { "code": null, "e": 10062, "s": 10025, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 10077, "s": 10062, "text": " Monica Mittal" }, { "code": null, "e": 10110, "s": 10077, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 10129, "s": 10110, "text": " Arnab Chakraborty" }, { "code": null, "e": 10136, "s": 10129, "text": " Print" }, { "code": null, "e": 10147, "s": 10136, "text": " Add Notes" } ]
C program to check if a given string is Keyword or not - GeeksforGeeks
06 Feb, 2019 Given a string, the task is to write a program that checks if the given string is a keyword or not. Keywords are reserved words which cannot be used as variable names. There are 32 keywords in C programming language. Examples: Input: str = "geeks" Output: geeks is not a keyword Input: str = "for" Output: for is a keyword // C program to check whether a given// string is a keyword or not#include <stdbool.h>#include <stdio.h>#include <string.h> // Function to check whether the given// string is a keyword or not// Returns 'true' if the string is a KEYWORD.bool isKeyword(char* str){ if (!strcmp(str, "auto") || !strcmp(str, "default") || !strcmp(str, "signed") || !strcmp(str, "enum") ||!strcmp(str, "extern") || !strcmp(str, "for") || !strcmp(str, "register") || !strcmp(str, "if") || !strcmp(str, "else") || !strcmp(str, "int") || !strcmp(str, "while") || !strcmp(str, "do") || !strcmp(str, "break") || !strcmp(str, "continue") || !strcmp(str, "double") || !strcmp(str, "float") || !strcmp(str, "return") || !strcmp(str, "char") || !strcmp(str, "case") || !strcmp(str, "const") || !strcmp(str, "sizeof") || !strcmp(str, "long") || !strcmp(str, "short") || !strcmp(str, "typedef") || !strcmp(str, "switch") || !strcmp(str, "unsigned") || !strcmp(str, "void") || !strcmp(str, "static") || !strcmp(str, "struct") || !strcmp(str, "goto") || !strcmp(str, "union") || !strcmp(str, "volatile")) return (true); return (false);} // Driver codeint main(){ isKeyword("geeks") ? printf("Yes\n") : printf("No\n"); isKeyword("for") ? printf("Yes\n") : printf("No\n"); return 0;} No Yes C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments rand() and srand() in C/C++ fork() in C Command line arguments in C/C++ Substring in C++ Function Pointer in C Strings in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File UDP Server-Client implementation in C Header files in C/C++ and its uses
[ { "code": null, "e": 24334, "s": 24306, "text": "\n06 Feb, 2019" }, { "code": null, "e": 24434, "s": 24334, "text": "Given a string, the task is to write a program that checks if the given string is a keyword or not." }, { "code": null, "e": 24502, "s": 24434, "text": "Keywords are reserved words which cannot be used as variable names." }, { "code": null, "e": 24551, "s": 24502, "text": "There are 32 keywords in C programming language." }, { "code": null, "e": 24561, "s": 24551, "text": "Examples:" }, { "code": null, "e": 24659, "s": 24561, "text": "Input: str = \"geeks\"\nOutput: geeks is not a keyword\n\nInput: str = \"for\"\nOutput: for is a keyword\n" }, { "code": "// C program to check whether a given// string is a keyword or not#include <stdbool.h>#include <stdio.h>#include <string.h> // Function to check whether the given// string is a keyword or not// Returns 'true' if the string is a KEYWORD.bool isKeyword(char* str){ if (!strcmp(str, \"auto\") || !strcmp(str, \"default\") || !strcmp(str, \"signed\") || !strcmp(str, \"enum\") ||!strcmp(str, \"extern\") || !strcmp(str, \"for\") || !strcmp(str, \"register\") || !strcmp(str, \"if\") || !strcmp(str, \"else\") || !strcmp(str, \"int\") || !strcmp(str, \"while\") || !strcmp(str, \"do\") || !strcmp(str, \"break\") || !strcmp(str, \"continue\") || !strcmp(str, \"double\") || !strcmp(str, \"float\") || !strcmp(str, \"return\") || !strcmp(str, \"char\") || !strcmp(str, \"case\") || !strcmp(str, \"const\") || !strcmp(str, \"sizeof\") || !strcmp(str, \"long\") || !strcmp(str, \"short\") || !strcmp(str, \"typedef\") || !strcmp(str, \"switch\") || !strcmp(str, \"unsigned\") || !strcmp(str, \"void\") || !strcmp(str, \"static\") || !strcmp(str, \"struct\") || !strcmp(str, \"goto\") || !strcmp(str, \"union\") || !strcmp(str, \"volatile\")) return (true); return (false);} // Driver codeint main(){ isKeyword(\"geeks\") ? printf(\"Yes\\n\") : printf(\"No\\n\"); isKeyword(\"for\") ? printf(\"Yes\\n\") : printf(\"No\\n\"); return 0;}", "e": 26083, "s": 24659, "text": null }, { "code": null, "e": 26091, "s": 26083, "text": "No\nYes\n" }, { "code": null, "e": 26102, "s": 26091, "text": "C Language" }, { "code": null, "e": 26113, "s": 26102, "text": "C Programs" }, { "code": null, "e": 26211, "s": 26113, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26220, "s": 26211, "text": "Comments" }, { "code": null, "e": 26233, "s": 26220, "text": "Old Comments" }, { "code": null, "e": 26261, "s": 26233, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 26273, "s": 26261, "text": "fork() in C" }, { "code": null, "e": 26305, "s": 26273, "text": "Command line arguments in C/C++" }, { "code": null, "e": 26322, "s": 26305, "text": "Substring in C++" }, { "code": null, "e": 26344, "s": 26322, "text": "Function Pointer in C" }, { "code": null, "e": 26357, "s": 26344, "text": "Strings in C" }, { "code": null, "e": 26398, "s": 26357, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 26439, "s": 26398, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 26477, "s": 26439, "text": "UDP Server-Client implementation in C" } ]
Java Applet | Implementing Flood Fill algorithm - GeeksforGeeks
11 May, 2021 Flood Fill Algorithm is to replace a certain closed or a similarly colored field with a specified color. The use of the FloodFill algorithm can be seen in paints and other games such as minesweeper.In this article, FloodFill is used for a connected area by a specified color, in Java Applet by using the FloodFill algorithm.There are two approaches that can be used: Recursive approach (limited usage as it crashes for a larger area)Using queue (more reliable) Recursive approach (limited usage as it crashes for a larger area) Using queue (more reliable) Examples: For image 1: For image 1: Output (floodfilled at position 35, 35): Output (floodfilled at position 35, 35): Output (floodfilled at position 35, 35): Output (floodfilled at position 1, 1): For image 2: For image 2: Output(floodfilled at position 35, 35) : Output(floodfilled at position 35, 35) : Output(floodfilled at position 35, 35) : Output (floodfilled at position 1, 1): /> For image 3: For image 3: Output(floodfilled at position 35, 35) : Output(floodfilled at position 35, 35) : Output(floodfilled at position 35, 35) : Output (floodfilled at position 1, 1): Program 1: To implement floodfill algorithm in Java Applet using recursion:Note: To run the program, use an offline IDE such as Netbeans, Eclipse, etc. Please download the input images and put them along with the class file. Otherwise, the program might yield an “Can’t read the input file” error. Java // Java Program to implement floodfill algorithm// in Java Applet(using recursion)import java.awt.*;import javax.swing.*;import java.awt.image.*;import java.io.*;import javax.imageio.ImageIO; public class floodfill extends JApplet { public void init() { } // paint function public void paint(Graphics g) { BufferedImage i = null; try { // Input the image to be used for FloodFill // The output is shown for 3 images // image1, image2 and image2 i = ImageIO.read(new File("image1.jpg")); // floodfill with color red at point 35, 35 // get color of image at 35, 35 Color c = new Color(i.getRGB(35, 35)); flood(i, g, 35, 35, c, Color.red); // draw the image after floodfill g.drawImage(i, 100, 100, this); } catch (Exception e) { JOptionPane.showMessageDialog(this, e.getMessage()); } // draw the image after floodfill g.drawImage(i, 100, 100, this); } // function to floodfill the image public void flood(BufferedImage i, Graphics g, int x, int y, Color c, Color c1) { if (x >= 1 && y >= 1 && x < i.getWidth() && y < i.getHeight()) { // find the color at point x, y Color c2 = new Color(i.getRGB(x, y)); // if there is no boundary (the color is almost // same as the color of the point where // floodfill is to be applied if (Math.abs(c2.getGreen() - c.getGreen()) < 30 && Math.abs(c2.getRed() - c.getRed()) < 30 && Math.abs(c2.getBlue() - c.getBlue()) < 30) { // change the color of the pixel of image i.setRGB(x, y, c1.getRGB()); g.drawImage(i, 100, 100, this); // floodfill in all possible directions flood(i, g, x, y + 1, c, c1); flood(i, g, x + 1, y, c, c1); flood(i, g, x - 1, y, c, c1); flood(i, g, x, y - 1, c, c1); } } }} Output: for image 1: Input: Output : for image 2: Input: Output : for image 3: Input: Output : Note: If a larger area is flood filled (at coordinate 1, 1) using the recursive approach, then recursive algorithm might get crashed.Example: floodfill the larger side of image Input: Output: Explanation: Since the area to be covered is very large, therefore only some part is covered by the algorithm, and after that the program gets crashed. Program 2: To implement floodfill algorithm in Java Applet using queue:Note: To run the program, use an offline IDE such as Netbeans, Eclipse, etc. Please download the input images and put them along with the class file. Otherwise, the program might yield an “Can’t read the input file” error. Java // Java Program to implement floodfill algorithm// in Java Applet(using queue)import java.awt.*;import javax.swing.*;import java.awt.image.*;import java.io.*;import javax.imageio.ImageIO; public class floodfill extends JApplet { public void init() { } // paint function public void paint(Graphics g) { BufferedImage i = null; try { // Input the image to be used for FloodFill // The output is shown for 3 images // image1, image2 and image2 i = ImageIO.read(new File("image1.jpg")); // floodfill with color red at point 1, 1 // get color of image at 1, 1 // if 35, 35 point is floodfilled it will floodfill // the smaller area Color c = new Color(i.getRGB(1, 1)); flood(i, g, 1, 1, c, Color.red); // draw the image after floodfill g.drawImage(i, 100, 100, this); } catch (Exception e) { JOptionPane.showMessageDialog(this, e.getMessage()); } // draw the image after floodfill g.drawImage(i, 100, 100, this); } // function to floodfill the image using queue public void flood(BufferedImage i, Graphics g, int x1, int y1, Color c, Color c1) { // create a stack using array int stx[] = new int[100000]; int sty[] = new int[100000], f, r, x, y; // create a front and rear f = r = 0; // initialize them stx[0] = x1; sty[0] = y1; // while front is greater than rear while (f >= r) { // pop element out x = stx[r]; y = sty[r++]; if (x >= 1 && y >= 1 && x < i.getWidth() && y < i.getHeight()) { // find the color at point x, y Color c2 = new Color(i.getRGB(x, y)); // if there is no boundary (the color is almost // same as the color of the point where // floodfill is to be applied if (Math.abs(c2.getGreen() - c.getGreen()) < 30 && Math.abs(c2.getRed() - c.getRed()) < 30 && Math.abs(c2.getBlue() - c.getBlue()) < 30) { // change the color of the pixel of image i.setRGB(x, y, c1.getRGB()); g.drawImage(i, 100, 100, this); // floodfill in all possible directions // store them in queue stx[f] = x; sty[f++] = y + 1; stx[f] = x; sty[f++] = y - 1; stx[f] = x + 1; sty[f++] = y; stx[f] = x - 1; sty[f++] = y; } } } }} Output: For image 1: Input: For image 1: Input: Output (floodfilled at position 35, 35): Output (floodfilled at position 1, 1): For image 2: Input: Output(floodfilled at position 35, 35) : Output (floodfilled at position 1, 1): For image 3: Input: Output(floodfilled at position 35, 35) : Output (floodfilled at position 1, 1): sweetyty java-applet Java Java Programs Recursion Recursion Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Initializing a List in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 25092, "s": 25064, "text": "\n11 May, 2021" }, { "code": null, "e": 25460, "s": 25092, "text": "Flood Fill Algorithm is to replace a certain closed or a similarly colored field with a specified color. The use of the FloodFill algorithm can be seen in paints and other games such as minesweeper.In this article, FloodFill is used for a connected area by a specified color, in Java Applet by using the FloodFill algorithm.There are two approaches that can be used: " }, { "code": null, "e": 25554, "s": 25460, "text": "Recursive approach (limited usage as it crashes for a larger area)Using queue (more reliable)" }, { "code": null, "e": 25621, "s": 25554, "text": "Recursive approach (limited usage as it crashes for a larger area)" }, { "code": null, "e": 25649, "s": 25621, "text": "Using queue (more reliable)" }, { "code": null, "e": 25661, "s": 25649, "text": "Examples: " }, { "code": null, "e": 25676, "s": 25661, "text": "For image 1: " }, { "code": null, "e": 25691, "s": 25676, "text": "For image 1: " }, { "code": null, "e": 25734, "s": 25691, "text": "Output (floodfilled at position 35, 35): " }, { "code": null, "e": 25777, "s": 25734, "text": "Output (floodfilled at position 35, 35): " }, { "code": null, "e": 25820, "s": 25777, "text": "Output (floodfilled at position 35, 35): " }, { "code": null, "e": 25863, "s": 25822, "text": "Output (floodfilled at position 1, 1): " }, { "code": null, "e": 25878, "s": 25863, "text": "For image 2: " }, { "code": null, "e": 25893, "s": 25878, "text": "For image 2: " }, { "code": null, "e": 25936, "s": 25893, "text": "Output(floodfilled at position 35, 35) : " }, { "code": null, "e": 25979, "s": 25936, "text": "Output(floodfilled at position 35, 35) : " }, { "code": null, "e": 26022, "s": 25979, "text": "Output(floodfilled at position 35, 35) : " }, { "code": null, "e": 26063, "s": 26022, "text": "Output (floodfilled at position 1, 1): " }, { "code": null, "e": 26066, "s": 26063, "text": "/>" }, { "code": null, "e": 26081, "s": 26066, "text": "For image 3: " }, { "code": null, "e": 26096, "s": 26081, "text": "For image 3: " }, { "code": null, "e": 26139, "s": 26096, "text": "Output(floodfilled at position 35, 35) : " }, { "code": null, "e": 26182, "s": 26139, "text": "Output(floodfilled at position 35, 35) : " }, { "code": null, "e": 26225, "s": 26182, "text": "Output(floodfilled at position 35, 35) : " }, { "code": null, "e": 26266, "s": 26225, "text": "Output (floodfilled at position 1, 1): " }, { "code": null, "e": 26565, "s": 26266, "text": "Program 1: To implement floodfill algorithm in Java Applet using recursion:Note: To run the program, use an offline IDE such as Netbeans, Eclipse, etc. Please download the input images and put them along with the class file. Otherwise, the program might yield an “Can’t read the input file” error. " }, { "code": null, "e": 26570, "s": 26565, "text": "Java" }, { "code": "// Java Program to implement floodfill algorithm// in Java Applet(using recursion)import java.awt.*;import javax.swing.*;import java.awt.image.*;import java.io.*;import javax.imageio.ImageIO; public class floodfill extends JApplet { public void init() { } // paint function public void paint(Graphics g) { BufferedImage i = null; try { // Input the image to be used for FloodFill // The output is shown for 3 images // image1, image2 and image2 i = ImageIO.read(new File(\"image1.jpg\")); // floodfill with color red at point 35, 35 // get color of image at 35, 35 Color c = new Color(i.getRGB(35, 35)); flood(i, g, 35, 35, c, Color.red); // draw the image after floodfill g.drawImage(i, 100, 100, this); } catch (Exception e) { JOptionPane.showMessageDialog(this, e.getMessage()); } // draw the image after floodfill g.drawImage(i, 100, 100, this); } // function to floodfill the image public void flood(BufferedImage i, Graphics g, int x, int y, Color c, Color c1) { if (x >= 1 && y >= 1 && x < i.getWidth() && y < i.getHeight()) { // find the color at point x, y Color c2 = new Color(i.getRGB(x, y)); // if there is no boundary (the color is almost // same as the color of the point where // floodfill is to be applied if (Math.abs(c2.getGreen() - c.getGreen()) < 30 && Math.abs(c2.getRed() - c.getRed()) < 30 && Math.abs(c2.getBlue() - c.getBlue()) < 30) { // change the color of the pixel of image i.setRGB(x, y, c1.getRGB()); g.drawImage(i, 100, 100, this); // floodfill in all possible directions flood(i, g, x, y + 1, c, c1); flood(i, g, x + 1, y, c, c1); flood(i, g, x - 1, y, c, c1); flood(i, g, x, y - 1, c, c1); } } }}", "e": 28779, "s": 26570, "text": null }, { "code": null, "e": 28789, "s": 28779, "text": "Output: " }, { "code": null, "e": 28811, "s": 28789, "text": "for image 1: Input: " }, { "code": null, "e": 28822, "s": 28811, "text": "Output : " }, { "code": null, "e": 28846, "s": 28824, "text": "for image 2: Input: " }, { "code": null, "e": 28857, "s": 28846, "text": "Output : " }, { "code": null, "e": 28881, "s": 28859, "text": "for image 3: Input: " }, { "code": null, "e": 28892, "s": 28881, "text": "Output : " }, { "code": null, "e": 29036, "s": 28892, "text": "Note: If a larger area is flood filled (at coordinate 1, 1) using the recursive approach, then recursive algorithm might get crashed.Example: " }, { "code": null, "e": 29078, "s": 29036, "text": "floodfill the larger side of image\nInput:" }, { "code": null, "e": 29086, "s": 29078, "text": "Output:" }, { "code": null, "e": 29240, "s": 29086, "text": "Explanation:\nSince the area to be covered is very large, \ntherefore only some part is covered by the algorithm, \nand after that the program gets crashed." }, { "code": null, "e": 29535, "s": 29240, "text": "Program 2: To implement floodfill algorithm in Java Applet using queue:Note: To run the program, use an offline IDE such as Netbeans, Eclipse, etc. Please download the input images and put them along with the class file. Otherwise, the program might yield an “Can’t read the input file” error. " }, { "code": null, "e": 29540, "s": 29535, "text": "Java" }, { "code": "// Java Program to implement floodfill algorithm// in Java Applet(using queue)import java.awt.*;import javax.swing.*;import java.awt.image.*;import java.io.*;import javax.imageio.ImageIO; public class floodfill extends JApplet { public void init() { } // paint function public void paint(Graphics g) { BufferedImage i = null; try { // Input the image to be used for FloodFill // The output is shown for 3 images // image1, image2 and image2 i = ImageIO.read(new File(\"image1.jpg\")); // floodfill with color red at point 1, 1 // get color of image at 1, 1 // if 35, 35 point is floodfilled it will floodfill // the smaller area Color c = new Color(i.getRGB(1, 1)); flood(i, g, 1, 1, c, Color.red); // draw the image after floodfill g.drawImage(i, 100, 100, this); } catch (Exception e) { JOptionPane.showMessageDialog(this, e.getMessage()); } // draw the image after floodfill g.drawImage(i, 100, 100, this); } // function to floodfill the image using queue public void flood(BufferedImage i, Graphics g, int x1, int y1, Color c, Color c1) { // create a stack using array int stx[] = new int[100000]; int sty[] = new int[100000], f, r, x, y; // create a front and rear f = r = 0; // initialize them stx[0] = x1; sty[0] = y1; // while front is greater than rear while (f >= r) { // pop element out x = stx[r]; y = sty[r++]; if (x >= 1 && y >= 1 && x < i.getWidth() && y < i.getHeight()) { // find the color at point x, y Color c2 = new Color(i.getRGB(x, y)); // if there is no boundary (the color is almost // same as the color of the point where // floodfill is to be applied if (Math.abs(c2.getGreen() - c.getGreen()) < 30 && Math.abs(c2.getRed() - c.getRed()) < 30 && Math.abs(c2.getBlue() - c.getBlue()) < 30) { // change the color of the pixel of image i.setRGB(x, y, c1.getRGB()); g.drawImage(i, 100, 100, this); // floodfill in all possible directions // store them in queue stx[f] = x; sty[f++] = y + 1; stx[f] = x; sty[f++] = y - 1; stx[f] = x + 1; sty[f++] = y; stx[f] = x - 1; sty[f++] = y; } } } }}", "e": 32445, "s": 29540, "text": null }, { "code": null, "e": 32475, "s": 32445, "text": "Output: For image 1: Input: " }, { "code": null, "e": 32497, "s": 32475, "text": "For image 1: Input: " }, { "code": null, "e": 32540, "s": 32497, "text": "Output (floodfilled at position 35, 35): " }, { "code": null, "e": 32581, "s": 32540, "text": "Output (floodfilled at position 1, 1): " }, { "code": null, "e": 32605, "s": 32583, "text": "For image 2: Input: " }, { "code": null, "e": 32648, "s": 32605, "text": "Output(floodfilled at position 35, 35) : " }, { "code": null, "e": 32689, "s": 32648, "text": "Output (floodfilled at position 1, 1): " }, { "code": null, "e": 32713, "s": 32691, "text": "For image 3: Input: " }, { "code": null, "e": 32756, "s": 32713, "text": "Output(floodfilled at position 35, 35) : " }, { "code": null, "e": 32797, "s": 32756, "text": "Output (floodfilled at position 1, 1): " }, { "code": null, "e": 32806, "s": 32797, "text": "sweetyty" }, { "code": null, "e": 32818, "s": 32806, "text": "java-applet" }, { "code": null, "e": 32823, "s": 32818, "text": "Java" }, { "code": null, "e": 32837, "s": 32823, "text": "Java Programs" }, { "code": null, "e": 32847, "s": 32837, "text": "Recursion" }, { "code": null, "e": 32857, "s": 32847, "text": "Recursion" }, { "code": null, "e": 32862, "s": 32857, "text": "Java" }, { "code": null, "e": 32960, "s": 32862, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32992, "s": 32960, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 33011, "s": 32992, "text": "Interfaces in Java" }, { "code": null, "e": 33029, "s": 33011, "text": "ArrayList in Java" }, { "code": null, "e": 33061, "s": 33029, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 33081, "s": 33061, "text": "Stack Class in Java" }, { "code": null, "e": 33109, "s": 33081, "text": "Initializing a List in Java" }, { "code": null, "e": 33153, "s": 33109, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 33179, "s": 33153, "text": "Java Programming Examples" }, { "code": null, "e": 33213, "s": 33179, "text": "Convert Double to Integer in Java" } ]
Python Program for Find minimum sum of factors of number
In this article, we will learn about the solution to the problem statement given below − Given a number input , find the minimum sum of factors of the given number. Here we will compute all the factors and their corresponding sum and then find the minimum among them. So to find the minimum sum of the product of number, we find the sum of prime factors of the product. Here is the iterative implementation for the problem − Live Demo #iterative approach def findMinSum(num): sum_ = 0 # Find factors of number and add to the sum i = 2 while(i * i <= num): while(num % i == 0): sum_ += i num /= i i += 1 sum_ += num return sum_ # Driver Code num = 12 print (findMinSum(num)) 7 All the variables are declared in the global frame as shown in the figure given below − In this article, we learned about the approach to Find the minimum sum of factors of a number.
[ { "code": null, "e": 1151, "s": 1062, "text": "In this article, we will learn about the solution to the problem statement given below −" }, { "code": null, "e": 1227, "s": 1151, "text": "Given a number input , find the minimum sum of factors of the given number." }, { "code": null, "e": 1330, "s": 1227, "text": "Here we will compute all the factors and their corresponding sum and then find the minimum among them." }, { "code": null, "e": 1432, "s": 1330, "text": "So to find the minimum sum of the product of number, we find the sum of prime factors of the product." }, { "code": null, "e": 1487, "s": 1432, "text": "Here is the iterative implementation for the problem −" }, { "code": null, "e": 1498, "s": 1487, "text": " Live Demo" }, { "code": null, "e": 1785, "s": 1498, "text": "#iterative approach\ndef findMinSum(num):\n sum_ = 0\n # Find factors of number and add to the sum\n i = 2\n while(i * i <= num):\n while(num % i == 0):\n sum_ += i\n num /= i\n i += 1\n sum_ += num\n return sum_\n# Driver Code\nnum = 12\nprint (findMinSum(num))" }, { "code": null, "e": 1787, "s": 1785, "text": "7" }, { "code": null, "e": 1875, "s": 1787, "text": "All the variables are declared in the global frame as shown in the figure given below −" }, { "code": null, "e": 1970, "s": 1875, "text": "In this article, we learned about the approach to Find the minimum sum of factors of a number." } ]
How to display a bold text inside the JTextArea in Java?
A JTextArea class can extend JTextComponent and allow a user to enter multiple lines of text inside it. A JTextArea can generate a CaretListener interface, which can listen to caret update events. We can set a font to a text inside the JTextArea by using setFont() method. import java.awt.*; import javax.swing.*; public class JTextAreaTextBoldTest extends JFrame { private JTextArea textArea; public JTextAreaTextBoldTest() { setTitle("JTextAreaTextBold Test"); setLayout(new BorderLayout()); textArea= new JTextArea(); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); Font boldFont=new Font(textArea.getFont().getName(), Font.BOLD, textArea.getFont().getSize()); textArea.setFont(boldFont); // bold text add(textArea); setSize(375, 250); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[]args) { new JTextAreaTextBoldTest(); } }
[ { "code": null, "e": 1335, "s": 1062, "text": "A JTextArea class can extend JTextComponent and allow a user to enter multiple lines of text inside it. A JTextArea can generate a CaretListener interface, which can listen to caret update events. We can set a font to a text inside the JTextArea by using setFont() method." }, { "code": null, "e": 2078, "s": 1335, "text": "import java.awt.*;\nimport javax.swing.*;\npublic class JTextAreaTextBoldTest extends JFrame {\n private JTextArea textArea;\n public JTextAreaTextBoldTest() {\n setTitle(\"JTextAreaTextBold Test\");\n setLayout(new BorderLayout());\n textArea= new JTextArea();\n textArea.setLineWrap(true);\n textArea.setWrapStyleWord(true);\n Font boldFont=new Font(textArea.getFont().getName(), Font.BOLD, textArea.getFont().getSize());\n textArea.setFont(boldFont); // bold text \n add(textArea);\n setSize(375, 250);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public static void main(String[]args) {\n new JTextAreaTextBoldTest();\n }\n}" } ]
How to handle exception inside a Python for loop?
You can handle exception inside a Python for loop just like you would in a normal code block. This doesn't cause any issues. For example, for i in range(5): try: if i % 2 == 0: raise ValueError("some error") print(i) except ValueError as e: print(e) This will give the output some error 1 some error 3 some error
[ { "code": null, "e": 1200, "s": 1062, "text": "You can handle exception inside a Python for loop just like you would in a normal code block. This doesn't cause any issues. For example," }, { "code": null, "e": 1339, "s": 1200, "text": "for i in range(5):\n try:\n if i % 2 == 0:\n raise ValueError(\"some error\")\n print(i)\nexcept ValueError as e:\n print(e)" }, { "code": null, "e": 1365, "s": 1339, "text": "This will give the output" }, { "code": null, "e": 1402, "s": 1365, "text": "some error\n1\nsome error\n3\nsome error" } ]
Tryit Editor v3.7
HTML id attribute Tryit: id as bookmark
[ { "code": null, "e": 28, "s": 10, "text": "HTML id attribute" } ]
What are cin, cout and cerr streams in C++?
cin, cout, cerr, and clog are streams that handle standard inputs and standard outputs. These are stream objects defined in iostream header file. std::cin is an object of class istream that represents the standard input stream oriented to narrow characters (of type char). It corresponds to the C stream stdin. The standard input stream is a source of characters determined by the environment. It is generally assumed to be input from an external source, such as the keyboard or a file. std::cout is an object of class ostream that represents the standard output stream oriented to narrow characters (of type char). It corresponds to the C stream stdout. The standard output stream is the default destination of characters determined by the environment. This destination may be shared with more standard objects (such as cerr or clog). The object cerr controls output to a stream buffer associated with the object stderr, declared in <cstdio>. It is used for outputting error to the standard output stream. Note − All the objects declared in this header share a peculiar property - you can assume they are constructed before any static objects you define, in a translation unit that includes <iostream>. Equally, you can assume that these objects are not destroyed before the destructors for any such static objects you define. (The output streams are, however, flushed during program termination.) Therefore, you can safely read from or write to the standard streams before program startup and after program termination. You can use these stream objects as follows − #include<iostream> int main() { int my_int; std::cin >> my_int; std::cout << my_int; std::cerr << "An error message"; return 0; } Then save this program to hello.cpp file. Finally navigate to the saved location of this file in the terminal/cmd and compile it using − $ g++ hello.cpp Run it using − $ ./a.out If you give it the input 15, this will give the output − 15 An error message
[ { "code": null, "e": 1208, "s": 1062, "text": "cin, cout, cerr, and clog are streams that handle standard inputs and standard outputs. These are stream objects defined in iostream header file." }, { "code": null, "e": 1549, "s": 1208, "text": "std::cin is an object of class istream that represents the standard input stream oriented to narrow characters (of type char). It corresponds to the C stream stdin. The standard input stream is a source of characters determined by the environment. It is generally assumed to be input from an external source, such as the keyboard or a file." }, { "code": null, "e": 1898, "s": 1549, "text": "std::cout is an object of class ostream that represents the standard output stream oriented to narrow characters (of type char). It corresponds to the C stream stdout. The standard output stream is the default destination of characters determined by the environment. This destination may be shared with more standard objects (such as cerr or clog)." }, { "code": null, "e": 2069, "s": 1898, "text": "The object cerr controls output to a stream buffer associated with the object stderr, declared in <cstdio>. It is used for outputting error to the standard output stream." }, { "code": null, "e": 2584, "s": 2069, "text": "Note − All the objects declared in this header share a peculiar property - you can assume they are constructed before any static objects you define, in a translation unit that includes <iostream>. Equally, you can assume that these objects are not destroyed before the destructors for any such static objects you define. (The output streams are, however, flushed during program termination.) Therefore, you can safely read from or write to the standard streams before program startup and after program termination." }, { "code": null, "e": 2630, "s": 2584, "text": "You can use these stream objects as follows −" }, { "code": null, "e": 2775, "s": 2630, "text": "#include<iostream>\nint main() {\n int my_int;\n std::cin >> my_int;\n std::cout << my_int;\n std::cerr << \"An error message\";\n return 0;\n}" }, { "code": null, "e": 2912, "s": 2775, "text": "Then save this program to hello.cpp file. Finally navigate to the saved location of this file in the terminal/cmd and compile it using −" }, { "code": null, "e": 2928, "s": 2912, "text": "$ g++ hello.cpp" }, { "code": null, "e": 2943, "s": 2928, "text": "Run it using −" }, { "code": null, "e": 2953, "s": 2943, "text": "$ ./a.out" }, { "code": null, "e": 3010, "s": 2953, "text": "If you give it the input 15, this will give the output −" }, { "code": null, "e": 3030, "s": 3010, "text": "15 An error message" } ]
gzip - Unix, Linux Command
gunzip, gzip - compress or expand files gunzip [ -acfhlLnNrtvV ] [-S suffix] [ name ... ] gzip [ -acdfhlLnNrtvV19 ] [-S suffix] [ name ... ] Gzip reduces the size of the named files using Lempel-Ziv coding (LZ77). Whenever possible, each file is replaced by one with the extension .gz, while keeping the same ownership modes, access and modification times. (The default extension is -gz for VMS, z for MSDOS, OS/2 FAT, Windows NT FAT and Atari.) If no files are specified, or if a file name is "-", the standard input is compressed to the standard output. Gzip will only attempt to compress regular files. In particular, it will ignore symbolic links. If the compressed file name is too long for its file system, gzip truncates it. Gzipattempts to truncate only the parts of the file name longer than 3 characters. (A part is delimited by dots.) If the name consists of small parts only, the longest parts are truncated. For example, if file names are limited to 14 characters, gzip.msdos.exe is compressed to gzi.msd.exe.gz. Names are not truncated on systems which do not have a limit on file name length. By default, gzip keeps the original file name and timestamp in the compressed file. These are used when decompressing the file with the -N option. This is useful when the compressed file name was truncated or when the time stamp was not preserved after a file transfer. Compressed files can be restored to their original form using gzip -d or gunzip or zcat. If the original name saved in the compressed file is not suitable for its file system, a new name is constructed from the original one to make it legal. Example-1: To Compress A File Using "gzip": $ gzip test.sh output: $ lstest.sh $ gzip test.sh $ lstest.sh.gz Example-2: To Decompress A File Using The "gzip" Command: $ gzip -d test.sh.gz output: $ lstest.sh.gz $ gzip -d test.sh.gz $ lstest.sh Example-3: Force A File To Be Compressed: $ gzip -f filenatest.sh output: $ lstest.sh $ gzip -f test.sh $ lstest.sh.gz Example-4: To Keep The Uncompressed File: $ gzip -k filename output: $ lstest.sh $ gzip -k test.sh $ lstest.sh test.sh.gz Example-5: Compress Every File In A Folder And Subfolders: $ gzip -r /tmp output: $ ls /tmp/abc xyz $ gzip -r /tmp/ $ ls /tmp/abc.gz xyz.gz Example-6: To Test The Validity Of A Compressed File: $ gzip -t test.sh.gz output: no output on screen if compressed file is valid. Example-7: To Change The Compression Level: To get minimum compression at the fastest speed: $ gzip -1 test.sh To get maximum compression at the slowest speed: $ gzip -9 test.sh output: test.sh.gz 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10617, "s": 10577, "text": "gunzip, gzip - compress or expand files" }, { "code": null, "e": 10718, "s": 10617, "text": "gunzip [ -acfhlLnNrtvV ] [-S suffix] [ name ... ]\ngzip [ -acdfhlLnNrtvV19 ] [-S suffix] [ name ... ]" }, { "code": null, "e": 11229, "s": 10718, "text": "Gzip reduces the size of the named files using Lempel-Ziv coding (LZ77). Whenever possible, each file is replaced by one with the extension .gz, while keeping the same ownership modes, access and modification times. (The default extension is -gz for VMS, z for MSDOS, OS/2 FAT, Windows NT FAT and Atari.) If no files are specified, or if a file name is \"-\", the standard input is compressed to the standard output. Gzip will only attempt to compress regular files. In particular, it will ignore symbolic links." }, { "code": null, "e": 11685, "s": 11229, "text": "If the compressed file name is too long for its file system, gzip truncates it. Gzipattempts to truncate only the parts of the file name longer than 3 characters. (A part is delimited by dots.) If the name consists of small parts only, the longest parts are truncated. For example, if file names are limited to 14 characters, gzip.msdos.exe is compressed to gzi.msd.exe.gz. Names are not truncated on systems which do not have a limit on file name length." }, { "code": null, "e": 11955, "s": 11685, "text": "By default, gzip keeps the original file name and timestamp in the compressed file. These are used when decompressing the file with the -N option. This is useful when the compressed file name was truncated or when the time stamp was not preserved after a file transfer." }, { "code": null, "e": 12197, "s": 11955, "text": "Compressed files can be restored to their original form using gzip -d or gunzip or zcat. If the original name saved in the compressed file is not suitable for its file system, a new name is constructed from the original one to make it legal." }, { "code": null, "e": 12208, "s": 12197, "text": "Example-1:" }, { "code": null, "e": 12241, "s": 12208, "text": "To Compress A File Using \"gzip\":" }, { "code": null, "e": 12256, "s": 12241, "text": "$ gzip test.sh" }, { "code": null, "e": 12264, "s": 12256, "text": "output:" }, { "code": null, "e": 12276, "s": 12264, "text": "$ lstest.sh" }, { "code": null, "e": 12291, "s": 12276, "text": "$ gzip test.sh" }, { "code": null, "e": 12306, "s": 12291, "text": "$ lstest.sh.gz" }, { "code": null, "e": 12317, "s": 12306, "text": "Example-2:" }, { "code": null, "e": 12364, "s": 12317, "text": "To Decompress A File Using The \"gzip\" Command:" }, { "code": null, "e": 12385, "s": 12364, "text": "$ gzip -d test.sh.gz" }, { "code": null, "e": 12393, "s": 12385, "text": "output:" }, { "code": null, "e": 12408, "s": 12393, "text": "$ lstest.sh.gz" }, { "code": null, "e": 12429, "s": 12408, "text": "$ gzip -d test.sh.gz" }, { "code": null, "e": 12441, "s": 12429, "text": "$ lstest.sh" }, { "code": null, "e": 12452, "s": 12441, "text": "Example-3:" }, { "code": null, "e": 12483, "s": 12452, "text": "Force A File To Be Compressed:" }, { "code": null, "e": 12507, "s": 12483, "text": "$ gzip -f filenatest.sh" }, { "code": null, "e": 12515, "s": 12507, "text": "output:" }, { "code": null, "e": 12527, "s": 12515, "text": "$ lstest.sh" }, { "code": null, "e": 12545, "s": 12527, "text": "$ gzip -f test.sh" }, { "code": null, "e": 12560, "s": 12545, "text": "$ lstest.sh.gz" }, { "code": null, "e": 12571, "s": 12560, "text": "Example-4:" }, { "code": null, "e": 12602, "s": 12571, "text": "To Keep The Uncompressed File:" }, { "code": null, "e": 12621, "s": 12602, "text": "$ gzip -k filename" }, { "code": null, "e": 12629, "s": 12621, "text": "output:" }, { "code": null, "e": 12641, "s": 12629, "text": "$ lstest.sh" }, { "code": null, "e": 12659, "s": 12641, "text": "$ gzip -k test.sh" }, { "code": null, "e": 12683, "s": 12659, "text": "$ lstest.sh test.sh.gz" }, { "code": null, "e": 12694, "s": 12683, "text": "Example-5:" }, { "code": null, "e": 12742, "s": 12694, "text": "Compress Every File In A Folder And Subfolders:" }, { "code": null, "e": 12757, "s": 12742, "text": "$ gzip -r /tmp" }, { "code": null, "e": 12765, "s": 12757, "text": "output:" }, { "code": null, "e": 12784, "s": 12765, "text": "$ ls /tmp/abc xyz" }, { "code": null, "e": 12800, "s": 12784, "text": "$ gzip -r /tmp/" }, { "code": null, "e": 12825, "s": 12800, "text": "$ ls /tmp/abc.gz xyz.gz" }, { "code": null, "e": 12836, "s": 12825, "text": "Example-6:" }, { "code": null, "e": 12879, "s": 12836, "text": "To Test The Validity Of A Compressed File:" }, { "code": null, "e": 12900, "s": 12879, "text": "$ gzip -t test.sh.gz" }, { "code": null, "e": 12908, "s": 12900, "text": "output:" }, { "code": null, "e": 12957, "s": 12908, "text": "no output on screen if compressed file is valid." }, { "code": null, "e": 12968, "s": 12957, "text": "Example-7:" }, { "code": null, "e": 13001, "s": 12968, "text": "To Change The Compression Level:" }, { "code": null, "e": 13050, "s": 13001, "text": "To get minimum compression at the fastest speed:" }, { "code": null, "e": 13068, "s": 13050, "text": "$ gzip -1 test.sh" }, { "code": null, "e": 13117, "s": 13068, "text": "To get maximum compression at the slowest speed:" }, { "code": null, "e": 13135, "s": 13117, "text": "$ gzip -9 test.sh" }, { "code": null, "e": 13143, "s": 13135, "text": "output:" }, { "code": null, "e": 13154, "s": 13143, "text": "test.sh.gz" }, { "code": null, "e": 13189, "s": 13154, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 13217, "s": 13189, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 13251, "s": 13217, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 13268, "s": 13251, "text": " Frahaan Hussain" }, { "code": null, "e": 13301, "s": 13268, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 13312, "s": 13301, "text": " Pradeep D" }, { "code": null, "e": 13347, "s": 13312, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13363, "s": 13347, "text": " Musab Zayadneh" }, { "code": null, "e": 13396, "s": 13363, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 13408, "s": 13396, "text": " GUHARAJANM" }, { "code": null, "e": 13440, "s": 13408, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 13448, "s": 13440, "text": " Uplatz" }, { "code": null, "e": 13455, "s": 13448, "text": " Print" }, { "code": null, "e": 13466, "s": 13455, "text": " Add Notes" } ]
Kotlin Operators - GeeksforGeeks
11 Apr, 2022 Operators are the special symbols that perform different operation on operands. For example + and – are operators that perform addition and subtraction respectively. Like Java, Kotlin contains different kinds of operators. Arithmetic operator Relation operator Assignment operator Unary operator Logical operator Bitwise operator Arithmetic Operators – Kotlin fun main(args: Array<String>){ var a = 20 var b = 4 println("a + b = " + (a + b)) println("a - b = " + (a - b)) println("a * b = " + (a.times(b))) println("a / b = " + (a / b)) println("a % b = " + (a.rem(b)))} Output: a + b = 24 a - b = 16 a * b = 80 a / b = 5 a % b = 0 Relational Operators – Kotlin fun main(args: Array<String>){ var c = 30 var d = 40 println("c > d = "+(c>d)) println("c < d = "+(c.compareTo(d) < 0)) println("c >= d = "+(c>=d)) println("c <= d = "+(c.compareTo(d) <= 0)) println("c == d = "+(c==d)) println("c != d = "+(!(c?.equals(d) ?: (d === null))))} Output: c > d = false c < d = true c >= d = false c <= d = true c == d = false c != d = true Assignment Operators – Kotlin fun main(args : Array<String>){ var a = 10 var b = 5 a+=b println(a) a-=b println(a) a*=b println(a) a/=b println(a) a%=b println(a) } Output: 15 10 50 10 0 Unary Operators – Kotlin fun main(args : Array<String>){ var e=10 var flag = true println("First print then increment: "+ e++) println("First increment then print: "+ ++e) println("First print then decrement: "+ e--) println("First decrement then print: "+ --e)} Output: First print then increment: 10 First increment then print: 12 First print then decrement: 12 First decrement then print: 10 Logical Operators – Kotlin fun main(args : Array<String>){ var x = 100 var y = 25 var z = 10 var result = false if(x > y && x > z) println(x) if(x < y || x > z) println(y) if( result.not()) println("Logical operators")} Output: 100 25 Logical operators Bitwise Operators – Kotlin fun main(args: Array<String>){ println("5 signed shift left by 1 bit: " + 5.shl(1)) println("10 signed shift right by 2 bits: : " + 10.shr(2)) println("12 unsigned shift right by 2 bits: " + 12.ushr(2)) println("36 bitwise and 22: " + 36.and(22)) println("36 bitwise or 22: " + 36.or(22)) println("36 bitwise xor 22: " + 36.xor(22)) println("14 bitwise inverse is: " + 14.inv())} Output: 5 signed shift left by 1 bit: 10 10 signed shift right by 2 bits: : 2 12 unsigned shift right by 2 bits: 3 36 bitwise and 22: 4 36 bitwise or 22: 54 36 bitwise xor 22: 50 14 bitwise inverse is: -15 Rajeev Joshi clintra surinderdawra388 ayushpandey3july Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Android RecyclerView in Kotlin Retrofit with Kotlin Coroutine in Android MVP (Model View Presenter) Architecture Pattern in Android with Example Android Menus MVC (Model View Controller) Architecture Pattern in Android with Example How to Convert Kotlin Code to Java Code in Android Studio? How to Build a Weather App in Android? How to Get Current Location in Android? ImageView in Android with Example ScrollView in Android
[ { "code": null, "e": 24036, "s": 24008, "text": "\n11 Apr, 2022" }, { "code": null, "e": 24260, "s": 24036, "text": "Operators are the special symbols that perform different operation on operands. For example + and – are operators that perform addition and subtraction respectively. Like Java, Kotlin contains different kinds of operators. " }, { "code": null, "e": 24280, "s": 24260, "text": "Arithmetic operator" }, { "code": null, "e": 24298, "s": 24280, "text": "Relation operator" }, { "code": null, "e": 24318, "s": 24298, "text": "Assignment operator" }, { "code": null, "e": 24333, "s": 24318, "text": "Unary operator" }, { "code": null, "e": 24350, "s": 24333, "text": "Logical operator" }, { "code": null, "e": 24369, "s": 24350, "text": "Bitwise operator " }, { "code": null, "e": 24393, "s": 24369, "text": "Arithmetic Operators – " }, { "code": null, "e": 24400, "s": 24393, "text": "Kotlin" }, { "code": "fun main(args: Array<String>){ var a = 20 var b = 4 println(\"a + b = \" + (a + b)) println(\"a - b = \" + (a - b)) println(\"a * b = \" + (a.times(b))) println(\"a / b = \" + (a / b)) println(\"a % b = \" + (a.rem(b)))}", "e": 24642, "s": 24400, "text": null }, { "code": null, "e": 24652, "s": 24642, "text": "Output: " }, { "code": null, "e": 24705, "s": 24652, "text": "a + b = 24\na - b = 16\na * b = 80\na / b = 5\na % b = 0" }, { "code": null, "e": 24730, "s": 24705, "text": " Relational Operators – " }, { "code": null, "e": 24737, "s": 24730, "text": "Kotlin" }, { "code": "fun main(args: Array<String>){ var c = 30 var d = 40 println(\"c > d = \"+(c>d)) println(\"c < d = \"+(c.compareTo(d) < 0)) println(\"c >= d = \"+(c>=d)) println(\"c <= d = \"+(c.compareTo(d) <= 0)) println(\"c == d = \"+(c==d)) println(\"c != d = \"+(!(c?.equals(d) ?: (d === null))))}", "e": 25036, "s": 24737, "text": null }, { "code": null, "e": 25046, "s": 25036, "text": "Output: " }, { "code": null, "e": 25131, "s": 25046, "text": "c > d = false\nc < d = true\nc >= d = false\nc <= d = true\nc == d = false\nc != d = true" }, { "code": null, "e": 25155, "s": 25131, "text": "Assignment Operators – " }, { "code": null, "e": 25162, "s": 25155, "text": "Kotlin" }, { "code": "fun main(args : Array<String>){ var a = 10 var b = 5 a+=b println(a) a-=b println(a) a*=b println(a) a/=b println(a) a%=b println(a) }", "e": 25330, "s": 25162, "text": null }, { "code": null, "e": 25340, "s": 25330, "text": "Output: " }, { "code": null, "e": 25354, "s": 25340, "text": "15\n10\n50\n10\n0" }, { "code": null, "e": 25373, "s": 25354, "text": "Unary Operators – " }, { "code": null, "e": 25380, "s": 25373, "text": "Kotlin" }, { "code": "fun main(args : Array<String>){ var e=10 var flag = true println(\"First print then increment: \"+ e++) println(\"First increment then print: \"+ ++e) println(\"First print then decrement: \"+ e--) println(\"First decrement then print: \"+ --e)}", "e": 25636, "s": 25380, "text": null }, { "code": null, "e": 25646, "s": 25636, "text": "Output: " }, { "code": null, "e": 25770, "s": 25646, "text": "First print then increment: 10\nFirst increment then print: 12\nFirst print then decrement: 12\nFirst decrement then print: 10" }, { "code": null, "e": 25791, "s": 25770, "text": "Logical Operators – " }, { "code": null, "e": 25798, "s": 25791, "text": "Kotlin" }, { "code": "fun main(args : Array<String>){ var x = 100 var y = 25 var z = 10 var result = false if(x > y && x > z) println(x) if(x < y || x > z) println(y) if( result.not()) println(\"Logical operators\")}", "e": 26024, "s": 25798, "text": null }, { "code": null, "e": 26034, "s": 26024, "text": "Output: " }, { "code": null, "e": 26059, "s": 26034, "text": "100\n25\nLogical operators" }, { "code": null, "e": 26080, "s": 26059, "text": "Bitwise Operators – " }, { "code": null, "e": 26087, "s": 26080, "text": "Kotlin" }, { "code": "fun main(args: Array<String>){ println(\"5 signed shift left by 1 bit: \" + 5.shl(1)) println(\"10 signed shift right by 2 bits: : \" + 10.shr(2)) println(\"12 unsigned shift right by 2 bits: \" + 12.ushr(2)) println(\"36 bitwise and 22: \" + 36.and(22)) println(\"36 bitwise or 22: \" + 36.or(22)) println(\"36 bitwise xor 22: \" + 36.xor(22)) println(\"14 bitwise inverse is: \" + 14.inv())}", "e": 26489, "s": 26087, "text": null }, { "code": null, "e": 26498, "s": 26489, "text": "Output: " }, { "code": null, "e": 26697, "s": 26498, "text": "5 signed shift left by 1 bit: 10\n10 signed shift right by 2 bits: : 2\n12 unsigned shift right by 2 bits: 3\n36 bitwise and 22: 4\n36 bitwise or 22: 54\n36 bitwise xor 22: 50\n14 bitwise inverse is: -15" }, { "code": null, "e": 26710, "s": 26697, "text": "Rajeev Joshi" }, { "code": null, "e": 26718, "s": 26710, "text": "clintra" }, { "code": null, "e": 26735, "s": 26718, "text": "surinderdawra388" }, { "code": null, "e": 26752, "s": 26735, "text": "ayushpandey3july" }, { "code": null, "e": 26759, "s": 26752, "text": "Kotlin" }, { "code": null, "e": 26857, "s": 26759, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26866, "s": 26857, "text": "Comments" }, { "code": null, "e": 26879, "s": 26866, "text": "Old Comments" }, { "code": null, "e": 26910, "s": 26879, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 26952, "s": 26910, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 27024, "s": 26952, "text": "MVP (Model View Presenter) Architecture Pattern in Android with Example" }, { "code": null, "e": 27038, "s": 27024, "text": "Android Menus" }, { "code": null, "e": 27111, "s": 27038, "text": "MVC (Model View Controller) Architecture Pattern in Android with Example" }, { "code": null, "e": 27170, "s": 27111, "text": "How to Convert Kotlin Code to Java Code in Android Studio?" }, { "code": null, "e": 27209, "s": 27170, "text": "How to Build a Weather App in Android?" }, { "code": null, "e": 27249, "s": 27209, "text": "How to Get Current Location in Android?" }, { "code": null, "e": 27283, "s": 27249, "text": "ImageView in Android with Example" } ]
SSID Full Form - GeeksforGeeks
12 Jun, 2020 Service Set Identifier(SSID) is used to identify any 802.11 Wireless Local Area Network (WLAN). It is also used by clients to identify and connect to the particular Wireless Network. To discuss in layman’s terms, it is the SSID we see when we are trying to connect your device(phone/computer) to a Wireless Network. Below is an screenshot that shows the SSID’s available while browsing for available networks to connect. It can be a 32 character string which is case-sensitive and can contain letters, numbers, symbols, punctuation marks and even a blank space. The following six characters are considered invalid characters in an SSID: /, ", +, ], TAB, trailing spaces And the first character cannot be any of: !, #, ; Types of SSID : Hidden –The SSID will not be visible for all the clients. Only the user who is aware of the exact SSID can jump on that Wireless Network.Broadcasted –The SSID is broadcasted over the network. Anyone can find that network and hop on. Hidden –The SSID will not be visible for all the clients. Only the user who is aware of the exact SSID can jump on that Wireless Network. Broadcasted –The SSID is broadcasted over the network. Anyone can find that network and hop on. Characteristics : SSID helps distinguish one network from other networks.An SSID can be broadcasted in either 2.4GHz or 5GHz.Each SSID can have its own security in place with either open, WEP, WPA, WPA2, etc...A Guest SSID may allow users to connect to the Internet but not to other local devices or facilities like intranet.An SSID can be analogous to a Virtual LAN(VLAN) to segment traffic or to provide different facilities or access levels. SSID helps distinguish one network from other networks. An SSID can be broadcasted in either 2.4GHz or 5GHz. Each SSID can have its own security in place with either open, WEP, WPA, WPA2, etc... A Guest SSID may allow users to connect to the Internet but not to other local devices or facilities like intranet. An SSID can be analogous to a Virtual LAN(VLAN) to segment traffic or to provide different facilities or access levels. Advantages : In multiple Wireless Network Environments it would be chaotic to send and receive data. To avoid this, the SSID is included in each packet that is sent over a Wireless Network It ensures that the data being sent over the air arrives at the correct location. Helps differentiate WLANs from one another Roaming is efficient if the SSIDs of both the WLANs are same. A single Access Point can broadcast multiple SSIDs at the same time. It will help in logically diving Users(For Example: In a School Environment, a single SSID can be used by all the Teachers and a different SSID can be assigned to all the Students, each with different polices and functions.). Disadvantages : Though security is added with hidden networks, it is still easy to hack While encryption is strong, most people use trivial passwords and access would become easier Any attacker can broadcast an SSID with the same name as our’s and steal our personal information An attacker can also spoof the “disassociation frame” as it came from the wireless bridge and send it to one of the clients connected; the client immediately reconnects revealing the SSID. Picked Computer Networks Full Form Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Advanced Encryption Standard (AES) Introduction and IPv4 Datagram Header Intrusion Detection System (IDS) Secure Socket Layer (SSL) Cryptography and its Types DBA Full Form RDBMS Full Form CDMA Full Form HTTP Full Form SCTP Full Form
[ { "code": null, "e": 25755, "s": 25727, "text": "\n12 Jun, 2020" }, { "code": null, "e": 26176, "s": 25755, "text": "Service Set Identifier(SSID) is used to identify any 802.11 Wireless Local Area Network (WLAN). It is also used by clients to identify and connect to the particular Wireless Network. To discuss in layman’s terms, it is the SSID we see when we are trying to connect your device(phone/computer) to a Wireless Network. Below is an screenshot that shows the SSID’s available while browsing for available networks to connect." }, { "code": null, "e": 26317, "s": 26176, "text": "It can be a 32 character string which is case-sensitive and can contain letters, numbers, symbols, punctuation marks and even a blank space." }, { "code": null, "e": 26392, "s": 26317, "text": "The following six characters are considered invalid characters in an SSID:" }, { "code": null, "e": 26427, "s": 26392, "text": "/, \", +, ], TAB, trailing spaces " }, { "code": null, "e": 26469, "s": 26427, "text": "And the first character cannot be any of:" }, { "code": null, "e": 26479, "s": 26469, "text": "!, #, ; " }, { "code": null, "e": 26495, "s": 26479, "text": "Types of SSID :" }, { "code": null, "e": 26728, "s": 26495, "text": "Hidden –The SSID will not be visible for all the clients. Only the user who is aware of the exact SSID can jump on that Wireless Network.Broadcasted –The SSID is broadcasted over the network. Anyone can find that network and hop on." }, { "code": null, "e": 26866, "s": 26728, "text": "Hidden –The SSID will not be visible for all the clients. Only the user who is aware of the exact SSID can jump on that Wireless Network." }, { "code": null, "e": 26962, "s": 26866, "text": "Broadcasted –The SSID is broadcasted over the network. Anyone can find that network and hop on." }, { "code": null, "e": 26980, "s": 26962, "text": "Characteristics :" }, { "code": null, "e": 27407, "s": 26980, "text": "SSID helps distinguish one network from other networks.An SSID can be broadcasted in either 2.4GHz or 5GHz.Each SSID can have its own security in place with either open, WEP, WPA, WPA2, etc...A Guest SSID may allow users to connect to the Internet but not to other local devices or facilities like intranet.An SSID can be analogous to a Virtual LAN(VLAN) to segment traffic or to provide different facilities or access levels." }, { "code": null, "e": 27463, "s": 27407, "text": "SSID helps distinguish one network from other networks." }, { "code": null, "e": 27516, "s": 27463, "text": "An SSID can be broadcasted in either 2.4GHz or 5GHz." }, { "code": null, "e": 27602, "s": 27516, "text": "Each SSID can have its own security in place with either open, WEP, WPA, WPA2, etc..." }, { "code": null, "e": 27718, "s": 27602, "text": "A Guest SSID may allow users to connect to the Internet but not to other local devices or facilities like intranet." }, { "code": null, "e": 27838, "s": 27718, "text": "An SSID can be analogous to a Virtual LAN(VLAN) to segment traffic or to provide different facilities or access levels." }, { "code": null, "e": 27851, "s": 27838, "text": "Advantages :" }, { "code": null, "e": 28027, "s": 27851, "text": "In multiple Wireless Network Environments it would be chaotic to send and receive data. To avoid this, the SSID is included in each packet that is sent over a Wireless Network" }, { "code": null, "e": 28109, "s": 28027, "text": "It ensures that the data being sent over the air arrives at the correct location." }, { "code": null, "e": 28152, "s": 28109, "text": "Helps differentiate WLANs from one another" }, { "code": null, "e": 28214, "s": 28152, "text": "Roaming is efficient if the SSIDs of both the WLANs are same." }, { "code": null, "e": 28509, "s": 28214, "text": "A single Access Point can broadcast multiple SSIDs at the same time. It will help in logically diving Users(For Example: In a School Environment, a single SSID can be used by all the Teachers and a different SSID can be assigned to all the Students, each with different polices and functions.)." }, { "code": null, "e": 28525, "s": 28509, "text": "Disadvantages :" }, { "code": null, "e": 28597, "s": 28525, "text": "Though security is added with hidden networks, it is still easy to hack" }, { "code": null, "e": 28690, "s": 28597, "text": "While encryption is strong, most people use trivial passwords and access would become easier" }, { "code": null, "e": 28788, "s": 28690, "text": "Any attacker can broadcast an SSID with the same name as our’s and steal our personal information" }, { "code": null, "e": 28977, "s": 28788, "text": "An attacker can also spoof the “disassociation frame” as it came from the wireless bridge and send it to one of the clients connected; the client immediately reconnects revealing the SSID." }, { "code": null, "e": 28984, "s": 28977, "text": "Picked" }, { "code": null, "e": 29002, "s": 28984, "text": "Computer Networks" }, { "code": null, "e": 29012, "s": 29002, "text": "Full Form" }, { "code": null, "e": 29030, "s": 29012, "text": "Computer Networks" }, { "code": null, "e": 29128, "s": 29030, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29163, "s": 29128, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 29201, "s": 29163, "text": "Introduction and IPv4 Datagram Header" }, { "code": null, "e": 29234, "s": 29201, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 29260, "s": 29234, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 29287, "s": 29260, "text": "Cryptography and its Types" }, { "code": null, "e": 29301, "s": 29287, "text": "DBA Full Form" }, { "code": null, "e": 29317, "s": 29301, "text": "RDBMS Full Form" }, { "code": null, "e": 29332, "s": 29317, "text": "CDMA Full Form" }, { "code": null, "e": 29347, "s": 29332, "text": "HTTP Full Form" } ]
Create a Tic-Tac-Toe Game using jQuery - GeeksforGeeks
16 Nov, 2021 In this post, we are going to implement 2-player tic-tac-toe using jQuery. It is quite easy to develop with some simple validations and error checks. Player-1 starts playing the game and both the players make their moves in consecutive turns. The player who makes a straight 3-block chain wins the game. Here, we’ll be implementing this game on the front-end using simple logics and validation checks only.Prerequisites: Basic knowledge of some front-end technologies like HTML, CSS, jQuery and Bootstrap.Developing the layout: First of all, we will develop 3 * 3 grid layout and apply some CSS effects on the same. It should also show a text showing the turn of the player. It should also contain a button to reset the game whenever needed. HTML Code: html <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" /> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"> </script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"> </script> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous"> </head> <body> <!-- Heading --> <div class="container-fluid text-center"> <h1 style="color: white;">TIC-TAC-TOE</h1></div> <br> <br> <div class="container-fluid text-center"> <!-- Inform area for player's turn --> <h4 id="screen" style="color: white;"> PLAYER 1 TURN FOLLOWS </h4> </div> <br> <div class="container-fluid"> <div class="row"> <div class="col-lg-4"> </div> <div class="col-lg-4"> <!-- Playing Canvas --> <center> <table> <tr> <td colspan="3"> </tr> <tr> <td> <button class="sq1 r"></button> </td> <td> <button class="sq2 r"></button> </td> <td> <button class="sq3 r"></button> </td> </tr> <tr> <td> <button class="sq4 r"></button> </td> <td> <button class="sq5 r"></button> </td> <td> <button class="sq6 r"></button> </td> </tr> <tr> <td> <button class="sq7 r"></button> </td> <td> <button class="sq8 r"></button> </td> <td> <button class="sq9 r"></button> </td> </tr> </table> <br> <br> <!-- Reset button for Game --> <input type="button" class="reset btn btn-lg btn-danger btn-block" value="RESET" onClick="reset()" /> </center> </div> <div class="col-lg-4"> </div> </div> </div></body> </html> CSS Code: CSS <!-- Applying CSS Properties --><style> body { background-color: #000000; } button { height: 80px; width: 80px; background-color: white; border: 0px transparent; border-radius: 50%; margin: 4px; padding: 4px; } .fa { font-size: 48px; color: black; } .reset { padding: 8px; } .reset:hover { opacity: 0.8; } </style> Output: Implementing Logic: Now, we need to implement the following steps in our main code for mimicking the logic for a tic-tac-toe game. Consecutive player turns: The consecutive turns will follow after the first player plays his move. Also, the text notifying the player’s turn should also be updated accordingly. JavaScript <!-- Consecutive player Turns --><script> // Flag variable for checking Turn// We'll be modifying our base logic in the// next steps as per requirements var turn = 1; $("button").click(function() { if(turn == 1) { $("#screen").text("PLAYER 2 TURN FOLLOWS"); // Check sign font from font-awesome $(this).addClass("fa fa-check"); turn = 2; } else { $("#screen").text("PLAYER 1 TURN FOLLOWS"); // Cross sign font from font-awesome $(this).addClass("fa fa-times"); turn = 1; }});</script> Mark/Notify invalid moves: Also, we need to ensure that the player on the turn should not play any invalid move. For this, we will check if the clicked button is not already used by other font class in the process. If it is already marked by a font, mark the move invalid for a short interval. JavaScript <!-- Script for checking any invalid moves -->$("button").click(function() { if($(this).hasClass("fa fa-times") || $(this).hasClass("fa fa-check")) { $(this).css("background-color", "red"); setTimeout(() => { $(this).css("background-color", "white"); }, 800); }}); Check for winning moves: We will develop a function that will check whether the player has completed the grid or not. For this, we need to check for 8 winning configurations of the player. We will send the font class to the function for checking the same. JavaScript <!-- Function to check the winning move -->function check(symbol) { if ($(".sq1").hasClass(symbol) && $(".sq2").hasClass(symbol) && $(".sq3").hasClass(symbol)) { $(".sq1").css("color", "green"); $(".sq2").css("color", "green"); $(".sq3").css("color", "green"); return true; } else if ($(".sq4").hasClass(symbol) && $(".sq5").hasClass(symbol) && $(".sq6").hasClass(symbol)) { $(".sq4").css("color", "green"); $(".sq5").css("color", "green"); $(".sq6").css("color", "green"); return true; } else if ($(".sq7").hasClass(symbol) && $(".sq8").hasClass(symbol) && $(".sq9").hasClass(symbol)) { $(".sq7").css("color", "green"); $(".sq8").css("color", "green"); $(".sq9").css("color", "green"); return true; } else if ($(".sq1").hasClass(symbol) && $(".sq4").hasClass(symbol) && $(".sq7").hasClass(symbol)) { $(".sq1").css("color", "green"); $(".sq4").css("color", "green"); $(".sq7").css("color", "green"); return true; } else if ($(".sq2").hasClass(symbol) && $(".sq5").hasClass(symbol) && $(".sq8").hasClass(symbol)) { $(".sq2").css("color", "green"); $(".sq5").css("color", "green"); $(".sq8").css("color", "green"); return true; } else if ($(".sq3").hasClass(symbol) && $(".sq6").hasClass(symbol) && $(".sq9").hasClass(symbol)) { $(".sq3").css("color", "green"); $(".sq6").css("color", "green"); $(".sq9").css("color", "green"); return true; } else if ($(".sq1").hasClass(symbol) && $(".sq5").hasClass(symbol) && $(".sq9").hasClass(symbol)) { $(".sq1").css("color", "green"); $(".sq5").css("color", "green"); $(".sq9").css("color", "green"); return true; } else if ($(".sq3").hasClass(symbol) && $(".sq5").hasClass(symbol) && $(".sq7").hasClass(symbol)) { $(".sq3").css("color", "green"); $(".sq5").css("color", "green"); $(".sq7").css("color", "green"); return true; } else { return false; }} Resetting the game: Clicking on this button will reset the game. JavaScript <!-- Resetting the game -->function reset(){ $("#screen").text("PLAYER 1 TURN FOLLOWS"); $("#screen").css("background-color", "transparent"); $(".r").removeClass("fa fa-check"); $(".r").removeClass("fa fa-times"); turn=1; // Reset Colors $(".sq1").css("color", "black"); $(".sq2").css("color", "black"); $(".sq3").css("color", "black"); $(".sq4").css("color", "black"); $(".sq5").css("color", "black"); $(".sq6").css("color", "black"); $(".sq7").css("color", "black"); $(".sq8").css("color", "black"); $(".sq9").css("color", "black"); } Output: Combining all the codes written above then it will be a complete tic-tac-toe game. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. simmytarika5 CSS-Misc HTML-Misc jQuery-Misc Bootstrap CSS HTML JQuery Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to pass data into a bootstrap modal? How to set Bootstrap Timepicker using datetimepicker library ? How to Show Images on Click using HTML ? How to change the background color of the active nav-item? Create a Homepage for Restaurant using HTML , CSS and Bootstrap 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)
[ { "code": null, "e": 24961, "s": 24933, "text": "\n16 Nov, 2021" }, { "code": null, "e": 25705, "s": 24961, "text": "In this post, we are going to implement 2-player tic-tac-toe using jQuery. It is quite easy to develop with some simple validations and error checks. Player-1 starts playing the game and both the players make their moves in consecutive turns. The player who makes a straight 3-block chain wins the game. Here, we’ll be implementing this game on the front-end using simple logics and validation checks only.Prerequisites: Basic knowledge of some front-end technologies like HTML, CSS, jQuery and Bootstrap.Developing the layout: First of all, we will develop 3 * 3 grid layout and apply some CSS effects on the same. It should also show a text showing the turn of the player. It should also contain a button to reset the game whenever needed. " }, { "code": null, "e": 25718, "s": 25705, "text": "HTML Code: " }, { "code": null, "e": 25723, "s": 25718, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge, chrome=1\" /> <script src=\"https://code.jquery.com/jquery-3.4.1.slim.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.7.0/css/all.css\" integrity=\"sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ\" crossorigin=\"anonymous\"> </head> <body> <!-- Heading --> <div class=\"container-fluid text-center\"> <h1 style=\"color: white;\">TIC-TAC-TOE</h1></div> <br> <br> <div class=\"container-fluid text-center\"> <!-- Inform area for player's turn --> <h4 id=\"screen\" style=\"color: white;\"> PLAYER 1 TURN FOLLOWS </h4> </div> <br> <div class=\"container-fluid\"> <div class=\"row\"> <div class=\"col-lg-4\"> </div> <div class=\"col-lg-4\"> <!-- Playing Canvas --> <center> <table> <tr> <td colspan=\"3\"> </tr> <tr> <td> <button class=\"sq1 r\"></button> </td> <td> <button class=\"sq2 r\"></button> </td> <td> <button class=\"sq3 r\"></button> </td> </tr> <tr> <td> <button class=\"sq4 r\"></button> </td> <td> <button class=\"sq5 r\"></button> </td> <td> <button class=\"sq6 r\"></button> </td> </tr> <tr> <td> <button class=\"sq7 r\"></button> </td> <td> <button class=\"sq8 r\"></button> </td> <td> <button class=\"sq9 r\"></button> </td> </tr> </table> <br> <br> <!-- Reset button for Game --> <input type=\"button\" class=\"reset btn btn-lg btn-danger btn-block\" value=\"RESET\" onClick=\"reset()\" /> </center> </div> <div class=\"col-lg-4\"> </div> </div> </div></body> </html>", "e": 28812, "s": 25723, "text": null }, { "code": null, "e": 28824, "s": 28812, "text": "CSS Code: " }, { "code": null, "e": 28828, "s": 28824, "text": "CSS" }, { "code": "<!-- Applying CSS Properties --><style> body { background-color: #000000; } button { height: 80px; width: 80px; background-color: white; border: 0px transparent; border-radius: 50%; margin: 4px; padding: 4px; } .fa { font-size: 48px; color: black; } .reset { padding: 8px; } .reset:hover { opacity: 0.8; } </style>", "e": 29261, "s": 28828, "text": null }, { "code": null, "e": 29271, "s": 29261, "text": "Output: " }, { "code": null, "e": 29404, "s": 29271, "text": "Implementing Logic: Now, we need to implement the following steps in our main code for mimicking the logic for a tic-tac-toe game. " }, { "code": null, "e": 29583, "s": 29404, "text": "Consecutive player turns: The consecutive turns will follow after the first player plays his move. Also, the text notifying the player’s turn should also be updated accordingly. " }, { "code": null, "e": 29594, "s": 29583, "text": "JavaScript" }, { "code": "<!-- Consecutive player Turns --><script> // Flag variable for checking Turn// We'll be modifying our base logic in the// next steps as per requirements var turn = 1; $(\"button\").click(function() { if(turn == 1) { $(\"#screen\").text(\"PLAYER 2 TURN FOLLOWS\"); // Check sign font from font-awesome $(this).addClass(\"fa fa-check\"); turn = 2; } else { $(\"#screen\").text(\"PLAYER 1 TURN FOLLOWS\"); // Cross sign font from font-awesome $(this).addClass(\"fa fa-times\"); turn = 1; }});</script>", "e": 30163, "s": 29594, "text": null }, { "code": null, "e": 30460, "s": 30165, "text": "Mark/Notify invalid moves: Also, we need to ensure that the player on the turn should not play any invalid move. For this, we will check if the clicked button is not already used by other font class in the process. If it is already marked by a font, mark the move invalid for a short interval. " }, { "code": null, "e": 30471, "s": 30460, "text": "JavaScript" }, { "code": "<!-- Script for checking any invalid moves -->$(\"button\").click(function() { if($(this).hasClass(\"fa fa-times\") || $(this).hasClass(\"fa fa-check\")) { $(this).css(\"background-color\", \"red\"); setTimeout(() => { $(this).css(\"background-color\", \"white\"); }, 800); }});", "e": 30801, "s": 30471, "text": null }, { "code": null, "e": 31061, "s": 30803, "text": "Check for winning moves: We will develop a function that will check whether the player has completed the grid or not. For this, we need to check for 8 winning configurations of the player. We will send the font class to the function for checking the same. " }, { "code": null, "e": 31072, "s": 31061, "text": "JavaScript" }, { "code": "<!-- Function to check the winning move -->function check(symbol) { if ($(\".sq1\").hasClass(symbol) && $(\".sq2\").hasClass(symbol) && $(\".sq3\").hasClass(symbol)) { $(\".sq1\").css(\"color\", \"green\"); $(\".sq2\").css(\"color\", \"green\"); $(\".sq3\").css(\"color\", \"green\"); return true; } else if ($(\".sq4\").hasClass(symbol) && $(\".sq5\").hasClass(symbol) && $(\".sq6\").hasClass(symbol)) { $(\".sq4\").css(\"color\", \"green\"); $(\".sq5\").css(\"color\", \"green\"); $(\".sq6\").css(\"color\", \"green\"); return true; } else if ($(\".sq7\").hasClass(symbol) && $(\".sq8\").hasClass(symbol) && $(\".sq9\").hasClass(symbol)) { $(\".sq7\").css(\"color\", \"green\"); $(\".sq8\").css(\"color\", \"green\"); $(\".sq9\").css(\"color\", \"green\"); return true; } else if ($(\".sq1\").hasClass(symbol) && $(\".sq4\").hasClass(symbol) && $(\".sq7\").hasClass(symbol)) { $(\".sq1\").css(\"color\", \"green\"); $(\".sq4\").css(\"color\", \"green\"); $(\".sq7\").css(\"color\", \"green\"); return true; } else if ($(\".sq2\").hasClass(symbol) && $(\".sq5\").hasClass(symbol) && $(\".sq8\").hasClass(symbol)) { $(\".sq2\").css(\"color\", \"green\"); $(\".sq5\").css(\"color\", \"green\"); $(\".sq8\").css(\"color\", \"green\"); return true; } else if ($(\".sq3\").hasClass(symbol) && $(\".sq6\").hasClass(symbol) && $(\".sq9\").hasClass(symbol)) { $(\".sq3\").css(\"color\", \"green\"); $(\".sq6\").css(\"color\", \"green\"); $(\".sq9\").css(\"color\", \"green\"); return true; } else if ($(\".sq1\").hasClass(symbol) && $(\".sq5\").hasClass(symbol) && $(\".sq9\").hasClass(symbol)) { $(\".sq1\").css(\"color\", \"green\"); $(\".sq5\").css(\"color\", \"green\"); $(\".sq9\").css(\"color\", \"green\"); return true; } else if ($(\".sq3\").hasClass(symbol) && $(\".sq5\").hasClass(symbol) && $(\".sq7\").hasClass(symbol)) { $(\".sq3\").css(\"color\", \"green\"); $(\".sq5\").css(\"color\", \"green\"); $(\".sq7\").css(\"color\", \"green\"); return true; } else { return false; }}", "e": 33316, "s": 31072, "text": null }, { "code": null, "e": 33382, "s": 33316, "text": "Resetting the game: Clicking on this button will reset the game. " }, { "code": null, "e": 33393, "s": 33382, "text": "JavaScript" }, { "code": "<!-- Resetting the game -->function reset(){ $(\"#screen\").text(\"PLAYER 1 TURN FOLLOWS\"); $(\"#screen\").css(\"background-color\", \"transparent\"); $(\".r\").removeClass(\"fa fa-check\"); $(\".r\").removeClass(\"fa fa-times\"); turn=1; // Reset Colors $(\".sq1\").css(\"color\", \"black\"); $(\".sq2\").css(\"color\", \"black\"); $(\".sq3\").css(\"color\", \"black\"); $(\".sq4\").css(\"color\", \"black\"); $(\".sq5\").css(\"color\", \"black\"); $(\".sq6\").css(\"color\", \"black\"); $(\".sq7\").css(\"color\", \"black\"); $(\".sq8\").css(\"color\", \"black\"); $(\".sq9\").css(\"color\", \"black\"); }", "e": 33961, "s": 33393, "text": null }, { "code": null, "e": 34054, "s": 33961, "text": "Output: Combining all the codes written above then it will be a complete tic-tac-toe game. " }, { "code": null, "e": 34193, "s": 34056, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 34206, "s": 34193, "text": "simmytarika5" }, { "code": null, "e": 34215, "s": 34206, "text": "CSS-Misc" }, { "code": null, "e": 34225, "s": 34215, "text": "HTML-Misc" }, { "code": null, "e": 34237, "s": 34225, "text": "jQuery-Misc" }, { "code": null, "e": 34247, "s": 34237, "text": "Bootstrap" }, { "code": null, "e": 34251, "s": 34247, "text": "CSS" }, { "code": null, "e": 34256, "s": 34251, "text": "HTML" }, { "code": null, "e": 34263, "s": 34256, "text": "JQuery" }, { "code": null, "e": 34280, "s": 34263, "text": "Web Technologies" }, { "code": null, "e": 34307, "s": 34280, "text": "Web technologies Questions" }, { "code": null, "e": 34312, "s": 34307, "text": "HTML" }, { "code": null, "e": 34410, "s": 34312, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34419, "s": 34410, "text": "Comments" }, { "code": null, "e": 34432, "s": 34419, "text": "Old Comments" }, { "code": null, "e": 34473, "s": 34432, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 34536, "s": 34473, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 34577, "s": 34536, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 34636, "s": 34577, "text": "How to change the background color of the active nav-item?" }, { "code": null, "e": 34700, "s": 34636, "text": "Create a Homepage for Restaurant using HTML , CSS and Bootstrap" }, { "code": null, "e": 34762, "s": 34700, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 34812, "s": 34762, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 34870, "s": 34812, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 34918, "s": 34870, "text": "How to update Node.js and NPM to next version ?" } ]
Difference between super() and this() in java - GeeksforGeeks
23 Nov, 2017 Similar article : super and this keywordsuper() as well as this() both are used to make constructor calls. super() is used to call Base class’s constructor(i.e, Parent’s class) while this() is used to call current class’s constructor. Let’s see both of them in detail: super() super() is use to call Base class’s(Parent class’s) constructor.// Java code to illustrate usage of super() class Parent { Parent() { System.out.println("Parent class's No " + " arg constructor"); }} class Child extends Parent { Child() { super(); System.out.println("Flow comes back from " + "Parent class no arg const"); } public static void main(String[] args) { new Child(); System.out.println("Inside Main"); }}Output:Parent class's No arg constructor Flow comes back from Parent class no arg const Inside Main Flow of Program :In main, we have made a statement new Child(), so it calls the no argument constructor of Child class.Inside that we have super() which calls the no argument of Parent class since we have written super() and no arguments that’s why it calls no argument constructor of Parent class, in that we have an SOP statement and hence it prints Parent class’s No arg constructor.Now as the No argument const of Parent class completes so flow comes back to the no argument of the Child class and in that we have an SOP statement and hence it prints Flow comes back from Parent class no arg const.Further after completing the no argument constructor of child class flow now came back again to main and executes remaining statements and prints Inside Main.We can use super() only inside constructor and nowhere else, not even in static context not even inside methods and super() should be first statement inside constructor.// Java program to illustrate usage of// super() as first statement class Parent { Parent() { System.out.println("Parent class's No " + "arg constructor"); }} class Child extends Parent { Child() { // Uncommenting below line causes compilation // error because super() should be first statement // System.out.println("Compile Time Error"); super(); System.out.println("Flow comes back from " + "Parent class no arg const"); } public static void main(String[] args) { new Child(); System.out.println("Inside main"); }}Output:Parent class's No arg constructor Flow comes back from Parent class no arg const Inside main Note : super() should be first statement inside any constructor. It can be used only inside constructor and nowhere else. super() is used to refer only parent class’s(super class’s) constructor. super() is use to call Base class’s(Parent class’s) constructor.// Java code to illustrate usage of super() class Parent { Parent() { System.out.println("Parent class's No " + " arg constructor"); }} class Child extends Parent { Child() { super(); System.out.println("Flow comes back from " + "Parent class no arg const"); } public static void main(String[] args) { new Child(); System.out.println("Inside Main"); }}Output:Parent class's No arg constructor Flow comes back from Parent class no arg const Inside Main Flow of Program :In main, we have made a statement new Child(), so it calls the no argument constructor of Child class.Inside that we have super() which calls the no argument of Parent class since we have written super() and no arguments that’s why it calls no argument constructor of Parent class, in that we have an SOP statement and hence it prints Parent class’s No arg constructor.Now as the No argument const of Parent class completes so flow comes back to the no argument of the Child class and in that we have an SOP statement and hence it prints Flow comes back from Parent class no arg const.Further after completing the no argument constructor of child class flow now came back again to main and executes remaining statements and prints Inside Main. // Java code to illustrate usage of super() class Parent { Parent() { System.out.println("Parent class's No " + " arg constructor"); }} class Child extends Parent { Child() { super(); System.out.println("Flow comes back from " + "Parent class no arg const"); } public static void main(String[] args) { new Child(); System.out.println("Inside Main"); }} Output: Parent class's No arg constructor Flow comes back from Parent class no arg const Inside Main Flow of Program : In main, we have made a statement new Child(), so it calls the no argument constructor of Child class. Inside that we have super() which calls the no argument of Parent class since we have written super() and no arguments that’s why it calls no argument constructor of Parent class, in that we have an SOP statement and hence it prints Parent class’s No arg constructor. Now as the No argument const of Parent class completes so flow comes back to the no argument of the Child class and in that we have an SOP statement and hence it prints Flow comes back from Parent class no arg const. Further after completing the no argument constructor of child class flow now came back again to main and executes remaining statements and prints Inside Main. We can use super() only inside constructor and nowhere else, not even in static context not even inside methods and super() should be first statement inside constructor.// Java program to illustrate usage of// super() as first statement class Parent { Parent() { System.out.println("Parent class's No " + "arg constructor"); }} class Child extends Parent { Child() { // Uncommenting below line causes compilation // error because super() should be first statement // System.out.println("Compile Time Error"); super(); System.out.println("Flow comes back from " + "Parent class no arg const"); } public static void main(String[] args) { new Child(); System.out.println("Inside main"); }}Output:Parent class's No arg constructor Flow comes back from Parent class no arg const Inside main Note : super() should be first statement inside any constructor. It can be used only inside constructor and nowhere else. super() is used to refer only parent class’s(super class’s) constructor. // Java program to illustrate usage of// super() as first statement class Parent { Parent() { System.out.println("Parent class's No " + "arg constructor"); }} class Child extends Parent { Child() { // Uncommenting below line causes compilation // error because super() should be first statement // System.out.println("Compile Time Error"); super(); System.out.println("Flow comes back from " + "Parent class no arg const"); } public static void main(String[] args) { new Child(); System.out.println("Inside main"); }} Output: Parent class's No arg constructor Flow comes back from Parent class no arg const Inside main Note : super() should be first statement inside any constructor. It can be used only inside constructor and nowhere else. super() is used to refer only parent class’s(super class’s) constructor. this() this() is used to call current class’s constructor.// Java code to illustrate usage of this() class RR { RR() { this(10); System.out.println("Flow comes back from " + "RR class's 1 arg const"); } RR(int a) { System.out.println("RR class's 1 arg const"); } public static void main(String[] args) { new RR(); System.out.println("Inside Main"); }}Output:RR class's 1 arg const Flow comes back from RR class's 1 arg const Inside Main Flow of Program :First start from main and then in that we have made a statement new Child() hence which calls the no argument constructor of Child class, inside that we have this(10) which calls the 1 argument of current class(i.e, RR class)Since we have written this(10) and 1 argument that’s why it calls 1 argument constructor of RR class. In that we have an SOP statement and hence it prints RR class’s 1 arg const.Now as the 1 argument const of RR class completes so flow comes back to the no argument of the RR class and in that we have an SOP statement and hence it prints Flow comes back from RR class’s 1 arg const.Further after completing the no argument constructor of RR class flow now came back again to main and executes remaining statements and prints Inside Main.We can use this() only inside constructor and nowhere else, not even in static context not even inside methods and this() should be first statement inside constructor.// Java program to illustrate usage of// this() as first statement class RR { RR() { // Uncommenting below line causes compilation // error because this() should be first statement // System.out.println("Compile Time Error"); this(51); System.out.println("Flow comes back from RR " + "class 1 arg const"); } RR(int k) { System.out.println("RR class's 1 arg const"); } public static void main(String[] args) { new RR(); System.out.println("Inside main"); }}Output:RR class's 1 arg constructor Flow comes back from RR class 1 arg const Inside main Note : this() should be first statement inside any constructor. It can be used only inside constructor and nowhere else. this() is use to refer only current class’s constructor. this() is used to call current class’s constructor.// Java code to illustrate usage of this() class RR { RR() { this(10); System.out.println("Flow comes back from " + "RR class's 1 arg const"); } RR(int a) { System.out.println("RR class's 1 arg const"); } public static void main(String[] args) { new RR(); System.out.println("Inside Main"); }}Output:RR class's 1 arg const Flow comes back from RR class's 1 arg const Inside Main Flow of Program :First start from main and then in that we have made a statement new Child() hence which calls the no argument constructor of Child class, inside that we have this(10) which calls the 1 argument of current class(i.e, RR class)Since we have written this(10) and 1 argument that’s why it calls 1 argument constructor of RR class. In that we have an SOP statement and hence it prints RR class’s 1 arg const.Now as the 1 argument const of RR class completes so flow comes back to the no argument of the RR class and in that we have an SOP statement and hence it prints Flow comes back from RR class’s 1 arg const.Further after completing the no argument constructor of RR class flow now came back again to main and executes remaining statements and prints Inside Main. // Java code to illustrate usage of this() class RR { RR() { this(10); System.out.println("Flow comes back from " + "RR class's 1 arg const"); } RR(int a) { System.out.println("RR class's 1 arg const"); } public static void main(String[] args) { new RR(); System.out.println("Inside Main"); }} Output: RR class's 1 arg const Flow comes back from RR class's 1 arg const Inside Main Flow of Program : First start from main and then in that we have made a statement new Child() hence which calls the no argument constructor of Child class, inside that we have this(10) which calls the 1 argument of current class(i.e, RR class) Since we have written this(10) and 1 argument that’s why it calls 1 argument constructor of RR class. In that we have an SOP statement and hence it prints RR class’s 1 arg const. Now as the 1 argument const of RR class completes so flow comes back to the no argument of the RR class and in that we have an SOP statement and hence it prints Flow comes back from RR class’s 1 arg const. Further after completing the no argument constructor of RR class flow now came back again to main and executes remaining statements and prints Inside Main. We can use this() only inside constructor and nowhere else, not even in static context not even inside methods and this() should be first statement inside constructor.// Java program to illustrate usage of// this() as first statement class RR { RR() { // Uncommenting below line causes compilation // error because this() should be first statement // System.out.println("Compile Time Error"); this(51); System.out.println("Flow comes back from RR " + "class 1 arg const"); } RR(int k) { System.out.println("RR class's 1 arg const"); } public static void main(String[] args) { new RR(); System.out.println("Inside main"); }}Output:RR class's 1 arg constructor Flow comes back from RR class 1 arg const Inside main Note : this() should be first statement inside any constructor. It can be used only inside constructor and nowhere else. this() is use to refer only current class’s constructor. // Java program to illustrate usage of// this() as first statement class RR { RR() { // Uncommenting below line causes compilation // error because this() should be first statement // System.out.println("Compile Time Error"); this(51); System.out.println("Flow comes back from RR " + "class 1 arg const"); } RR(int k) { System.out.println("RR class's 1 arg const"); } public static void main(String[] args) { new RR(); System.out.println("Inside main"); }} Output: RR class's 1 arg constructor Flow comes back from RR class 1 arg const Inside main Note : this() should be first statement inside any constructor. It can be used only inside constructor and nowhere else. this() is use to refer only current class’s constructor. Important points about this() and super() We can use super() as well this() only once inside constructor. If we use super() twice or this() twice or super() followed by this() or this() followed by super(), then immediately we get compile time error i.e, we can use either super() or this() as first statement inside constructor and not both.It is upto you that whether you use super() or this() or not because if we are not using this() or super() then by default compiler will put super() as first statement inside constructor.// Java program to illustrate super() by default// executed by compiler if not provided explicitly class Parent { Parent() { System.out.println("Parent class's No " + "argument constructor"); } Parent(int a) { System.out.println("Parent class's 1 argument" + " constructor"); } } class Base extends Parent { Base() { // By default compiler put super() // here and not super(int) System.out.println("Base class's No " + "argument constructor"); } public static void main(String[] args) { new Base(); System.out.println("Inside Main"); }}Output: Parent class's No argument constructor Base class's No argument constructor Inside Main Flow of program:Inside main we have new Base() then flow goes to No argument constructor of Base class.After that if we don’t put either super() or this() then by default compiler put super().So flow goes to Parent class’s No arg constructor and not 1 argument constructor.After that it prints Parent class’s No argument constructor.After that when Parent() constructor completes then flow again comes back to that No argument constructor of Base class and executes next SOP statement i.e, Base class’s No argument constructor.After completing that No argument constructor flow comes back to main() again and prints the remaining statements inside main() i.e, Inside mainHowever, if explicitly specified, you may use this() before super.// Java program to illustrate super() put by // compiler always if not provided explicitly class Parent { Parent() { System.out.println("Parent class's No " + "argument constructor"); } Parent(int a) { System.out.println("Parent class's one " + " argument constructor"); }} class Base extends Parent { Base() { this(10); System.out.println("No arg const"); } Base(int a) { this(10, 20); System.out.println("1 arg const"); } Base(int k, int m) { // See here by default compiler put super(); System.out.println("2 arg const"); } public static void main(String[] args) { new Base(); System.out.println("Inside Main"); }}Output:Parent class's No argument constructor 2 arg const 1 arg const No arg const Inside Main Recursive constructor call not allowed// Java program to illustrate recursive // constructor call not allowed class RR { RR() { this(30); } RR(int a) { this(); } public static void main(String[] args) { new RR(); }}Output:Compile time error saying recursive constructor invocation Flow of program : Here, above start from main() and then flow goes to No arg constructor of RR class. After that we have this(30) and flow goes to 1 arg constructor of RR and in that we have this() so again flow goes to No arg constructor of base class and in that again we have this(30) and flow again goes to 1 arg constructor of Base class and it goes on ...... like a recursion. So it is invalid that’s why we get compile time error saying recursive constructor invocation. So recursive constructor invocations are not allowed in java. We can use super() as well this() only once inside constructor. If we use super() twice or this() twice or super() followed by this() or this() followed by super(), then immediately we get compile time error i.e, we can use either super() or this() as first statement inside constructor and not both. It is upto you that whether you use super() or this() or not because if we are not using this() or super() then by default compiler will put super() as first statement inside constructor.// Java program to illustrate super() by default// executed by compiler if not provided explicitly class Parent { Parent() { System.out.println("Parent class's No " + "argument constructor"); } Parent(int a) { System.out.println("Parent class's 1 argument" + " constructor"); } } class Base extends Parent { Base() { // By default compiler put super() // here and not super(int) System.out.println("Base class's No " + "argument constructor"); } public static void main(String[] args) { new Base(); System.out.println("Inside Main"); }}Output: Parent class's No argument constructor Base class's No argument constructor Inside Main Flow of program:Inside main we have new Base() then flow goes to No argument constructor of Base class.After that if we don’t put either super() or this() then by default compiler put super().So flow goes to Parent class’s No arg constructor and not 1 argument constructor.After that it prints Parent class’s No argument constructor.After that when Parent() constructor completes then flow again comes back to that No argument constructor of Base class and executes next SOP statement i.e, Base class’s No argument constructor.After completing that No argument constructor flow comes back to main() again and prints the remaining statements inside main() i.e, Inside mainHowever, if explicitly specified, you may use this() before super.// Java program to illustrate super() put by // compiler always if not provided explicitly class Parent { Parent() { System.out.println("Parent class's No " + "argument constructor"); } Parent(int a) { System.out.println("Parent class's one " + " argument constructor"); }} class Base extends Parent { Base() { this(10); System.out.println("No arg const"); } Base(int a) { this(10, 20); System.out.println("1 arg const"); } Base(int k, int m) { // See here by default compiler put super(); System.out.println("2 arg const"); } public static void main(String[] args) { new Base(); System.out.println("Inside Main"); }}Output:Parent class's No argument constructor 2 arg const 1 arg const No arg const Inside Main // Java program to illustrate super() by default// executed by compiler if not provided explicitly class Parent { Parent() { System.out.println("Parent class's No " + "argument constructor"); } Parent(int a) { System.out.println("Parent class's 1 argument" + " constructor"); } } class Base extends Parent { Base() { // By default compiler put super() // here and not super(int) System.out.println("Base class's No " + "argument constructor"); } public static void main(String[] args) { new Base(); System.out.println("Inside Main"); }} Output: Parent class's No argument constructor Base class's No argument constructor Inside Main Flow of program: Inside main we have new Base() then flow goes to No argument constructor of Base class. After that if we don’t put either super() or this() then by default compiler put super(). So flow goes to Parent class’s No arg constructor and not 1 argument constructor. After that it prints Parent class’s No argument constructor. After that when Parent() constructor completes then flow again comes back to that No argument constructor of Base class and executes next SOP statement i.e, Base class’s No argument constructor. After completing that No argument constructor flow comes back to main() again and prints the remaining statements inside main() i.e, Inside main However, if explicitly specified, you may use this() before super. // Java program to illustrate super() put by // compiler always if not provided explicitly class Parent { Parent() { System.out.println("Parent class's No " + "argument constructor"); } Parent(int a) { System.out.println("Parent class's one " + " argument constructor"); }} class Base extends Parent { Base() { this(10); System.out.println("No arg const"); } Base(int a) { this(10, 20); System.out.println("1 arg const"); } Base(int k, int m) { // See here by default compiler put super(); System.out.println("2 arg const"); } public static void main(String[] args) { new Base(); System.out.println("Inside Main"); }} Output: Parent class's No argument constructor 2 arg const 1 arg const No arg const Inside Main Recursive constructor call not allowed// Java program to illustrate recursive // constructor call not allowed class RR { RR() { this(30); } RR(int a) { this(); } public static void main(String[] args) { new RR(); }}Output:Compile time error saying recursive constructor invocation Flow of program : Here, above start from main() and then flow goes to No arg constructor of RR class. After that we have this(30) and flow goes to 1 arg constructor of RR and in that we have this() so again flow goes to No arg constructor of base class and in that again we have this(30) and flow again goes to 1 arg constructor of Base class and it goes on ...... like a recursion. So it is invalid that’s why we get compile time error saying recursive constructor invocation. So recursive constructor invocations are not allowed in java. // Java program to illustrate recursive // constructor call not allowed class RR { RR() { this(30); } RR(int a) { this(); } public static void main(String[] args) { new RR(); }} Output: Compile time error saying recursive constructor invocation Flow of program : Here, above start from main() and then flow goes to No arg constructor of RR class. After that we have this(30) and flow goes to 1 arg constructor of RR and in that we have this() so again flow goes to No arg constructor of base class and in that again we have this(30) and flow again goes to 1 arg constructor of Base class and it goes on ...... like a recursion. So it is invalid that’s why we get compile time error saying recursive constructor invocation. So recursive constructor invocations are not allowed in java. This article is contributed by Rajat Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Difference Between Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack vs Heap Memory Allocation Difference between Process and Thread Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 24370, "s": 24342, "text": "\n23 Nov, 2017" }, { "code": null, "e": 24605, "s": 24370, "text": "Similar article : super and this keywordsuper() as well as this() both are used to make constructor calls. super() is used to call Base class’s constructor(i.e, Parent’s class) while this() is used to call current class’s constructor." }, { "code": null, "e": 24639, "s": 24605, "text": "Let’s see both of them in detail:" }, { "code": null, "e": 24647, "s": 24639, "text": "super()" }, { "code": null, "e": 27162, "s": 24647, "text": "super() is use to call Base class’s(Parent class’s) constructor.// Java code to illustrate usage of super() class Parent { Parent() { System.out.println(\"Parent class's No \" + \" arg constructor\"); }} class Child extends Parent { Child() { super(); System.out.println(\"Flow comes back from \" + \"Parent class no arg const\"); } public static void main(String[] args) { new Child(); System.out.println(\"Inside Main\"); }}Output:Parent class's No arg constructor\nFlow comes back from Parent class no arg const\nInside Main\nFlow of Program :In main, we have made a statement new Child(), so it calls the no argument constructor of Child class.Inside that we have super() which calls the no argument of Parent class since we have written super() and no arguments that’s why it calls no argument constructor of Parent class, in that we have an SOP statement and hence it prints Parent class’s No arg constructor.Now as the No argument const of Parent class completes so flow comes back to the no argument of the Child class and in that we have an SOP statement and hence it prints Flow comes back from Parent class no arg const.Further after completing the no argument constructor of child class flow now came back again to main and executes remaining statements and prints Inside Main.We can use super() only inside constructor and nowhere else, not even in static context not even inside methods and super() should be first statement inside constructor.// Java program to illustrate usage of// super() as first statement class Parent { Parent() { System.out.println(\"Parent class's No \" + \"arg constructor\"); }} class Child extends Parent { Child() { // Uncommenting below line causes compilation // error because super() should be first statement // System.out.println(\"Compile Time Error\"); super(); System.out.println(\"Flow comes back from \" + \"Parent class no arg const\"); } public static void main(String[] args) { new Child(); System.out.println(\"Inside main\"); }}Output:Parent class's No arg constructor\nFlow comes back from Parent class no arg const\nInside main\nNote : super() should be first statement inside any constructor. It can be used only inside constructor and nowhere else. super() is used to refer only parent class’s(super class’s) constructor." }, { "code": null, "e": 28557, "s": 27162, "text": "super() is use to call Base class’s(Parent class’s) constructor.// Java code to illustrate usage of super() class Parent { Parent() { System.out.println(\"Parent class's No \" + \" arg constructor\"); }} class Child extends Parent { Child() { super(); System.out.println(\"Flow comes back from \" + \"Parent class no arg const\"); } public static void main(String[] args) { new Child(); System.out.println(\"Inside Main\"); }}Output:Parent class's No arg constructor\nFlow comes back from Parent class no arg const\nInside Main\nFlow of Program :In main, we have made a statement new Child(), so it calls the no argument constructor of Child class.Inside that we have super() which calls the no argument of Parent class since we have written super() and no arguments that’s why it calls no argument constructor of Parent class, in that we have an SOP statement and hence it prints Parent class’s No arg constructor.Now as the No argument const of Parent class completes so flow comes back to the no argument of the Child class and in that we have an SOP statement and hence it prints Flow comes back from Parent class no arg const.Further after completing the no argument constructor of child class flow now came back again to main and executes remaining statements and prints Inside Main." }, { "code": "// Java code to illustrate usage of super() class Parent { Parent() { System.out.println(\"Parent class's No \" + \" arg constructor\"); }} class Child extends Parent { Child() { super(); System.out.println(\"Flow comes back from \" + \"Parent class no arg const\"); } public static void main(String[] args) { new Child(); System.out.println(\"Inside Main\"); }}", "e": 29028, "s": 28557, "text": null }, { "code": null, "e": 29036, "s": 29028, "text": "Output:" }, { "code": null, "e": 29130, "s": 29036, "text": "Parent class's No arg constructor\nFlow comes back from Parent class no arg const\nInside Main\n" }, { "code": null, "e": 29148, "s": 29130, "text": "Flow of Program :" }, { "code": null, "e": 29251, "s": 29148, "text": "In main, we have made a statement new Child(), so it calls the no argument constructor of Child class." }, { "code": null, "e": 29519, "s": 29251, "text": "Inside that we have super() which calls the no argument of Parent class since we have written super() and no arguments that’s why it calls no argument constructor of Parent class, in that we have an SOP statement and hence it prints Parent class’s No arg constructor." }, { "code": null, "e": 29736, "s": 29519, "text": "Now as the No argument const of Parent class completes so flow comes back to the no argument of the Child class and in that we have an SOP statement and hence it prints Flow comes back from Parent class no arg const." }, { "code": null, "e": 29895, "s": 29736, "text": "Further after completing the no argument constructor of child class flow now came back again to main and executes remaining statements and prints Inside Main." }, { "code": null, "e": 31016, "s": 29895, "text": "We can use super() only inside constructor and nowhere else, not even in static context not even inside methods and super() should be first statement inside constructor.// Java program to illustrate usage of// super() as first statement class Parent { Parent() { System.out.println(\"Parent class's No \" + \"arg constructor\"); }} class Child extends Parent { Child() { // Uncommenting below line causes compilation // error because super() should be first statement // System.out.println(\"Compile Time Error\"); super(); System.out.println(\"Flow comes back from \" + \"Parent class no arg const\"); } public static void main(String[] args) { new Child(); System.out.println(\"Inside main\"); }}Output:Parent class's No arg constructor\nFlow comes back from Parent class no arg const\nInside main\nNote : super() should be first statement inside any constructor. It can be used only inside constructor and nowhere else. super() is used to refer only parent class’s(super class’s) constructor." }, { "code": "// Java program to illustrate usage of// super() as first statement class Parent { Parent() { System.out.println(\"Parent class's No \" + \"arg constructor\"); }} class Child extends Parent { Child() { // Uncommenting below line causes compilation // error because super() should be first statement // System.out.println(\"Compile Time Error\"); super(); System.out.println(\"Flow comes back from \" + \"Parent class no arg const\"); } public static void main(String[] args) { new Child(); System.out.println(\"Inside main\"); }}", "e": 31674, "s": 31016, "text": null }, { "code": null, "e": 31682, "s": 31674, "text": "Output:" }, { "code": null, "e": 31776, "s": 31682, "text": "Parent class's No arg constructor\nFlow comes back from Parent class no arg const\nInside main\n" }, { "code": null, "e": 31971, "s": 31776, "text": "Note : super() should be first statement inside any constructor. It can be used only inside constructor and nowhere else. super() is used to refer only parent class’s(super class’s) constructor." }, { "code": null, "e": 31978, "s": 31971, "text": "this()" }, { "code": null, "e": 34288, "s": 31978, "text": "this() is used to call current class’s constructor.// Java code to illustrate usage of this() class RR { RR() { this(10); System.out.println(\"Flow comes back from \" + \"RR class's 1 arg const\"); } RR(int a) { System.out.println(\"RR class's 1 arg const\"); } public static void main(String[] args) { new RR(); System.out.println(\"Inside Main\"); }}Output:RR class's 1 arg const\nFlow comes back from RR class's 1 arg const\nInside Main\nFlow of Program :First start from main and then in that we have made a statement new Child() hence which calls the no argument constructor of Child class, inside that we have this(10) which calls the 1 argument of current class(i.e, RR class)Since we have written this(10) and 1 argument that’s why it calls 1 argument constructor of RR class. In that we have an SOP statement and hence it prints RR class’s 1 arg const.Now as the 1 argument const of RR class completes so flow comes back to the no argument of the RR class and in that we have an SOP statement and hence it prints Flow comes back from RR class’s 1 arg const.Further after completing the no argument constructor of RR class flow now came back again to main and executes remaining statements and prints Inside Main.We can use this() only inside constructor and nowhere else, not even in static context not even inside methods and this() should be first statement inside constructor.// Java program to illustrate usage of// this() as first statement class RR { RR() { // Uncommenting below line causes compilation // error because this() should be first statement // System.out.println(\"Compile Time Error\"); this(51); System.out.println(\"Flow comes back from RR \" + \"class 1 arg const\"); } RR(int k) { System.out.println(\"RR class's 1 arg const\"); } public static void main(String[] args) { new RR(); System.out.println(\"Inside main\"); }}Output:RR class's 1 arg constructor\nFlow comes back from RR class 1 arg const\nInside main\nNote : this() should be first statement inside any constructor. It can be used only inside constructor and nowhere else. this() is use to refer only current class’s constructor." }, { "code": null, "e": 35591, "s": 34288, "text": "this() is used to call current class’s constructor.// Java code to illustrate usage of this() class RR { RR() { this(10); System.out.println(\"Flow comes back from \" + \"RR class's 1 arg const\"); } RR(int a) { System.out.println(\"RR class's 1 arg const\"); } public static void main(String[] args) { new RR(); System.out.println(\"Inside Main\"); }}Output:RR class's 1 arg const\nFlow comes back from RR class's 1 arg const\nInside Main\nFlow of Program :First start from main and then in that we have made a statement new Child() hence which calls the no argument constructor of Child class, inside that we have this(10) which calls the 1 argument of current class(i.e, RR class)Since we have written this(10) and 1 argument that’s why it calls 1 argument constructor of RR class. In that we have an SOP statement and hence it prints RR class’s 1 arg const.Now as the 1 argument const of RR class completes so flow comes back to the no argument of the RR class and in that we have an SOP statement and hence it prints Flow comes back from RR class’s 1 arg const.Further after completing the no argument constructor of RR class flow now came back again to main and executes remaining statements and prints Inside Main." }, { "code": "// Java code to illustrate usage of this() class RR { RR() { this(10); System.out.println(\"Flow comes back from \" + \"RR class's 1 arg const\"); } RR(int a) { System.out.println(\"RR class's 1 arg const\"); } public static void main(String[] args) { new RR(); System.out.println(\"Inside Main\"); }}", "e": 35977, "s": 35591, "text": null }, { "code": null, "e": 35985, "s": 35977, "text": "Output:" }, { "code": null, "e": 36065, "s": 35985, "text": "RR class's 1 arg const\nFlow comes back from RR class's 1 arg const\nInside Main\n" }, { "code": null, "e": 36083, "s": 36065, "text": "Flow of Program :" }, { "code": null, "e": 36309, "s": 36083, "text": "First start from main and then in that we have made a statement new Child() hence which calls the no argument constructor of Child class, inside that we have this(10) which calls the 1 argument of current class(i.e, RR class)" }, { "code": null, "e": 36488, "s": 36309, "text": "Since we have written this(10) and 1 argument that’s why it calls 1 argument constructor of RR class. In that we have an SOP statement and hence it prints RR class’s 1 arg const." }, { "code": null, "e": 36694, "s": 36488, "text": "Now as the 1 argument const of RR class completes so flow comes back to the no argument of the RR class and in that we have an SOP statement and hence it prints Flow comes back from RR class’s 1 arg const." }, { "code": null, "e": 36850, "s": 36694, "text": "Further after completing the no argument constructor of RR class flow now came back again to main and executes remaining statements and prints Inside Main." }, { "code": null, "e": 37858, "s": 36850, "text": "We can use this() only inside constructor and nowhere else, not even in static context not even inside methods and this() should be first statement inside constructor.// Java program to illustrate usage of// this() as first statement class RR { RR() { // Uncommenting below line causes compilation // error because this() should be first statement // System.out.println(\"Compile Time Error\"); this(51); System.out.println(\"Flow comes back from RR \" + \"class 1 arg const\"); } RR(int k) { System.out.println(\"RR class's 1 arg const\"); } public static void main(String[] args) { new RR(); System.out.println(\"Inside main\"); }}Output:RR class's 1 arg constructor\nFlow comes back from RR class 1 arg const\nInside main\nNote : this() should be first statement inside any constructor. It can be used only inside constructor and nowhere else. this() is use to refer only current class’s constructor." }, { "code": "// Java program to illustrate usage of// this() as first statement class RR { RR() { // Uncommenting below line causes compilation // error because this() should be first statement // System.out.println(\"Compile Time Error\"); this(51); System.out.println(\"Flow comes back from RR \" + \"class 1 arg const\"); } RR(int k) { System.out.println(\"RR class's 1 arg const\"); } public static void main(String[] args) { new RR(); System.out.println(\"Inside main\"); }}", "e": 38432, "s": 37858, "text": null }, { "code": null, "e": 38440, "s": 38432, "text": "Output:" }, { "code": null, "e": 38524, "s": 38440, "text": "RR class's 1 arg constructor\nFlow comes back from RR class 1 arg const\nInside main\n" }, { "code": null, "e": 38702, "s": 38524, "text": "Note : this() should be first statement inside any constructor. It can be used only inside constructor and nowhere else. this() is use to refer only current class’s constructor." }, { "code": null, "e": 38744, "s": 38702, "text": "Important points about this() and super()" }, { "code": null, "e": 42538, "s": 38744, "text": "We can use super() as well this() only once inside constructor. If we use super() twice or this() twice or super() followed by this() or this() followed by super(), then immediately we get compile time error i.e, we can use either super() or this() as first statement inside constructor and not both.It is upto you that whether you use super() or this() or not because if we are not using this() or super() then by default compiler will put super() as first statement inside constructor.// Java program to illustrate super() by default// executed by compiler if not provided explicitly class Parent { Parent() { System.out.println(\"Parent class's No \" + \"argument constructor\"); } Parent(int a) { System.out.println(\"Parent class's 1 argument\" + \" constructor\"); } } class Base extends Parent { Base() { // By default compiler put super() // here and not super(int) System.out.println(\"Base class's No \" + \"argument constructor\"); } public static void main(String[] args) { new Base(); System.out.println(\"Inside Main\"); }}Output:\nParent class's No argument constructor\nBase class's No argument constructor\nInside Main\nFlow of program:Inside main we have new Base() then flow goes to No argument constructor of Base class.After that if we don’t put either super() or this() then by default compiler put super().So flow goes to Parent class’s No arg constructor and not 1 argument constructor.After that it prints Parent class’s No argument constructor.After that when Parent() constructor completes then flow again comes back to that No argument constructor of Base class and executes next SOP statement i.e, Base class’s No argument constructor.After completing that No argument constructor flow comes back to main() again and prints the remaining statements inside main() i.e, Inside mainHowever, if explicitly specified, you may use this() before super.// Java program to illustrate super() put by // compiler always if not provided explicitly class Parent { Parent() { System.out.println(\"Parent class's No \" + \"argument constructor\"); } Parent(int a) { System.out.println(\"Parent class's one \" + \" argument constructor\"); }} class Base extends Parent { Base() { this(10); System.out.println(\"No arg const\"); } Base(int a) { this(10, 20); System.out.println(\"1 arg const\"); } Base(int k, int m) { // See here by default compiler put super(); System.out.println(\"2 arg const\"); } public static void main(String[] args) { new Base(); System.out.println(\"Inside Main\"); }}Output:Parent class's No argument constructor\n2 arg const\n1 arg const\nNo arg const\nInside Main\nRecursive constructor call not allowed// Java program to illustrate recursive // constructor call not allowed class RR { RR() { this(30); } RR(int a) { this(); } public static void main(String[] args) { new RR(); }}Output:Compile time error saying recursive constructor invocation\nFlow of program : Here, above start from main() and then flow goes to No arg constructor of RR class. After that we have this(30) and flow goes to 1 arg constructor of RR and in that we have this() so again flow goes to No arg constructor of base class and in that again we have this(30) and flow again goes to 1 arg constructor of Base class and it goes on ...... like a recursion. So it is invalid that’s why we get compile time error saying recursive constructor invocation. So recursive constructor invocations are not allowed in java." }, { "code": null, "e": 42839, "s": 42538, "text": "We can use super() as well this() only once inside constructor. If we use super() twice or this() twice or super() followed by this() or this() followed by super(), then immediately we get compile time error i.e, we can use either super() or this() as first statement inside constructor and not both." }, { "code": null, "e": 45464, "s": 42839, "text": "It is upto you that whether you use super() or this() or not because if we are not using this() or super() then by default compiler will put super() as first statement inside constructor.// Java program to illustrate super() by default// executed by compiler if not provided explicitly class Parent { Parent() { System.out.println(\"Parent class's No \" + \"argument constructor\"); } Parent(int a) { System.out.println(\"Parent class's 1 argument\" + \" constructor\"); } } class Base extends Parent { Base() { // By default compiler put super() // here and not super(int) System.out.println(\"Base class's No \" + \"argument constructor\"); } public static void main(String[] args) { new Base(); System.out.println(\"Inside Main\"); }}Output:\nParent class's No argument constructor\nBase class's No argument constructor\nInside Main\nFlow of program:Inside main we have new Base() then flow goes to No argument constructor of Base class.After that if we don’t put either super() or this() then by default compiler put super().So flow goes to Parent class’s No arg constructor and not 1 argument constructor.After that it prints Parent class’s No argument constructor.After that when Parent() constructor completes then flow again comes back to that No argument constructor of Base class and executes next SOP statement i.e, Base class’s No argument constructor.After completing that No argument constructor flow comes back to main() again and prints the remaining statements inside main() i.e, Inside mainHowever, if explicitly specified, you may use this() before super.// Java program to illustrate super() put by // compiler always if not provided explicitly class Parent { Parent() { System.out.println(\"Parent class's No \" + \"argument constructor\"); } Parent(int a) { System.out.println(\"Parent class's one \" + \" argument constructor\"); }} class Base extends Parent { Base() { this(10); System.out.println(\"No arg const\"); } Base(int a) { this(10, 20); System.out.println(\"1 arg const\"); } Base(int k, int m) { // See here by default compiler put super(); System.out.println(\"2 arg const\"); } public static void main(String[] args) { new Base(); System.out.println(\"Inside Main\"); }}Output:Parent class's No argument constructor\n2 arg const\n1 arg const\nNo arg const\nInside Main\n" }, { "code": "// Java program to illustrate super() by default// executed by compiler if not provided explicitly class Parent { Parent() { System.out.println(\"Parent class's No \" + \"argument constructor\"); } Parent(int a) { System.out.println(\"Parent class's 1 argument\" + \" constructor\"); } } class Base extends Parent { Base() { // By default compiler put super() // here and not super(int) System.out.println(\"Base class's No \" + \"argument constructor\"); } public static void main(String[] args) { new Base(); System.out.println(\"Inside Main\"); }}", "e": 46177, "s": 45464, "text": null }, { "code": null, "e": 46274, "s": 46177, "text": "Output:\nParent class's No argument constructor\nBase class's No argument constructor\nInside Main\n" }, { "code": null, "e": 46291, "s": 46274, "text": "Flow of program:" }, { "code": null, "e": 46379, "s": 46291, "text": "Inside main we have new Base() then flow goes to No argument constructor of Base class." }, { "code": null, "e": 46469, "s": 46379, "text": "After that if we don’t put either super() or this() then by default compiler put super()." }, { "code": null, "e": 46551, "s": 46469, "text": "So flow goes to Parent class’s No arg constructor and not 1 argument constructor." }, { "code": null, "e": 46612, "s": 46551, "text": "After that it prints Parent class’s No argument constructor." }, { "code": null, "e": 46807, "s": 46612, "text": "After that when Parent() constructor completes then flow again comes back to that No argument constructor of Base class and executes next SOP statement i.e, Base class’s No argument constructor." }, { "code": null, "e": 46952, "s": 46807, "text": "After completing that No argument constructor flow comes back to main() again and prints the remaining statements inside main() i.e, Inside main" }, { "code": null, "e": 47019, "s": 46952, "text": "However, if explicitly specified, you may use this() before super." }, { "code": "// Java program to illustrate super() put by // compiler always if not provided explicitly class Parent { Parent() { System.out.println(\"Parent class's No \" + \"argument constructor\"); } Parent(int a) { System.out.println(\"Parent class's one \" + \" argument constructor\"); }} class Base extends Parent { Base() { this(10); System.out.println(\"No arg const\"); } Base(int a) { this(10, 20); System.out.println(\"1 arg const\"); } Base(int k, int m) { // See here by default compiler put super(); System.out.println(\"2 arg const\"); } public static void main(String[] args) { new Base(); System.out.println(\"Inside Main\"); }}", "e": 47817, "s": 47019, "text": null }, { "code": null, "e": 47825, "s": 47817, "text": "Output:" }, { "code": null, "e": 47914, "s": 47825, "text": "Parent class's No argument constructor\n2 arg const\n1 arg const\nNo arg const\nInside Main\n" }, { "code": null, "e": 48784, "s": 47914, "text": "Recursive constructor call not allowed// Java program to illustrate recursive // constructor call not allowed class RR { RR() { this(30); } RR(int a) { this(); } public static void main(String[] args) { new RR(); }}Output:Compile time error saying recursive constructor invocation\nFlow of program : Here, above start from main() and then flow goes to No arg constructor of RR class. After that we have this(30) and flow goes to 1 arg constructor of RR and in that we have this() so again flow goes to No arg constructor of base class and in that again we have this(30) and flow again goes to 1 arg constructor of Base class and it goes on ...... like a recursion. So it is invalid that’s why we get compile time error saying recursive constructor invocation. So recursive constructor invocations are not allowed in java." }, { "code": "// Java program to illustrate recursive // constructor call not allowed class RR { RR() { this(30); } RR(int a) { this(); } public static void main(String[] args) { new RR(); }}", "e": 49011, "s": 48784, "text": null }, { "code": null, "e": 49019, "s": 49011, "text": "Output:" }, { "code": null, "e": 49079, "s": 49019, "text": "Compile time error saying recursive constructor invocation\n" }, { "code": null, "e": 49619, "s": 49079, "text": "Flow of program : Here, above start from main() and then flow goes to No arg constructor of RR class. After that we have this(30) and flow goes to 1 arg constructor of RR and in that we have this() so again flow goes to No arg constructor of base class and in that again we have this(30) and flow again goes to 1 arg constructor of Base class and it goes on ...... like a recursion. So it is invalid that’s why we get compile time error saying recursive constructor invocation. So recursive constructor invocations are not allowed in java." }, { "code": null, "e": 49918, "s": 49619, "text": "This article is contributed by Rajat Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 50043, "s": 49918, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 50062, "s": 50043, "text": "Difference Between" }, { "code": null, "e": 50067, "s": 50062, "text": "Java" }, { "code": null, "e": 50072, "s": 50067, "text": "Java" }, { "code": null, "e": 50170, "s": 50072, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 50179, "s": 50170, "text": "Comments" }, { "code": null, "e": 50192, "s": 50179, "text": "Old Comments" }, { "code": null, "e": 50224, "s": 50192, "text": "Stack vs Heap Memory Allocation" }, { "code": null, "e": 50262, "s": 50224, "text": "Difference between Process and Thread" }, { "code": null, "e": 50323, "s": 50262, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 50391, "s": 50323, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 50428, "s": 50391, "text": "Differences between JDK, JRE and JVM" }, { "code": null, "e": 50443, "s": 50428, "text": "Arrays in Java" }, { "code": null, "e": 50487, "s": 50443, "text": "Split() String method in Java with examples" }, { "code": null, "e": 50509, "s": 50487, "text": "For-each loop in Java" }, { "code": null, "e": 50545, "s": 50509, "text": "Arrays.sort() in Java with examples" } ]
Difference Between System.out.print() and System.out.println() Function in Java - GeeksforGeeks
07 Oct, 2021 In Java, we have the following functions to print anything in the console. System.out.print() and System.out.println() But there is a slight difference between both of them, i.e. System.out.println() prints the content and switch to the next line after execution of the statement whereas System.out.print() only prints the content without switching to the next line after executing this statement. The following examples will help you in understanding the difference between them more prominently. Example 1: Java import java.io.*; class GFG { public static void main(String[] args) { System.out.println("Welcome to JAVA (1st line)"); // this print statement will be printed in a new line. System.out.print("Welcome to GeeksforGeeks (2nd line) "); // this print statement will be printed in the same line. System.out.print("Hello Geeks (2nd line)"); } } Welcome to JAVA (1st line) Welcome to GeeksforGeeks (2nd line) Hello Geeks (2nd line) Example 2: Java import java.io.*; class GFG { public static void main(String[] args) { System.out.print("Welcome to JAVA (1st line) "); // this print statement will be printed in the same line. System.out.println("Welcome to GeeksforGeeks (1st line)"); // this print statement will be printed in a new line. System.out.print("Hello Geeks (2nd line)"); } } Welcome to JAVA (1st line) Welcome to GeeksforGeeks (1st line) Hello Geeks (2nd line) Difference Between Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Differences and Applications of List, Tuple, Set and Dictionary in Python Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 24932, "s": 24901, "text": " \n07 Oct, 2021\n" }, { "code": null, "e": 25007, "s": 24932, "text": "In Java, we have the following functions to print anything in the console." }, { "code": null, "e": 25030, "s": 25007, "text": "System.out.print() and" }, { "code": null, "e": 25051, "s": 25030, "text": "System.out.println()" }, { "code": null, "e": 25112, "s": 25051, "text": "But there is a slight difference between both of them, i.e. " }, { "code": null, "e": 25222, "s": 25112, "text": "System.out.println() prints the content and switch to the next line after execution of the statement whereas " }, { "code": null, "e": 25332, "s": 25222, "text": "System.out.print() only prints the content without switching to the next line after executing this statement." }, { "code": null, "e": 25432, "s": 25332, "text": "The following examples will help you in understanding the difference between them more prominently." }, { "code": null, "e": 25443, "s": 25432, "text": "Example 1:" }, { "code": null, "e": 25448, "s": 25443, "text": "Java" }, { "code": "\n\n\n\n\n\n\nimport java.io.*; \n \nclass GFG { \n public static void main(String[] args) \n { \n System.out.println(\"Welcome to JAVA (1st line)\"); \n \n // this print statement will be printed in a new line. \n System.out.print(\"Welcome to GeeksforGeeks (2nd line) \"); \n \n // this print statement will be printed in the same line. \n System.out.print(\"Hello Geeks (2nd line)\"); \n } \n}\n\n\n\n\n\n", "e": 25900, "s": 25458, "text": null }, { "code": null, "e": 25986, "s": 25900, "text": "Welcome to JAVA (1st line)\nWelcome to GeeksforGeeks (2nd line) Hello Geeks (2nd line)" }, { "code": null, "e": 25997, "s": 25986, "text": "Example 2:" }, { "code": null, "e": 26002, "s": 25997, "text": "Java" }, { "code": "\n\n\n\n\n\n\nimport java.io.*; \n \nclass GFG { \n public static void main(String[] args) \n { \n System.out.print(\"Welcome to JAVA (1st line) \"); \n \n // this print statement will be printed in the same line. \n System.out.println(\"Welcome to GeeksforGeeks (1st line)\"); \n \n // this print statement will be printed in a new line. \n System.out.print(\"Hello Geeks (2nd line)\"); \n } \n}\n\n\n\n\n\n", "e": 26454, "s": 26012, "text": null }, { "code": null, "e": 26540, "s": 26454, "text": "Welcome to JAVA (1st line) Welcome to GeeksforGeeks (1st line)\nHello Geeks (2nd line)" }, { "code": null, "e": 26561, "s": 26540, "text": "\nDifference Between\n" }, { "code": null, "e": 26568, "s": 26561, "text": "\nJava\n" }, { "code": null, "e": 26773, "s": 26568, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 26834, "s": 26773, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26902, "s": 26834, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 26960, "s": 26902, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 27015, "s": 26960, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 27089, "s": 27015, "text": "Differences and Applications of List, Tuple, Set and Dictionary in Python" }, { "code": null, "e": 27104, "s": 27089, "text": "Arrays in Java" }, { "code": null, "e": 27148, "s": 27104, "text": "Split() String method in Java with examples" }, { "code": null, "e": 27170, "s": 27148, "text": "For-each loop in Java" }, { "code": null, "e": 27206, "s": 27170, "text": "Arrays.sort() in Java with examples" } ]
Ubuntu - Command Line
Ubuntu is a Linux based operating system and most Linux users are more familiar with the command line interface. In this chapter, we will go through some of the popular command line’s used in Ubuntu. To invoke the command line, go to the search option and enter the command keyword in the search box. The search result will give the Terminal option. Double-lick to get the command line as shown in the following screenshot. The easiest command to start with, is the directory listing command which is used to list the directory contents. ls –option directoryname Option − These are the options to be specified with the ls command. Option − These are the options to be specified with the ls command. Directoryname − This is the optional directory name that can be specified along with the ls command. Directoryname − This is the optional directory name that can be specified along with the ls command. The output will be the listing of the directory contents. In the following example, we just issue the ls command to list the directory contents. The directory listing of the current directory will be shown as the output. Another variant of the ls command is to list the directory, but with more details on each line item. This is shown in the following screenshot with the ls –l command. To clear the screen, we can use the clear command. clear None The command line screen will be cleared. To get more information on a command, we can use the ‘man’ command. man commandname Commandname − This is the name of the command for which more information is required. The information on the command will be displayed. Following is an example of the ‘man’ command. If we issue the ‘man ls’ command, we will get the following output. The output will contain information on the ls command. We can use the find command to find for files. find filepattern Filepattern − This is the pattern used to find for files. The files based on the file pattern will be displayed. In this example, we will issue the following command. find Sample.* This command will list all the files which start with the word ‘Sample’. This command is used to display who is the current logged on user. whoami None The name of the current logged on user will be displayed. In this example, we will issue the following command. whoami This command will display the current working directory. pwd None The current working directory will be displayed. In this example, we will issue the following command. Pwd 8 Lectures 31 mins Musab Zayadneh 14 Lectures 1.5 hours Satish 26 Lectures 1.5 hours YouAccel Print Add Notes Bookmark this page
[ { "code": null, "e": 2333, "s": 2133, "text": "Ubuntu is a Linux based operating system and most Linux users are more familiar with the command line interface. In this chapter, we will go through some of the popular command line’s used in Ubuntu." }, { "code": null, "e": 2434, "s": 2333, "text": "To invoke the command line, go to the search option and enter the command keyword in the search box." }, { "code": null, "e": 2557, "s": 2434, "text": "The search result will give the Terminal option. Double-lick to get the command line as shown in the following screenshot." }, { "code": null, "e": 2671, "s": 2557, "text": "The easiest command to start with, is the directory listing command which is used to list the directory contents." }, { "code": null, "e": 2697, "s": 2671, "text": "ls –option directoryname\n" }, { "code": null, "e": 2765, "s": 2697, "text": "Option − These are the options to be specified with the ls command." }, { "code": null, "e": 2833, "s": 2765, "text": "Option − These are the options to be specified with the ls command." }, { "code": null, "e": 2934, "s": 2833, "text": "Directoryname − This is the optional directory name that can be specified along with the ls command." }, { "code": null, "e": 3035, "s": 2934, "text": "Directoryname − This is the optional directory name that can be specified along with the ls command." }, { "code": null, "e": 3093, "s": 3035, "text": "The output will be the listing of the directory contents." }, { "code": null, "e": 3180, "s": 3093, "text": "In the following example, we just issue the ls command to list the directory contents." }, { "code": null, "e": 3256, "s": 3180, "text": "The directory listing of the current directory will be shown as the output." }, { "code": null, "e": 3423, "s": 3256, "text": "Another variant of the ls command is to list the directory, but with more details on each line item. This is shown in the following screenshot with the ls –l command." }, { "code": null, "e": 3474, "s": 3423, "text": "To clear the screen, we can use the clear command." }, { "code": null, "e": 3481, "s": 3474, "text": "clear\n" }, { "code": null, "e": 3486, "s": 3481, "text": "None" }, { "code": null, "e": 3527, "s": 3486, "text": "The command line screen will be cleared." }, { "code": null, "e": 3595, "s": 3527, "text": "To get more information on a command, we can use the ‘man’ command." }, { "code": null, "e": 3612, "s": 3595, "text": "man commandname\n" }, { "code": null, "e": 3698, "s": 3612, "text": "Commandname − This is the name of the command for which more information is required." }, { "code": null, "e": 3748, "s": 3698, "text": "The information on the command will be displayed." }, { "code": null, "e": 3917, "s": 3748, "text": "Following is an example of the ‘man’ command. If we issue the ‘man ls’ command, we will get the following output. The output will contain information on the ls command." }, { "code": null, "e": 3964, "s": 3917, "text": "We can use the find command to find for files." }, { "code": null, "e": 3982, "s": 3964, "text": "find filepattern\n" }, { "code": null, "e": 4040, "s": 3982, "text": "Filepattern − This is the pattern used to find for files." }, { "code": null, "e": 4095, "s": 4040, "text": "The files based on the file pattern will be displayed." }, { "code": null, "e": 4149, "s": 4095, "text": "In this example, we will issue the following command." }, { "code": null, "e": 4164, "s": 4149, "text": "find Sample.*\n" }, { "code": null, "e": 4237, "s": 4164, "text": "This command will list all the files which start with the word ‘Sample’." }, { "code": null, "e": 4304, "s": 4237, "text": "This command is used to display who is the current logged on user." }, { "code": null, "e": 4312, "s": 4304, "text": "whoami\n" }, { "code": null, "e": 4317, "s": 4312, "text": "None" }, { "code": null, "e": 4375, "s": 4317, "text": "The name of the current logged on user will be displayed." }, { "code": null, "e": 4429, "s": 4375, "text": "In this example, we will issue the following command." }, { "code": null, "e": 4437, "s": 4429, "text": "whoami\n" }, { "code": null, "e": 4494, "s": 4437, "text": "This command will display the current working directory." }, { "code": null, "e": 4499, "s": 4494, "text": "pwd\n" }, { "code": null, "e": 4504, "s": 4499, "text": "None" }, { "code": null, "e": 4553, "s": 4504, "text": "The current working directory will be displayed." }, { "code": null, "e": 4607, "s": 4553, "text": "In this example, we will issue the following command." }, { "code": null, "e": 4612, "s": 4607, "text": "Pwd\n" }, { "code": null, "e": 4643, "s": 4612, "text": "\n 8 Lectures \n 31 mins\n" }, { "code": null, "e": 4659, "s": 4643, "text": " Musab Zayadneh" }, { "code": null, "e": 4694, "s": 4659, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4702, "s": 4694, "text": " Satish" }, { "code": null, "e": 4737, "s": 4702, "text": "\n 26 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4747, "s": 4737, "text": " YouAccel" }, { "code": null, "e": 4754, "s": 4747, "text": " Print" }, { "code": null, "e": 4765, "s": 4754, "text": " Add Notes" } ]
Find probability that a player wins when probabilities of hitting the target are given - GeeksforGeeks
10 Jan, 2022 Given four integers p, q, r, and s. Two players are playing a game where both the players hit a target and the first player who hits the target wins the game. The probability of the first player hitting the target is p / q and that of the second player hitting the target is r / s. The task is to find the probability of the first player winning the game. Examples: Input: p = 1, q = 4, r = 3, s = 4 Output: 0.307692308 Input: p = 1, q = 2, r = 1, s = 2 Output: 0.666666667 Approach: The probability of the first player hitting the target is p / q and missing the target is 1 – p / q. The probability of the second player hitting the target is r / s and missing the target is 1 – r / s. Let the first player be x and the second player is y. So the total probability will be x won + (x lost * y lost * x won) + (x lost * y lost * x lost * y lost * x won) + ... so on. Because x can win at any turn, it’s an infinite sequence. Let t = (1 – p / q) * (1 – r / s). Here t < 1 as p / q and r / s are always <1. So the series will become, p / q + (p / q) * t + (p / q) * t2 + ... This is an infinite GP series with a common ratio of less than 1 and its sum will be (p / q) / (1 – t). Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the probability of the winnerdouble find_probability(double p, double q, double r, double s){ double t = (1 - p / q) * (1 - r / s); double ans = (p / q) / (1 - t); return ans;} // Driver Codeint main(){ double p = 1, q = 2, r = 1, s = 2; // Will print 9 digits after the decimal point cout << fixed << setprecision(9) << find_probability(p, q, r, s); return 0;} // Java implementation of the approachimport java.util.*;import java.text.DecimalFormat; class solution{ // Function to return the probability of the winnerstatic double find_probability(double p, double q, double r, double s){ double t = (1 - p / q) * (1 - r / s); double ans = (p / q) / (1 - t); return ans;} // Driver Codepublic static void main(String args[]){ double p = 1, q = 2, r = 1, s = 2; // Will print 9 digits after the decimal point DecimalFormat dec = new DecimalFormat("#0.000000000"); System.out.println(dec.format(find_probability(p, q, r, s)));}}// This code is contributed by// Surendra_Gangwar # Python3 implementation of the approach # Function to return the probability# of the winnerdef find_probability(p, q, r, s) : t = (1 - p / q) * (1 - r / s) ans = (p / q) / (1 - t); return round(ans, 9) # Driver Codeif __name__ == "__main__" : p, q, r, s = 1, 2, 1, 2 # Will print 9 digits after # the decimal point print(find_probability(p, q, r, s)) # This code is contributed by Ryuga // C# implementation of the approachusing System; class GFG{ // Function to return the probability of the winnerstatic double find_probability(double p, double q, double r, double s){ double t = (1 - p / q) * (1 - r / s); double ans = (p / q) / (1 - t); return ans;} // Driver Codepublic static void Main(){ double p = 1, q = 2, r = 1, s = 2; Console.WriteLine(find_probability(p, q, r, s));}} // This code is contributed by// anuj_67.. <?php// PHP implementation of the approach // Function to return the probability// of the winnerfunction find_probability($p, $q, $r, $s){ $t = (1 - $p / $q) * (1 - $r / $s); $ans = ($p / $q) / (1 - $t); return $ans;} // Driver Code$p = 1; $q = 2;$r = 1; $s = 2; // Will print 9 digits after// the decimal point$res = find_probability($p, $q, $r, $s);$update = number_format($res, 7);echo $update; // This code is contributed by Rajput-Ji?> <script> // Javascript implementation of the approach // Function to return the probability of the winnerfunction find_probability(p, q, r, s){ var t = (1 - p / q) * (1 - r / s); var ans = (p / q) / (1 - t); return ans;} // Driver Codevar p = 1, q = 2, r = 1, s = 2;// Will print 9 digits after the decimal pointdocument.write( find_probability(p, q, r, s).toFixed(9)); </script> 0.666666667 ankthon SURENDRA_GANGWAR Rajput-Ji vt_m rutvik_56 surinderdawra388 Probability Game Theory Mathematical Mathematical Game Theory Probability Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Combinatorial Game Theory | Set 2 (Game of Nim) Minimax Algorithm in Game Theory | Set 2 (Introduction to Evaluation Function) Expectimax Algorithm in Game Theory Find the winner in nim-game Combinatorial Game Theory | Set 1 (Introduction) 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": 24973, "s": 24945, "text": "\n10 Jan, 2022" }, { "code": null, "e": 25329, "s": 24973, "text": "Given four integers p, q, r, and s. Two players are playing a game where both the players hit a target and the first player who hits the target wins the game. The probability of the first player hitting the target is p / q and that of the second player hitting the target is r / s. The task is to find the probability of the first player winning the game." }, { "code": null, "e": 25340, "s": 25329, "text": "Examples: " }, { "code": null, "e": 25394, "s": 25340, "text": "Input: p = 1, q = 4, r = 3, s = 4 Output: 0.307692308" }, { "code": null, "e": 25449, "s": 25394, "text": "Input: p = 1, q = 2, r = 1, s = 2 Output: 0.666666667 " }, { "code": null, "e": 26152, "s": 25449, "text": "Approach: The probability of the first player hitting the target is p / q and missing the target is 1 – p / q. The probability of the second player hitting the target is r / s and missing the target is 1 – r / s. Let the first player be x and the second player is y. So the total probability will be x won + (x lost * y lost * x won) + (x lost * y lost * x lost * y lost * x won) + ... so on. Because x can win at any turn, it’s an infinite sequence. Let t = (1 – p / q) * (1 – r / s). Here t < 1 as p / q and r / s are always <1. So the series will become, p / q + (p / q) * t + (p / q) * t2 + ... This is an infinite GP series with a common ratio of less than 1 and its sum will be (p / q) / (1 – t)." }, { "code": null, "e": 26205, "s": 26152, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26209, "s": 26205, "text": "C++" }, { "code": null, "e": 26214, "s": 26209, "text": "Java" }, { "code": null, "e": 26222, "s": 26214, "text": "Python3" }, { "code": null, "e": 26225, "s": 26222, "text": "C#" }, { "code": null, "e": 26229, "s": 26225, "text": "PHP" }, { "code": null, "e": 26240, "s": 26229, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the probability of the winnerdouble find_probability(double p, double q, double r, double s){ double t = (1 - p / q) * (1 - r / s); double ans = (p / q) / (1 - t); return ans;} // Driver Codeint main(){ double p = 1, q = 2, r = 1, s = 2; // Will print 9 digits after the decimal point cout << fixed << setprecision(9) << find_probability(p, q, r, s); return 0;}", "e": 26763, "s": 26240, "text": null }, { "code": "// Java implementation of the approachimport java.util.*;import java.text.DecimalFormat; class solution{ // Function to return the probability of the winnerstatic double find_probability(double p, double q, double r, double s){ double t = (1 - p / q) * (1 - r / s); double ans = (p / q) / (1 - t); return ans;} // Driver Codepublic static void main(String args[]){ double p = 1, q = 2, r = 1, s = 2; // Will print 9 digits after the decimal point DecimalFormat dec = new DecimalFormat(\"#0.000000000\"); System.out.println(dec.format(find_probability(p, q, r, s)));}}// This code is contributed by// Surendra_Gangwar", "e": 27426, "s": 26763, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the probability# of the winnerdef find_probability(p, q, r, s) : t = (1 - p / q) * (1 - r / s) ans = (p / q) / (1 - t); return round(ans, 9) # Driver Codeif __name__ == \"__main__\" : p, q, r, s = 1, 2, 1, 2 # Will print 9 digits after # the decimal point print(find_probability(p, q, r, s)) # This code is contributed by Ryuga", "e": 27844, "s": 27426, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the probability of the winnerstatic double find_probability(double p, double q, double r, double s){ double t = (1 - p / q) * (1 - r / s); double ans = (p / q) / (1 - t); return ans;} // Driver Codepublic static void Main(){ double p = 1, q = 2, r = 1, s = 2; Console.WriteLine(find_probability(p, q, r, s));}} // This code is contributed by// anuj_67..", "e": 28322, "s": 27844, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the probability// of the winnerfunction find_probability($p, $q, $r, $s){ $t = (1 - $p / $q) * (1 - $r / $s); $ans = ($p / $q) / (1 - $t); return $ans;} // Driver Code$p = 1; $q = 2;$r = 1; $s = 2; // Will print 9 digits after// the decimal point$res = find_probability($p, $q, $r, $s);$update = number_format($res, 7);echo $update; // This code is contributed by Rajput-Ji?>", "e": 28774, "s": 28322, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the probability of the winnerfunction find_probability(p, q, r, s){ var t = (1 - p / q) * (1 - r / s); var ans = (p / q) / (1 - t); return ans;} // Driver Codevar p = 1, q = 2, r = 1, s = 2;// Will print 9 digits after the decimal pointdocument.write( find_probability(p, q, r, s).toFixed(9)); </script>", "e": 29168, "s": 28774, "text": null }, { "code": null, "e": 29180, "s": 29168, "text": "0.666666667" }, { "code": null, "e": 29190, "s": 29182, "text": "ankthon" }, { "code": null, "e": 29207, "s": 29190, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 29217, "s": 29207, "text": "Rajput-Ji" }, { "code": null, "e": 29222, "s": 29217, "text": "vt_m" }, { "code": null, "e": 29232, "s": 29222, "text": "rutvik_56" }, { "code": null, "e": 29249, "s": 29232, "text": "surinderdawra388" }, { "code": null, "e": 29261, "s": 29249, "text": "Probability" }, { "code": null, "e": 29273, "s": 29261, "text": "Game Theory" }, { "code": null, "e": 29286, "s": 29273, "text": "Mathematical" }, { "code": null, "e": 29299, "s": 29286, "text": "Mathematical" }, { "code": null, "e": 29311, "s": 29299, "text": "Game Theory" }, { "code": null, "e": 29323, "s": 29311, "text": "Probability" }, { "code": null, "e": 29421, "s": 29323, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29430, "s": 29421, "text": "Comments" }, { "code": null, "e": 29443, "s": 29430, "text": "Old Comments" }, { "code": null, "e": 29491, "s": 29443, "text": "Combinatorial Game Theory | Set 2 (Game of Nim)" }, { "code": null, "e": 29570, "s": 29491, "text": "Minimax Algorithm in Game Theory | Set 2 (Introduction to Evaluation Function)" }, { "code": null, "e": 29606, "s": 29570, "text": "Expectimax Algorithm in Game Theory" }, { "code": null, "e": 29634, "s": 29606, "text": "Find the winner in nim-game" }, { "code": null, "e": 29683, "s": 29634, "text": "Combinatorial Game Theory | Set 1 (Introduction)" }, { "code": null, "e": 29713, "s": 29683, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 29773, "s": 29713, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 29788, "s": 29773, "text": "C++ Data Types" }, { "code": null, "e": 29831, "s": 29788, "text": "Set in C++ Standard Template Library (STL)" } ]
Gradient Descent Algorithm and Its Variants | by Imad Dabbura | Towards Data Science
Optimization refers to the task of minimizing/maximizing an objective function f(x) parameterized by x. In machine/deep learning terminology, it’s the task of minimizing the cost/loss function J(w) parameterized by the model’s parameters w ∈ R^d. Optimization algorithms (in case of minimization) have one of the following goals: Find the global minimum of the objective function. This is feasible if the objective function is convex, i.e. any local minimum is a global minimum. Find the lowest possible value of the objective function within its neighborhood. That’s usually the case if the objective function is not convex as the case in most deep learning problems. There are three kinds of optimization algorithms: Optimization algorithm that is not iterative and simply solves for one point. Optimization algorithm that is iterative in nature and converges to acceptable solution regardless of the parameters initialization such as gradient descent applied to logistic regression. Optimization algorithm that is iterative in nature and applied to a set of problems that have non-convex cost functions such as neural networks. Therefore, parameters’ initialization plays a critical role in speeding up convergence and achieving lower error rates. Gradient Descent is the most common optimization algorithm in machine learning and deep learning. It is a first-order optimization algorithm. This means it only takes into account the first derivative when performing the updates on the parameters. On each iteration, we update the parameters in the opposite direction of the gradient of the objective function J(w) w.r.t the parameters where the gradient gives the direction of the steepest ascent. The size of the step we take on each iteration to reach the local minimum is determined by the learning rate α. Therefore, we follow the direction of the slope downhill until we reach a local minimum. In this article, we’ll cover gradient descent algorithm and its variants: Batch Gradient Descent, Mini-batch Gradient Descent, and Stochastic Gradient Descent. Let’s first see how gradient descent works on logistic regression before going into the details of its variants. For the sake of simplicity, let’s assume that the logistic regression model has only two parameters: weight w and bias b. 1. Initialize weight w and bias b to any random numbers. 2. Pick a value for the learning rate α. The learning rate determines how big the step would be on each iteration. If α is very small, it would take long time to converge and become computationally expensive. If α is large, it may fail to converge and overshoot the minimum. Therefore, plot the cost function against different values of α and pick the value of α that is right before the first value that didn’t converge so that we would have a very fast learning algorithm that converges (see figure 2). The most commonly used rates are : 0.001, 0.003, 0.01, 0.03, 0.1, 0.3. 3. Make sure to scale the data if it’s on a very different scales. If we don’t scale the data, the level curves (contours) would be narrower and taller which means it would take longer time to converge (see figure 3). Scale the data to have μ = 0 and σ = 1. Below is the formula for scaling each example: 4. On each iteration, take the partial derivative of the cost function J(w) w.r.t each parameter (gradient): The update equations are: For the sake of illustration, let’s assume we don’t have bias. If the slope of the current value of w > 0, this means that we are to the right of optimal w*. Therefore, the update will be negative, and will start getting close to the optimal values of w*. However, if it’s negative, the update will be positive and will increase the current values of w to converge to the optimal values of w*(see figure 4): Continue the process until the cost function converges. That is, until the error curve becomes flat and doesn’t change. In addition, on each iteration, the step would be in the direction that gives the maximum change since it’s perpendicular to level curves at each step. Now let’s discuss the three variants of gradient descent algorithm. The main difference between them is the amount of data we use when computing the gradients for each learning step. The trade-off between them is the accuracy of the gradient versus the time complexity to perform each parameter’s update (learning step). Batch Gradient Descent is when we sum up over all examples on each iteration when performing the updates to the parameters. Therefore, for each update, we have to sum over all examples: for i in range(num_epochs): grad = compute_gradient(data, params) params = params — learning_rate * grad The main advantages: We can use fixed learning rate during training without worrying about learning rate decay. It has straight trajectory towards the minimum and it is guaranteed to converge in theory to the global minimum if the loss function is convex and to a local minimum if the loss function is not convex. It has unbiased estimate of gradients. The more the examples, the lower the standard error. The main disadvantages: Even though we can use vectorized implementation, it may still be slow to go over all examples especially when we have large datasets. Each step of learning happens after going over all examples where some examples may be redundant and don’t contribute much to the update. Instead of going over all examples, Mini-batch Gradient Descent sums up over lower number of examples based on the batch size. Therefore, learning happens on each mini-batch of b examples: Shuffle the training data set to avoid pre-existing order of examples. Partition the training data set into b mini-batches based on the batch size. If the training set size is not divisible by batch size, the remaining will be its own batch. for i in range(num_epochs): np.random.shuffle(data) for batch in radom_minibatches(data, batch_size=32): grad = compute_gradient(batch, params) params = params — learning_rate * grad The batch size is something we can tune. It is usually chosen as power of 2 such as 32, 64, 128, 256, 512, etc. The reason behind it is because some hardware such as GPUs achieve better run time with common batch sizes such as power of 2. The main advantages: Faster than Batch version because it goes through a lot less examples than Batch (all examples). Randomly selecting examples will help avoid redundant examples or examples that are very similar that don’t contribute much to the learning. With batch size < size of training set, it adds noise to the learning process that helps improving generalization error. Even though with more examples the estimate would have lower standard error, the return is less than linear compared to the computational burden we incur. The main disadvantages: It won’t converge. On each iteration, the learning step may go back and forth due to the noise. Therefore, it wanders around the minimum region but never converges. Due to the noise, the learning steps have more oscillations (see figure 4) and requires adding learning-decay to decrease the learning rate as we become closer to the minimum. With large training datasets, we don’t usually need more than 2–10 passes over all training examples (epochs). Note: with batch size b = m (number of training examples), we get the Batch Gradient Descent. Instead of going through all examples, Stochastic Gradient Descent (SGD) performs the parameters update on each example (x^i,y^i). Therefore, learning happens on every example: Shuffle the training data set to avoid pre-existing order of examples. Partition the training data set into m examples. for i in range(num_epochs): np.random.shuffle(data) for example in data: grad = compute_gradient(example, params) params = params — learning_rate * grad It shares most of the advantages and the disadvantages with mini-batch version. Below are the ones that are specific to SGD: It adds even more noise to the learning process than mini-batch that helps improving generalization error. However, this would increase the run time. We can’t utilize vectorization over 1 example and becomes very slow. Also, the variance becomes large since we only use 1 example for each learning step. Below is a graph that shows the gradient descent’s variants and their direction towards the minimum: As the figure above shows, SGD direction is very noisy compared to mini-batch. Below are some challenges regarding gradient descent algorithm in general as well as its variants — mainly batch and mini-batch: Gradient descent is a first-order optimization algorithm, which means it doesn’t take into account the second derivatives of the cost function. However, the curvature of the function affects the size of each learning step. The gradient measures the steepness of the curve but the second derivative measures the curvature of the curve. Therefore, if: Second derivative = 0 →the curvature is linear. Therefore, the step size = the learning rate α.Second derivative > 0 → the curvature is going upward. Therefore, the step size < the learning rate α and may lead to divergence.Second derivative < 0 → the curvature is going downward. Therefore, the step size > the learning rate α. Second derivative = 0 →the curvature is linear. Therefore, the step size = the learning rate α. Second derivative > 0 → the curvature is going upward. Therefore, the step size < the learning rate α and may lead to divergence. Second derivative < 0 → the curvature is going downward. Therefore, the step size > the learning rate α. As a result, the direction that looks promising to the gradient may not be so and may lead to slow the learning process or even diverge. If Hessian matrix has poor conditioning number, i.e. the direction of the most curvature has much more curvature than the direction of the lowest curvature. This will lead the cost function to be very sensitive in some directions and insensitive in other directions. As a result, it will make it harder on the gradient because the direction that looks promising for the gradient may not lead to big changes in the cost function (see figure 7). The norm of the gradient gTg is supposed to decrease slowly with each learning step because the curve is getting flatter and steepness of the curve will decrease. However, we see that the norm of the gradient is increasing, because of the curvature of the curve. Nonetheless, even though the gradients’ norm is increasing, we’re able to achieve a very low error rates (see figure 8). In small dimensions, local minimum is common; however, in large dimensions, saddle points are more common. Saddle point is when the function curves up in some directions and curves down in other directions. In other words, saddle point looks like a minimum from one direction and a maximum from other direction (see figure 9). This happens when at least one eigenvalue of the hessian matrix is negative and the rest of eigenvalues are positive. As discussed previously, choosing a proper learning rate is hard. Also, for mini-batch gradient descent, we have to adjust the learning rate during the training process to make sure it converges to the local minimum and not wander around it. Figuring out the decay rate of the learning rate is also hard and changes with different data sets. All parameter updates have the same learning rate; however, we may want to perform larger updates to some parameters that have their directional derivatives more inline with the trajectory towards the minimum than other parameters. Originally published at imaddabbura.github.io on December 21, 2017.
[ { "code": null, "e": 502, "s": 172, "text": "Optimization refers to the task of minimizing/maximizing an objective function f(x) parameterized by x. In machine/deep learning terminology, it’s the task of minimizing the cost/loss function J(w) parameterized by the model’s parameters w ∈ R^d. Optimization algorithms (in case of minimization) have one of the following goals:" }, { "code": null, "e": 651, "s": 502, "text": "Find the global minimum of the objective function. This is feasible if the objective function is convex, i.e. any local minimum is a global minimum." }, { "code": null, "e": 841, "s": 651, "text": "Find the lowest possible value of the objective function within its neighborhood. That’s usually the case if the objective function is not convex as the case in most deep learning problems." }, { "code": null, "e": 891, "s": 841, "text": "There are three kinds of optimization algorithms:" }, { "code": null, "e": 969, "s": 891, "text": "Optimization algorithm that is not iterative and simply solves for one point." }, { "code": null, "e": 1158, "s": 969, "text": "Optimization algorithm that is iterative in nature and converges to acceptable solution regardless of the parameters initialization such as gradient descent applied to logistic regression." }, { "code": null, "e": 1423, "s": 1158, "text": "Optimization algorithm that is iterative in nature and applied to a set of problems that have non-convex cost functions such as neural networks. Therefore, parameters’ initialization plays a critical role in speeding up convergence and achieving lower error rates." }, { "code": null, "e": 2073, "s": 1423, "text": "Gradient Descent is the most common optimization algorithm in machine learning and deep learning. It is a first-order optimization algorithm. This means it only takes into account the first derivative when performing the updates on the parameters. On each iteration, we update the parameters in the opposite direction of the gradient of the objective function J(w) w.r.t the parameters where the gradient gives the direction of the steepest ascent. The size of the step we take on each iteration to reach the local minimum is determined by the learning rate α. Therefore, we follow the direction of the slope downhill until we reach a local minimum." }, { "code": null, "e": 2233, "s": 2073, "text": "In this article, we’ll cover gradient descent algorithm and its variants: Batch Gradient Descent, Mini-batch Gradient Descent, and Stochastic Gradient Descent." }, { "code": null, "e": 2468, "s": 2233, "text": "Let’s first see how gradient descent works on logistic regression before going into the details of its variants. For the sake of simplicity, let’s assume that the logistic regression model has only two parameters: weight w and bias b." }, { "code": null, "e": 2525, "s": 2468, "text": "1. Initialize weight w and bias b to any random numbers." }, { "code": null, "e": 2640, "s": 2525, "text": "2. Pick a value for the learning rate α. The learning rate determines how big the step would be on each iteration." }, { "code": null, "e": 2734, "s": 2640, "text": "If α is very small, it would take long time to converge and become computationally expensive." }, { "code": null, "e": 2800, "s": 2734, "text": "If α is large, it may fail to converge and overshoot the minimum." }, { "code": null, "e": 3030, "s": 2800, "text": "Therefore, plot the cost function against different values of α and pick the value of α that is right before the first value that didn’t converge so that we would have a very fast learning algorithm that converges (see figure 2)." }, { "code": null, "e": 3101, "s": 3030, "text": "The most commonly used rates are : 0.001, 0.003, 0.01, 0.03, 0.1, 0.3." }, { "code": null, "e": 3319, "s": 3101, "text": "3. Make sure to scale the data if it’s on a very different scales. If we don’t scale the data, the level curves (contours) would be narrower and taller which means it would take longer time to converge (see figure 3)." }, { "code": null, "e": 3406, "s": 3319, "text": "Scale the data to have μ = 0 and σ = 1. Below is the formula for scaling each example:" }, { "code": null, "e": 3515, "s": 3406, "text": "4. On each iteration, take the partial derivative of the cost function J(w) w.r.t each parameter (gradient):" }, { "code": null, "e": 3541, "s": 3515, "text": "The update equations are:" }, { "code": null, "e": 3949, "s": 3541, "text": "For the sake of illustration, let’s assume we don’t have bias. If the slope of the current value of w > 0, this means that we are to the right of optimal w*. Therefore, the update will be negative, and will start getting close to the optimal values of w*. However, if it’s negative, the update will be positive and will increase the current values of w to converge to the optimal values of w*(see figure 4):" }, { "code": null, "e": 4069, "s": 3949, "text": "Continue the process until the cost function converges. That is, until the error curve becomes flat and doesn’t change." }, { "code": null, "e": 4221, "s": 4069, "text": "In addition, on each iteration, the step would be in the direction that gives the maximum change since it’s perpendicular to level curves at each step." }, { "code": null, "e": 4542, "s": 4221, "text": "Now let’s discuss the three variants of gradient descent algorithm. The main difference between them is the amount of data we use when computing the gradients for each learning step. The trade-off between them is the accuracy of the gradient versus the time complexity to perform each parameter’s update (learning step)." }, { "code": null, "e": 4728, "s": 4542, "text": "Batch Gradient Descent is when we sum up over all examples on each iteration when performing the updates to the parameters. Therefore, for each update, we have to sum over all examples:" }, { "code": null, "e": 4839, "s": 4728, "text": "for i in range(num_epochs): grad = compute_gradient(data, params) params = params — learning_rate * grad" }, { "code": null, "e": 4860, "s": 4839, "text": "The main advantages:" }, { "code": null, "e": 4951, "s": 4860, "text": "We can use fixed learning rate during training without worrying about learning rate decay." }, { "code": null, "e": 5153, "s": 4951, "text": "It has straight trajectory towards the minimum and it is guaranteed to converge in theory to the global minimum if the loss function is convex and to a local minimum if the loss function is not convex." }, { "code": null, "e": 5245, "s": 5153, "text": "It has unbiased estimate of gradients. The more the examples, the lower the standard error." }, { "code": null, "e": 5269, "s": 5245, "text": "The main disadvantages:" }, { "code": null, "e": 5404, "s": 5269, "text": "Even though we can use vectorized implementation, it may still be slow to go over all examples especially when we have large datasets." }, { "code": null, "e": 5542, "s": 5404, "text": "Each step of learning happens after going over all examples where some examples may be redundant and don’t contribute much to the update." }, { "code": null, "e": 5731, "s": 5542, "text": "Instead of going over all examples, Mini-batch Gradient Descent sums up over lower number of examples based on the batch size. Therefore, learning happens on each mini-batch of b examples:" }, { "code": null, "e": 5802, "s": 5731, "text": "Shuffle the training data set to avoid pre-existing order of examples." }, { "code": null, "e": 5973, "s": 5802, "text": "Partition the training data set into b mini-batches based on the batch size. If the training set size is not divisible by batch size, the remaining will be its own batch." }, { "code": null, "e": 6176, "s": 5973, "text": "for i in range(num_epochs): np.random.shuffle(data) for batch in radom_minibatches(data, batch_size=32): grad = compute_gradient(batch, params) params = params — learning_rate * grad" }, { "code": null, "e": 6415, "s": 6176, "text": "The batch size is something we can tune. It is usually chosen as power of 2 such as 32, 64, 128, 256, 512, etc. The reason behind it is because some hardware such as GPUs achieve better run time with common batch sizes such as power of 2." }, { "code": null, "e": 6436, "s": 6415, "text": "The main advantages:" }, { "code": null, "e": 6533, "s": 6436, "text": "Faster than Batch version because it goes through a lot less examples than Batch (all examples)." }, { "code": null, "e": 6674, "s": 6533, "text": "Randomly selecting examples will help avoid redundant examples or examples that are very similar that don’t contribute much to the learning." }, { "code": null, "e": 6795, "s": 6674, "text": "With batch size < size of training set, it adds noise to the learning process that helps improving generalization error." }, { "code": null, "e": 6950, "s": 6795, "text": "Even though with more examples the estimate would have lower standard error, the return is less than linear compared to the computational burden we incur." }, { "code": null, "e": 6974, "s": 6950, "text": "The main disadvantages:" }, { "code": null, "e": 7139, "s": 6974, "text": "It won’t converge. On each iteration, the learning step may go back and forth due to the noise. Therefore, it wanders around the minimum region but never converges." }, { "code": null, "e": 7315, "s": 7139, "text": "Due to the noise, the learning steps have more oscillations (see figure 4) and requires adding learning-decay to decrease the learning rate as we become closer to the minimum." }, { "code": null, "e": 7520, "s": 7315, "text": "With large training datasets, we don’t usually need more than 2–10 passes over all training examples (epochs). Note: with batch size b = m (number of training examples), we get the Batch Gradient Descent." }, { "code": null, "e": 7697, "s": 7520, "text": "Instead of going through all examples, Stochastic Gradient Descent (SGD) performs the parameters update on each example (x^i,y^i). Therefore, learning happens on every example:" }, { "code": null, "e": 7768, "s": 7697, "text": "Shuffle the training data set to avoid pre-existing order of examples." }, { "code": null, "e": 7817, "s": 7768, "text": "Partition the training data set into m examples." }, { "code": null, "e": 7990, "s": 7817, "text": "for i in range(num_epochs): np.random.shuffle(data) for example in data: grad = compute_gradient(example, params) params = params — learning_rate * grad" }, { "code": null, "e": 8115, "s": 7990, "text": "It shares most of the advantages and the disadvantages with mini-batch version. Below are the ones that are specific to SGD:" }, { "code": null, "e": 8265, "s": 8115, "text": "It adds even more noise to the learning process than mini-batch that helps improving generalization error. However, this would increase the run time." }, { "code": null, "e": 8419, "s": 8265, "text": "We can’t utilize vectorization over 1 example and becomes very slow. Also, the variance becomes large since we only use 1 example for each learning step." }, { "code": null, "e": 8520, "s": 8419, "text": "Below is a graph that shows the gradient descent’s variants and their direction towards the minimum:" }, { "code": null, "e": 8599, "s": 8520, "text": "As the figure above shows, SGD direction is very noisy compared to mini-batch." }, { "code": null, "e": 8728, "s": 8599, "text": "Below are some challenges regarding gradient descent algorithm in general as well as its variants — mainly batch and mini-batch:" }, { "code": null, "e": 9078, "s": 8728, "text": "Gradient descent is a first-order optimization algorithm, which means it doesn’t take into account the second derivatives of the cost function. However, the curvature of the function affects the size of each learning step. The gradient measures the steepness of the curve but the second derivative measures the curvature of the curve. Therefore, if:" }, { "code": null, "e": 9407, "s": 9078, "text": "Second derivative = 0 →the curvature is linear. Therefore, the step size = the learning rate α.Second derivative > 0 → the curvature is going upward. Therefore, the step size < the learning rate α and may lead to divergence.Second derivative < 0 → the curvature is going downward. Therefore, the step size > the learning rate α." }, { "code": null, "e": 9503, "s": 9407, "text": "Second derivative = 0 →the curvature is linear. Therefore, the step size = the learning rate α." }, { "code": null, "e": 9633, "s": 9503, "text": "Second derivative > 0 → the curvature is going upward. Therefore, the step size < the learning rate α and may lead to divergence." }, { "code": null, "e": 9738, "s": 9633, "text": "Second derivative < 0 → the curvature is going downward. Therefore, the step size > the learning rate α." }, { "code": null, "e": 9875, "s": 9738, "text": "As a result, the direction that looks promising to the gradient may not be so and may lead to slow the learning process or even diverge." }, { "code": null, "e": 10319, "s": 9875, "text": "If Hessian matrix has poor conditioning number, i.e. the direction of the most curvature has much more curvature than the direction of the lowest curvature. This will lead the cost function to be very sensitive in some directions and insensitive in other directions. As a result, it will make it harder on the gradient because the direction that looks promising for the gradient may not lead to big changes in the cost function (see figure 7)." }, { "code": null, "e": 10703, "s": 10319, "text": "The norm of the gradient gTg is supposed to decrease slowly with each learning step because the curve is getting flatter and steepness of the curve will decrease. However, we see that the norm of the gradient is increasing, because of the curvature of the curve. Nonetheless, even though the gradients’ norm is increasing, we’re able to achieve a very low error rates (see figure 8)." }, { "code": null, "e": 11148, "s": 10703, "text": "In small dimensions, local minimum is common; however, in large dimensions, saddle points are more common. Saddle point is when the function curves up in some directions and curves down in other directions. In other words, saddle point looks like a minimum from one direction and a maximum from other direction (see figure 9). This happens when at least one eigenvalue of the hessian matrix is negative and the rest of eigenvalues are positive." }, { "code": null, "e": 11490, "s": 11148, "text": "As discussed previously, choosing a proper learning rate is hard. Also, for mini-batch gradient descent, we have to adjust the learning rate during the training process to make sure it converges to the local minimum and not wander around it. Figuring out the decay rate of the learning rate is also hard and changes with different data sets." }, { "code": null, "e": 11722, "s": 11490, "text": "All parameter updates have the same learning rate; however, we may want to perform larger updates to some parameters that have their directional derivatives more inline with the trajectory towards the minimum than other parameters." } ]
Advanced Time Series Analysis in Python: Decomposition, Autocorrelation | Towards Data Science
Following my very well-received post and Kaggle notebook on every single Pandas function to manipulate time series, it is time to take the trajectory of this TS project to visualization. This post is about the core processes that make up an in-depth time series analysis. Specifically, we will talk about: Decomposition of time series — seasonality and trend analysis Analyzing and comparing multiple time series simultaneously Calculating autocorrelation and partial autocorrelation and what they represent and if seasonality or trends among multiple series affect each other. Most importantly, we will build some very cool visualizations, and this image should be a preview of what you will be learning. I hope you are as excited about learning these things as I when writing this article. Let’s begin. Read the notebook of the article here. Any time series distribution has 3 core components: Seasonality — does the data have a clear cyclical/periodic pattern?Trend — does the data represent a general upward or downward slope?Noise — what are the outliers or missing values that are not consistent with the rest of the data? Seasonality — does the data have a clear cyclical/periodic pattern? Trend — does the data represent a general upward or downward slope? Noise — what are the outliers or missing values that are not consistent with the rest of the data? Deconstructing a time series into these components is called decomposition, and we will explore each one in detail. Consider this TPS July Kaggle playground dataset: Obviously, summer months have higher temperatures, and we would expect this behavior to repeat every year. However, the human eye and its ability to detect patterns can only go so far. For example, it might be harder to find seasonal patterns from plots such as these: To find hidden seasonal patterns from time series like above, we will use the seasonal_decompose function from statsmodels: Using sm.tsa.seasonal_decompose on 'beef' time-series returns a DecomposeResult object with attributes like seasonal, trend and resid (more on the last two later). Above, we are plotting the seasonality, but the plot is not useful since it has too much noise. Let’s choose an interval to give the line some room to breathe: decomposition.seasonal["1999":"2005"].plot(); This plot shows that beef production really goes down at the beginning of each year, but it reaches its peak towards the end. Note on seasonal_decompose function: it produces small figures by default. You have to control its aspects on your own and the plot function does not accept most of the regular Matplotlib parameters. Now, let’s plot the seasonality of all types of meat over a 5-year interval: As you can see, each meat types have rather different seasonality patterns. Now, let’s explore trends. Once again, the overall trend of a time series shows whether it increased, decreased, or stayed constant (flat) over a time period. The above DecomposeResult object contains values that show the overall slope of a time series under the trend attribute. Let’s plot them for the meat production dataset: This plot is massively insightful compared to the simple line plot we saw in the beginning. Indeed, we now see that meat from lambs and veal production has decreased dramatically since the 1940s. This might be in part caused by the double or triple production increases in beef, broilers, and turkey. We are performing informed guesses now, but we will explore some powerful methods to validate them in later sections. The third component of time series is noise. There is nothing fancy about it like the other two components. It only shows random and irregular data points that could not be attributed to either seasonality or noise. You can plot them using the resid attribute from the DecomposeResult object: Calling plot on the whole DecomposeResult object will produce a plot with all components displayed on the same axes. Decomposing your times series helps you think of them in a structured manner. Instead of imagining a series as a value changing over time, you can think of it as a distribution with a particular seasonality signal or a feature with a particular slope. This level of data understanding can be a key factor during feature engineering and modeling. Working with multiple time series presents certain challenges. One example, as we saw, is the different scales each distribution comes in: When features with larger scales squish others to a flat line (lamb and veal), it is impossible to compare their growth. One solution is using normalization. When normalizing time series, you divide every data point in the distribution by the first sample. This has the effect of representing every single data point as the percentage increase relative to the first sample: meat.div(meat.iloc[0]).head() The best part is now, each distribution has the same scale. Let’s plot the meat production data by performing normalization: Beef and pork saw the highest percentage increases while veal and lamb meat production plummeted over the given time period. I know what you are saying: “Correlation? Really? What’s new....” But bear with me. A simple correlation heatmap can indeed tell a lot about the linear relationships between variables: What we are more interested in is how underlying components of time series affect each other. For example, let’s see how the seasonality of each time series influences others: This time, we are using a ClusterMap rather than a heatmap to see closely correlated groups with the help of dendrograms immediately. The plot tells us that the seasonality of beef, broilers, and other chicken meats are heavily correlated. The same is true with pork and lamb/mutton meats. This positive correlation can be indicative of close seasonality matches. For example, it is possible that increase/decrease patterns of beef, broilers, and other chicken meats often matched over the given period. Let’s do the same for trends, which I think should be more interesting: The above plot is awesome because it helps us validate our assumptions in the trend analysis section. Let’s look at the normalized plot of meat production once again: Can you match the patterns in the cluster map to the line plot? For example, beef has strong negative correlations with lamb/mutton and veal. This is matched by the fact that beef production tripled in amount while the production of the other two decreased by ~75% (seen from the line plot). The same observations can be made between pork and veal, lamb/mutton. I want you to tread carefully when making assumptions about correlated features. Always remember that correlation does not mean causation. When two features are heavily correlated, it does not mean an increase in one causes an increase in another. An example I like to use is that even though the number of storks in a town can correlate with the number of newborn babies, it does not mean that storks deliver the babies. It might take a while to draw the line between correlation and causation clearly, so why don’t you take a look at my other article on the topic. Autocorrelation is a powerful analysis tool for modeling time series data. As the name suggests, it involves computing the correlation coefficient. But here, rather than computing it between two features, correlation of a time series is found with a lagging version of itself. Let’s first look at an example plot and explain further: The XAxis of an autocorrelation function plot (ACF) is the lag number k. For example, when k=1, the correlation is found by shifting the series by 1. This is the same as using the shift function of Pandas: The YAXis is the amount of correlation at each lag k. The shaded red region is a confidence interval — if the height of the bars is outside this region, it means the correlation is statistically significant. Please pause and think of what you can learn from an ACF plot. They offer an alternative way of detecting patterns and seasonality. For example, the ACF plot of temperature in Celcius shows that the correlation at every 15 lags decreases or every 25 lags increases. When a clear trend exists in a time series, the autocorrelation tends to be high at small lags like 1 or 2. When seasonality exists, the autocorrelation goes up periodically at larger lags. Let’s look at another example: The ACF of carbon monoxide confirms that small lags tend to have high correlations. It also shows that every 25 lags, the correlation increases significantly but quickly drops down to the negative. But most of the downward bars are inside the shaded area, suggesting that they are not statistically significant. This ability to compare the relationship between past and present data points present a unique advantage. If you can associate the present value to points k periods before, this also means you can find a link to values that come after k periods. Besides, understanding autocorrelation is key to modeling time series with ARIMA models (a topic for another article). Even though discussing partial autocorrelation means we are getting way ahead of things, I will give you the gist. It is similar to autocorrelation — it is calculated using the series and its lagged version at k: The only difference is that this method tries to account for the effect the intervening lags have. For example, at lag 3, partial autocorrelation removes the effect lags 1 and 2 have on computing the correlation. While autocorrelation is useful for analyzing a time series's properties and choosing what type of ARIMA model to use, partial autocorrelation tells what order of autoregressive model to fit. Again, this topic will be discussed in-depth when we talk about forecasting. So, stay tuned! Congratulations! By reading this post, you learned powerful techniques to dissect any time series and derive meaningful insights. Most importantly, you now have the ability to apply these techniques to multiple time series and critically evaluate the relationships between them. Thank you for reading, and I will see you in the next one! Every Pandas Function You Can (Should) Use to Manipulate Time Series Comprehensive Guide on Multiclass Classification Metrics Practical Sklearn Feature Selection in 3 stages
[ { "code": null, "e": 359, "s": 172, "text": "Following my very well-received post and Kaggle notebook on every single Pandas function to manipulate time series, it is time to take the trajectory of this TS project to visualization." }, { "code": null, "e": 478, "s": 359, "text": "This post is about the core processes that make up an in-depth time series analysis. Specifically, we will talk about:" }, { "code": null, "e": 540, "s": 478, "text": "Decomposition of time series — seasonality and trend analysis" }, { "code": null, "e": 600, "s": 540, "text": "Analyzing and comparing multiple time series simultaneously" }, { "code": null, "e": 680, "s": 600, "text": "Calculating autocorrelation and partial autocorrelation and what they represent" }, { "code": null, "e": 750, "s": 680, "text": "and if seasonality or trends among multiple series affect each other." }, { "code": null, "e": 878, "s": 750, "text": "Most importantly, we will build some very cool visualizations, and this image should be a preview of what you will be learning." }, { "code": null, "e": 977, "s": 878, "text": "I hope you are as excited about learning these things as I when writing this article. Let’s begin." }, { "code": null, "e": 1016, "s": 977, "text": "Read the notebook of the article here." }, { "code": null, "e": 1068, "s": 1016, "text": "Any time series distribution has 3 core components:" }, { "code": null, "e": 1301, "s": 1068, "text": "Seasonality — does the data have a clear cyclical/periodic pattern?Trend — does the data represent a general upward or downward slope?Noise — what are the outliers or missing values that are not consistent with the rest of the data?" }, { "code": null, "e": 1369, "s": 1301, "text": "Seasonality — does the data have a clear cyclical/periodic pattern?" }, { "code": null, "e": 1437, "s": 1369, "text": "Trend — does the data represent a general upward or downward slope?" }, { "code": null, "e": 1536, "s": 1437, "text": "Noise — what are the outliers or missing values that are not consistent with the rest of the data?" }, { "code": null, "e": 1652, "s": 1536, "text": "Deconstructing a time series into these components is called decomposition, and we will explore each one in detail." }, { "code": null, "e": 1702, "s": 1652, "text": "Consider this TPS July Kaggle playground dataset:" }, { "code": null, "e": 1887, "s": 1702, "text": "Obviously, summer months have higher temperatures, and we would expect this behavior to repeat every year. However, the human eye and its ability to detect patterns can only go so far." }, { "code": null, "e": 1971, "s": 1887, "text": "For example, it might be harder to find seasonal patterns from plots such as these:" }, { "code": null, "e": 2095, "s": 1971, "text": "To find hidden seasonal patterns from time series like above, we will use the seasonal_decompose function from statsmodels:" }, { "code": null, "e": 2259, "s": 2095, "text": "Using sm.tsa.seasonal_decompose on 'beef' time-series returns a DecomposeResult object with attributes like seasonal, trend and resid (more on the last two later)." }, { "code": null, "e": 2419, "s": 2259, "text": "Above, we are plotting the seasonality, but the plot is not useful since it has too much noise. Let’s choose an interval to give the line some room to breathe:" }, { "code": null, "e": 2465, "s": 2419, "text": "decomposition.seasonal[\"1999\":\"2005\"].plot();" }, { "code": null, "e": 2591, "s": 2465, "text": "This plot shows that beef production really goes down at the beginning of each year, but it reaches its peak towards the end." }, { "code": null, "e": 2791, "s": 2591, "text": "Note on seasonal_decompose function: it produces small figures by default. You have to control its aspects on your own and the plot function does not accept most of the regular Matplotlib parameters." }, { "code": null, "e": 2868, "s": 2791, "text": "Now, let’s plot the seasonality of all types of meat over a 5-year interval:" }, { "code": null, "e": 2971, "s": 2868, "text": "As you can see, each meat types have rather different seasonality patterns. Now, let’s explore trends." }, { "code": null, "e": 3224, "s": 2971, "text": "Once again, the overall trend of a time series shows whether it increased, decreased, or stayed constant (flat) over a time period. The above DecomposeResult object contains values that show the overall slope of a time series under the trend attribute." }, { "code": null, "e": 3273, "s": 3224, "text": "Let’s plot them for the meat production dataset:" }, { "code": null, "e": 3469, "s": 3273, "text": "This plot is massively insightful compared to the simple line plot we saw in the beginning. Indeed, we now see that meat from lambs and veal production has decreased dramatically since the 1940s." }, { "code": null, "e": 3692, "s": 3469, "text": "This might be in part caused by the double or triple production increases in beef, broilers, and turkey. We are performing informed guesses now, but we will explore some powerful methods to validate them in later sections." }, { "code": null, "e": 3908, "s": 3692, "text": "The third component of time series is noise. There is nothing fancy about it like the other two components. It only shows random and irregular data points that could not be attributed to either seasonality or noise." }, { "code": null, "e": 3985, "s": 3908, "text": "You can plot them using the resid attribute from the DecomposeResult object:" }, { "code": null, "e": 4102, "s": 3985, "text": "Calling plot on the whole DecomposeResult object will produce a plot with all components displayed on the same axes." }, { "code": null, "e": 4448, "s": 4102, "text": "Decomposing your times series helps you think of them in a structured manner. Instead of imagining a series as a value changing over time, you can think of it as a distribution with a particular seasonality signal or a feature with a particular slope. This level of data understanding can be a key factor during feature engineering and modeling." }, { "code": null, "e": 4587, "s": 4448, "text": "Working with multiple time series presents certain challenges. One example, as we saw, is the different scales each distribution comes in:" }, { "code": null, "e": 4745, "s": 4587, "text": "When features with larger scales squish others to a flat line (lamb and veal), it is impossible to compare their growth. One solution is using normalization." }, { "code": null, "e": 4961, "s": 4745, "text": "When normalizing time series, you divide every data point in the distribution by the first sample. This has the effect of representing every single data point as the percentage increase relative to the first sample:" }, { "code": null, "e": 4991, "s": 4961, "text": "meat.div(meat.iloc[0]).head()" }, { "code": null, "e": 5116, "s": 4991, "text": "The best part is now, each distribution has the same scale. Let’s plot the meat production data by performing normalization:" }, { "code": null, "e": 5241, "s": 5116, "text": "Beef and pork saw the highest percentage increases while veal and lamb meat production plummeted over the given time period." }, { "code": null, "e": 5307, "s": 5241, "text": "I know what you are saying: “Correlation? Really? What’s new....”" }, { "code": null, "e": 5426, "s": 5307, "text": "But bear with me. A simple correlation heatmap can indeed tell a lot about the linear relationships between variables:" }, { "code": null, "e": 5602, "s": 5426, "text": "What we are more interested in is how underlying components of time series affect each other. For example, let’s see how the seasonality of each time series influences others:" }, { "code": null, "e": 5736, "s": 5602, "text": "This time, we are using a ClusterMap rather than a heatmap to see closely correlated groups with the help of dendrograms immediately." }, { "code": null, "e": 5966, "s": 5736, "text": "The plot tells us that the seasonality of beef, broilers, and other chicken meats are heavily correlated. The same is true with pork and lamb/mutton meats. This positive correlation can be indicative of close seasonality matches." }, { "code": null, "e": 6106, "s": 5966, "text": "For example, it is possible that increase/decrease patterns of beef, broilers, and other chicken meats often matched over the given period." }, { "code": null, "e": 6178, "s": 6106, "text": "Let’s do the same for trends, which I think should be more interesting:" }, { "code": null, "e": 6345, "s": 6178, "text": "The above plot is awesome because it helps us validate our assumptions in the trend analysis section. Let’s look at the normalized plot of meat production once again:" }, { "code": null, "e": 6637, "s": 6345, "text": "Can you match the patterns in the cluster map to the line plot? For example, beef has strong negative correlations with lamb/mutton and veal. This is matched by the fact that beef production tripled in amount while the production of the other two decreased by ~75% (seen from the line plot)." }, { "code": null, "e": 6707, "s": 6637, "text": "The same observations can be made between pork and veal, lamb/mutton." }, { "code": null, "e": 6955, "s": 6707, "text": "I want you to tread carefully when making assumptions about correlated features. Always remember that correlation does not mean causation. When two features are heavily correlated, it does not mean an increase in one causes an increase in another." }, { "code": null, "e": 7129, "s": 6955, "text": "An example I like to use is that even though the number of storks in a town can correlate with the number of newborn babies, it does not mean that storks deliver the babies." }, { "code": null, "e": 7274, "s": 7129, "text": "It might take a while to draw the line between correlation and causation clearly, so why don’t you take a look at my other article on the topic." }, { "code": null, "e": 7551, "s": 7274, "text": "Autocorrelation is a powerful analysis tool for modeling time series data. As the name suggests, it involves computing the correlation coefficient. But here, rather than computing it between two features, correlation of a time series is found with a lagging version of itself." }, { "code": null, "e": 7608, "s": 7551, "text": "Let’s first look at an example plot and explain further:" }, { "code": null, "e": 7814, "s": 7608, "text": "The XAxis of an autocorrelation function plot (ACF) is the lag number k. For example, when k=1, the correlation is found by shifting the series by 1. This is the same as using the shift function of Pandas:" }, { "code": null, "e": 8022, "s": 7814, "text": "The YAXis is the amount of correlation at each lag k. The shaded red region is a confidence interval — if the height of the bars is outside this region, it means the correlation is statistically significant." }, { "code": null, "e": 8085, "s": 8022, "text": "Please pause and think of what you can learn from an ACF plot." }, { "code": null, "e": 8288, "s": 8085, "text": "They offer an alternative way of detecting patterns and seasonality. For example, the ACF plot of temperature in Celcius shows that the correlation at every 15 lags decreases or every 25 lags increases." }, { "code": null, "e": 8478, "s": 8288, "text": "When a clear trend exists in a time series, the autocorrelation tends to be high at small lags like 1 or 2. When seasonality exists, the autocorrelation goes up periodically at larger lags." }, { "code": null, "e": 8509, "s": 8478, "text": "Let’s look at another example:" }, { "code": null, "e": 8821, "s": 8509, "text": "The ACF of carbon monoxide confirms that small lags tend to have high correlations. It also shows that every 25 lags, the correlation increases significantly but quickly drops down to the negative. But most of the downward bars are inside the shaded area, suggesting that they are not statistically significant." }, { "code": null, "e": 9067, "s": 8821, "text": "This ability to compare the relationship between past and present data points present a unique advantage. If you can associate the present value to points k periods before, this also means you can find a link to values that come after k periods." }, { "code": null, "e": 9186, "s": 9067, "text": "Besides, understanding autocorrelation is key to modeling time series with ARIMA models (a topic for another article)." }, { "code": null, "e": 9301, "s": 9186, "text": "Even though discussing partial autocorrelation means we are getting way ahead of things, I will give you the gist." }, { "code": null, "e": 9399, "s": 9301, "text": "It is similar to autocorrelation — it is calculated using the series and its lagged version at k:" }, { "code": null, "e": 9612, "s": 9399, "text": "The only difference is that this method tries to account for the effect the intervening lags have. For example, at lag 3, partial autocorrelation removes the effect lags 1 and 2 have on computing the correlation." }, { "code": null, "e": 9804, "s": 9612, "text": "While autocorrelation is useful for analyzing a time series's properties and choosing what type of ARIMA model to use, partial autocorrelation tells what order of autoregressive model to fit." }, { "code": null, "e": 9897, "s": 9804, "text": "Again, this topic will be discussed in-depth when we talk about forecasting. So, stay tuned!" }, { "code": null, "e": 9914, "s": 9897, "text": "Congratulations!" }, { "code": null, "e": 10176, "s": 9914, "text": "By reading this post, you learned powerful techniques to dissect any time series and derive meaningful insights. Most importantly, you now have the ability to apply these techniques to multiple time series and critically evaluate the relationships between them." }, { "code": null, "e": 10235, "s": 10176, "text": "Thank you for reading, and I will see you in the next one!" }, { "code": null, "e": 10304, "s": 10235, "text": "Every Pandas Function You Can (Should) Use to Manipulate Time Series" }, { "code": null, "e": 10361, "s": 10304, "text": "Comprehensive Guide on Multiclass Classification Metrics" } ]
Simple Machine Learning Model in Python in 5 lines of code | by Raman Sah | Towards Data Science
In this blog, we will train a Linear Regression Model and expect to perform correct on a fresh input. The basic idea of any machine learning model is that it is exposed to a large number of inputs and also supplied the output applicable for them. On analysing more and more data, it tries to figure out the relationship between input and the result. Consider a very primitive example when you have to decide whether to wear a jacket or not depending on the weather. You have access to the training data as we call it - +---------------------+---------------+| Outside Temperature | Wear a Jacket |+---------------------+---------------+| 30°C | No || 25°C | No || 20°C | No || 15°C | Yes || 10°C | Yes |+---------------------+---------------+ Somehow, your mind finds a connection between the input (temperature) and the output (decision to wear a jacket). So, if the temperature is 12°C, you would still wear a jacket although you were never told the outcome for that particular temperature. Now, lets move on to a slightly better algebraic problem which the computer will solve for us. Before we begin, don’t forget to install scikit-learn, it provides easy to use functions and predefined models which saves a lot of time pip install scikit-learn Here, X is the input and y is the output. Given the training set you could easily guess that the output (y) is nothing but (x1 + 2*x2 + 3*x3). Working with linear regression model is simple. Create a model, train it and then use it :) We have the training set ready, so create a Linear Regression Model and pass it the training data. X = [[10, 20, 30]] The outcome should be 10 + 20*2 + 30*3 = 140. Let’s see what we got... Outcome : [ 140.]Coefficients : [ 1. 2. 3.] Did you notice what just happened? The model had access to the training data, through which it calculated the weights to assign to the inputs to arrive at the desired output. On giving test data, it successfully managed to get the right answer! If you want to dive deeper into Machine Learning and use Python; I would prefer this book to start with. shop.oreilly.com I also experiment a lot and tinker with code. Feel free to fork ML Prototype where I have tried to expose the functions of scikit-learn through API. And don’t forget to clap if you find this article interesting.
[ { "code": null, "e": 273, "s": 171, "text": "In this blog, we will train a Linear Regression Model and expect to perform correct on a fresh input." }, { "code": null, "e": 521, "s": 273, "text": "The basic idea of any machine learning model is that it is exposed to a large number of inputs and also supplied the output applicable for them. On analysing more and more data, it tries to figure out the relationship between input and the result." }, { "code": null, "e": 690, "s": 521, "text": "Consider a very primitive example when you have to decide whether to wear a jacket or not depending on the weather. You have access to the training data as we call it -" }, { "code": null, "e": 1042, "s": 690, "text": "+---------------------+---------------+| Outside Temperature | Wear a Jacket |+---------------------+---------------+| 30°C | No || 25°C | No || 20°C | No || 15°C | Yes || 10°C | Yes |+---------------------+---------------+" }, { "code": null, "e": 1156, "s": 1042, "text": "Somehow, your mind finds a connection between the input (temperature) and the output (decision to wear a jacket)." }, { "code": null, "e": 1292, "s": 1156, "text": "So, if the temperature is 12°C, you would still wear a jacket although you were never told the outcome for that particular temperature." }, { "code": null, "e": 1387, "s": 1292, "text": "Now, lets move on to a slightly better algebraic problem which the computer will solve for us." }, { "code": null, "e": 1524, "s": 1387, "text": "Before we begin, don’t forget to install scikit-learn, it provides easy to use functions and predefined models which saves a lot of time" }, { "code": null, "e": 1549, "s": 1524, "text": "pip install scikit-learn" }, { "code": null, "e": 1591, "s": 1549, "text": "Here, X is the input and y is the output." }, { "code": null, "e": 1692, "s": 1591, "text": "Given the training set you could easily guess that the output (y) is nothing but (x1 + 2*x2 + 3*x3)." }, { "code": null, "e": 1784, "s": 1692, "text": "Working with linear regression model is simple. Create a model, train it and then use it :)" }, { "code": null, "e": 1883, "s": 1784, "text": "We have the training set ready, so create a Linear Regression Model and pass it the training data." }, { "code": null, "e": 1902, "s": 1883, "text": "X = [[10, 20, 30]]" }, { "code": null, "e": 1973, "s": 1902, "text": "The outcome should be 10 + 20*2 + 30*3 = 140. Let’s see what we got..." }, { "code": null, "e": 2017, "s": 1973, "text": "Outcome : [ 140.]Coefficients : [ 1. 2. 3.]" }, { "code": null, "e": 2262, "s": 2017, "text": "Did you notice what just happened? The model had access to the training data, through which it calculated the weights to assign to the inputs to arrive at the desired output. On giving test data, it successfully managed to get the right answer!" }, { "code": null, "e": 2367, "s": 2262, "text": "If you want to dive deeper into Machine Learning and use Python; I would prefer this book to start with." }, { "code": null, "e": 2384, "s": 2367, "text": "shop.oreilly.com" } ]
Python | bytearray() function - GeeksforGeeks
30 Jul, 2018 bytearray() method returns a bytearray object which is an array of given bytes. It gives a mutable sequence of integers in the range 0 <= x < 256. Syntax: bytearray(source, encoding, errors) Parameters: source[optional]: Initializes the array of bytes encoding[optional]: Encoding of the string errors[optional]: Takes action when encoding fails Returns: Returns an array of bytes of the given size. source parameter can be used to initialize the array in few different ways. Let’s discuss each one by one with help of examples. Code #1: If a string, must provided encoding and errors parameters, bytearray() converts the string to bytes using str.encode() str = "Geeksforgeeks" # encoding the string with unicode 8 and 16array1 = bytearray(str, 'utf-8')array2 = bytearray(str, 'utf-16') print(array1)print(array2) Output: bytearray(b'Geeksforgeeks') bytearray(b'\xff\xfeG\x00e\x00e\x00k\x00s\x00f\x00o\x00r\x00g\x00e\x00e\x00k\x00s\x00') Code #2: If an integer, creates an array of that size and initialized with null bytes. # size of arraysize = 3 # will create an array of given size # and initialize with null bytesarray1 = bytearray(size) print(array1) Output: bytearray(b'\x00\x00\x00') Code #3: If an Object, read-only buffer will be used to initialize the bytes array. # Creates bytearray from byte literalarr1 = bytearray(b"abcd") # iterating the valuefor value in arr1: print(value) # Create a bytearray objectarr2 = bytearray(b"aaaacccc") # count bytes from the bufferprint("Count of c is:", arr2.count(b"c")) Output: 97 98 99 100 Count of c is: 4 Code #4: If an Iterable(range 0<= x < 256), used as the initial contents of an array. # simple list of integerslist = [1, 2, 3, 4] # iterable as sourcearray = bytearray(list) print(array)print("Count of bytes:", len(array)) Output: bytearray(b'\x01\x02\x03\x04') Count of bytes: 4 Code #5: If No source, an array of size 0 is created. # array of size o will be created # iterable as sourcearray = bytearray() print(array) Output: bytearray(b'') Python-Built-in-functions 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 program to convert a list to string Python String | replace() Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24313, "s": 24285, "text": "\n30 Jul, 2018" }, { "code": null, "e": 24460, "s": 24313, "text": "bytearray() method returns a bytearray object which is an array of given bytes. It gives a mutable sequence of integers in the range 0 <= x < 256." }, { "code": null, "e": 24468, "s": 24460, "text": "Syntax:" }, { "code": null, "e": 24504, "s": 24468, "text": "bytearray(source, encoding, errors)" }, { "code": null, "e": 24516, "s": 24504, "text": "Parameters:" }, { "code": null, "e": 24660, "s": 24516, "text": "source[optional]: Initializes the array of bytes\nencoding[optional]: Encoding of the string\nerrors[optional]: Takes action when encoding fails\n" }, { "code": null, "e": 24714, "s": 24660, "text": "Returns: Returns an array of bytes of the given size." }, { "code": null, "e": 24843, "s": 24714, "text": "source parameter can be used to initialize the array in few different ways. Let’s discuss each one by one with help of examples." }, { "code": null, "e": 24971, "s": 24843, "text": "Code #1: If a string, must provided encoding and errors parameters, bytearray() converts the string to bytes using str.encode()" }, { "code": "str = \"Geeksforgeeks\" # encoding the string with unicode 8 and 16array1 = bytearray(str, 'utf-8')array2 = bytearray(str, 'utf-16') print(array1)print(array2)", "e": 25131, "s": 24971, "text": null }, { "code": null, "e": 25139, "s": 25131, "text": "Output:" }, { "code": null, "e": 25255, "s": 25139, "text": "bytearray(b'Geeksforgeeks')\nbytearray(b'\\xff\\xfeG\\x00e\\x00e\\x00k\\x00s\\x00f\\x00o\\x00r\\x00g\\x00e\\x00e\\x00k\\x00s\\x00')" }, { "code": null, "e": 25343, "s": 25255, "text": " Code #2: If an integer, creates an array of that size and initialized with null bytes." }, { "code": "# size of arraysize = 3 # will create an array of given size # and initialize with null bytesarray1 = bytearray(size) print(array1)", "e": 25477, "s": 25343, "text": null }, { "code": null, "e": 25485, "s": 25477, "text": "Output:" }, { "code": null, "e": 25512, "s": 25485, "text": "bytearray(b'\\x00\\x00\\x00')" }, { "code": null, "e": 25597, "s": 25512, "text": " Code #3: If an Object, read-only buffer will be used to initialize the bytes array." }, { "code": "# Creates bytearray from byte literalarr1 = bytearray(b\"abcd\") # iterating the valuefor value in arr1: print(value) # Create a bytearray objectarr2 = bytearray(b\"aaaacccc\") # count bytes from the bufferprint(\"Count of c is:\", arr2.count(b\"c\"))", "e": 25851, "s": 25597, "text": null }, { "code": null, "e": 25859, "s": 25851, "text": "Output:" }, { "code": null, "e": 25889, "s": 25859, "text": "97\n98\n99\n100\nCount of c is: 4" }, { "code": null, "e": 25976, "s": 25889, "text": " Code #4: If an Iterable(range 0<= x < 256), used as the initial contents of an array." }, { "code": "# simple list of integerslist = [1, 2, 3, 4] # iterable as sourcearray = bytearray(list) print(array)print(\"Count of bytes:\", len(array))", "e": 26116, "s": 25976, "text": null }, { "code": null, "e": 26124, "s": 26116, "text": "Output:" }, { "code": null, "e": 26173, "s": 26124, "text": "bytearray(b'\\x01\\x02\\x03\\x04')\nCount of bytes: 4" }, { "code": null, "e": 26227, "s": 26173, "text": "Code #5: If No source, an array of size 0 is created." }, { "code": "# array of size o will be created # iterable as sourcearray = bytearray() print(array)", "e": 26316, "s": 26227, "text": null }, { "code": null, "e": 26324, "s": 26316, "text": "Output:" }, { "code": null, "e": 26339, "s": 26324, "text": "bytearray(b'')" }, { "code": null, "e": 26365, "s": 26339, "text": "Python-Built-in-functions" }, { "code": null, "e": 26372, "s": 26365, "text": "Python" }, { "code": null, "e": 26470, "s": 26372, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26479, "s": 26470, "text": "Comments" }, { "code": null, "e": 26492, "s": 26479, "text": "Old Comments" }, { "code": null, "e": 26510, "s": 26492, "text": "Python Dictionary" }, { "code": null, "e": 26545, "s": 26510, "text": "Read a file line by line in Python" }, { "code": null, "e": 26567, "s": 26545, "text": "Enumerate() in Python" }, { "code": null, "e": 26599, "s": 26567, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26629, "s": 26599, "text": "Iterate over a list in Python" }, { "code": null, "e": 26671, "s": 26629, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26714, "s": 26671, "text": "Python program to convert a list to string" }, { "code": null, "e": 26740, "s": 26714, "text": "Python String | replace()" }, { "code": null, "e": 26784, "s": 26740, "text": "Reading and Writing to text files in Python" } ]
Big Data Analytics - Introduction to R
This section is devoted to introduce the users to the R programming language. R can be downloaded from the cran website. For Windows users, it is useful to install rtools and the rstudio IDE. The general concept behind R is to serve as an interface to other software developed in compiled languages such as C, C++, and Fortran and to give the user an interactive tool to analyze data. Navigate to the folder of the book zip file bda/part2/R_introduction and open the R_introduction.Rproj file. This will open an RStudio session. Then open the 01_vectors.R file. Run the script line by line and follow the comments in the code. Another useful option in order to learn is to just type the code, this will help you get used to R syntax. In R comments are written with the # symbol. In order to display the results of running R code in the book, after code is evaluated, the results R returns are commented. This way, you can copy paste the code in the book and try directly sections of it in R. # Create a vector of numbers numbers = c(1, 2, 3, 4, 5) print(numbers) # [1] 1 2 3 4 5 # Create a vector of letters ltrs = c('a', 'b', 'c', 'd', 'e') # [1] "a" "b" "c" "d" "e" # Concatenate both mixed_vec = c(numbers, ltrs) print(mixed_vec) # [1] "1" "2" "3" "4" "5" "a" "b" "c" "d" "e" Let’s analyze what happened in the previous code. We can see it is possible to create vectors with numbers and with letters. We did not need to tell R what type of data type we wanted beforehand. Finally, we were able to create a vector with both numbers and letters. The vector mixed_vec has coerced the numbers to character, we can see this by visualizing how the values are printed inside quotes. The following code shows the data type of different vectors as returned by the function class. It is common to use the class function to "interrogate" an object, asking him what his class is. ### Evaluate the data types using class ### One dimensional objects # Integer vector num = 1:10 class(num) # [1] "integer" # Numeric vector, it has a float, 10.5 num = c(1:10, 10.5) class(num) # [1] "numeric" # Character vector ltrs = letters[1:10] class(ltrs) # [1] "character" # Factor vector fac = as.factor(ltrs) class(fac) # [1] "factor" R supports two-dimensional objects also. In the following code, there are examples of the two most popular data structures used in R: the matrix and data.frame. # Matrix M = matrix(1:12, ncol = 4) # [,1] [,2] [,3] [,4] # [1,] 1 4 7 10 # [2,] 2 5 8 11 # [3,] 3 6 9 12 lM = matrix(letters[1:12], ncol = 4) # [,1] [,2] [,3] [,4] # [1,] "a" "d" "g" "j" # [2,] "b" "e" "h" "k" # [3,] "c" "f" "i" "l" # Coerces the numbers to character # cbind concatenates two matrices (or vectors) in one matrix cbind(M, lM) # [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] # [1,] "1" "4" "7" "10" "a" "d" "g" "j" # [2,] "2" "5" "8" "11" "b" "e" "h" "k" # [3,] "3" "6" "9" "12" "c" "f" "i" "l" class(M) # [1] "matrix" class(lM) # [1] "matrix" # data.frame # One of the main objects of R, handles different data types in the same object. # It is possible to have numeric, character and factor vectors in the same data.frame df = data.frame(n = 1:5, l = letters[1:5]) df # n l # 1 1 a # 2 2 b # 3 3 c # 4 4 d # 5 5 e As demonstrated in the previous example, it is possible to use different data types in the same object. In general, this is how data is presented in databases, APIs part of the data is text or character vectors and other numeric. In is the analyst job to determine which statistical data type to assign and then use the correct R data type for it. In statistics we normally consider variables are of the following types − Numeric Nominal or categorical Ordinal In R, a vector can be of the following classes − Numeric - Integer Factor Ordered Factor R provides a data type for each statistical type of variable. The ordered factor is however rarely used, but can be created by the function factor, or ordered. The following section treats the concept of indexing. This is a quite common operation, and deals with the problem of selecting sections of an object and making transformations to them. # Let's create a data.frame df = data.frame(numbers = 1:26, letters) head(df) # numbers letters # 1 1 a # 2 2 b # 3 3 c # 4 4 d # 5 5 e # 6 6 f # str gives the structure of a data.frame, it’s a good summary to inspect an object str(df) # 'data.frame': 26 obs. of 2 variables: # $ numbers: int 1 2 3 4 5 6 7 8 9 10 ... # $ letters: Factor w/ 26 levels "a","b","c","d",..: 1 2 3 4 5 6 7 8 9 10 ... # The latter shows the letters character vector was coerced as a factor. # This can be explained by the stringsAsFactors = TRUE argumnet in data.frame # read ?data.frame for more information class(df) # [1] "data.frame" ### Indexing # Get the first row df[1, ] # numbers letters # 1 1 a # Used for programming normally - returns the output as a list df[1, , drop = TRUE] # $numbers # [1] 1 # # $letters # [1] a # Levels: a b c d e f g h i j k l m n o p q r s t u v w x y z # Get several rows of the data.frame df[5:7, ] # numbers letters # 5 5 e # 6 6 f # 7 7 g ### Add one column that mixes the numeric column with the factor column df$mixed = paste(df$numbers, df$letters, sep = ’’) str(df) # 'data.frame': 26 obs. of 3 variables: # $ numbers: int 1 2 3 4 5 6 7 8 9 10 ... # $ letters: Factor w/ 26 levels "a","b","c","d",..: 1 2 3 4 5 6 7 8 9 10 ... # $ mixed : chr "1a" "2b" "3c" "4d" ... ### Get columns # Get the first column df[, 1] # It returns a one dimensional vector with that column # Get two columns df2 = df[, 1:2] head(df2) # numbers letters # 1 1 a # 2 2 b # 3 3 c # 4 4 d # 5 5 e # 6 6 f # Get the first and third columns df3 = df[, c(1, 3)] df3[1:3, ] # numbers mixed # 1 1 1a # 2 2 2b # 3 3 3c ### Index columns from their names names(df) # [1] "numbers" "letters" "mixed" # This is the best practice in programming, as many times indeces change, but variable names don’t # We create a variable with the names we want to subset keep_vars = c("numbers", "mixed") df4 = df[, keep_vars] head(df4) # numbers mixed # 1 1 1a # 2 2 2b # 3 3 3c # 4 4 4d # 5 5 5e # 6 6 6f ### subset rows and columns # Keep the first five rows df5 = df[1:5, keep_vars] df5 # numbers mixed # 1 1 1a # 2 2 2b # 3 3 3c # 4 4 4d # 5 5 5e # subset rows using a logical condition df6 = df[df$numbers < 10, keep_vars] df6 # numbers mixed # 1 1 1a # 2 2 2b # 3 3 3c # 4 4 4d # 5 5 5e # 6 6 6f # 7 7 7g # 8 8 8h # 9 9 9i 65 Lectures 6 hours Arnab Chakraborty 18 Lectures 1.5 hours Pranjal Srivastava, Harshit Srivastava 23 Lectures 2 hours John Shea 18 Lectures 1.5 hours Pranjal Srivastava 46 Lectures 3.5 hours Pranjal Srivastava 37 Lectures 3.5 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2746, "s": 2554, "text": "This section is devoted to introduce the users to the R programming language. R can be downloaded from the cran website. For Windows users, it is useful to install rtools and the rstudio IDE." }, { "code": null, "e": 2939, "s": 2746, "text": "The general concept behind R is to serve as an interface to other software developed in compiled languages such as C, C++, and Fortran and to give the user an interactive tool to analyze data." }, { "code": null, "e": 3333, "s": 2939, "text": "Navigate to the folder of the book zip file bda/part2/R_introduction and open the R_introduction.Rproj file. This will open an RStudio session. Then open the 01_vectors.R file. Run the script line by line and follow the comments in the code. Another useful option in order to learn is to just type the code, this will help you get used to R syntax. In R comments are written with the # symbol." }, { "code": null, "e": 3546, "s": 3333, "text": "In order to display the results of running R code in the book, after code is evaluated, the results R returns are commented. This way, you can copy paste the code in the book and try directly sections of it in R." }, { "code": null, "e": 3849, "s": 3546, "text": "# Create a vector of numbers \nnumbers = c(1, 2, 3, 4, 5) \nprint(numbers) \n\n# [1] 1 2 3 4 5 \n# Create a vector of letters \nltrs = c('a', 'b', 'c', 'd', 'e') \n# [1] \"a\" \"b\" \"c\" \"d\" \"e\" \n\n# Concatenate both \nmixed_vec = c(numbers, ltrs) \nprint(mixed_vec) \n# [1] \"1\" \"2\" \"3\" \"4\" \"5\" \"a\" \"b\" \"c\" \"d\" \"e\"\n" }, { "code": null, "e": 4249, "s": 3849, "text": "Let’s analyze what happened in the previous code. We can see it is possible to create vectors with numbers and with letters. We did not need to tell R what type of data type we wanted beforehand. Finally, we were able to create a vector with both numbers and letters. The vector mixed_vec has coerced the numbers to character, we can see this by visualizing how the values are printed inside quotes." }, { "code": null, "e": 4441, "s": 4249, "text": "The following code shows the data type of different vectors as returned by the function class. It is common to use the class function to \"interrogate\" an object, asking him what his class is." }, { "code": null, "e": 4808, "s": 4441, "text": "### Evaluate the data types using class\n\n### One dimensional objects \n# Integer vector \nnum = 1:10 \nclass(num) \n# [1] \"integer\" \n\n# Numeric vector, it has a float, 10.5 \nnum = c(1:10, 10.5) \nclass(num) \n# [1] \"numeric\" \n\n# Character vector \nltrs = letters[1:10] \nclass(ltrs) \n# [1] \"character\" \n\n# Factor vector \nfac = as.factor(ltrs) \nclass(fac) \n# [1] \"factor\"\n" }, { "code": null, "e": 4969, "s": 4808, "text": "R supports two-dimensional objects also. In the following code, there are examples of the two most popular data structures used in R: the matrix and data.frame." }, { "code": null, "e": 5918, "s": 4969, "text": "# Matrix\nM = matrix(1:12, ncol = 4) \n# [,1] [,2] [,3] [,4] \n# [1,] 1 4 7 10 \n# [2,] 2 5 8 11 \n# [3,] 3 6 9 12 \nlM = matrix(letters[1:12], ncol = 4) \n# [,1] [,2] [,3] [,4] \n# [1,] \"a\" \"d\" \"g\" \"j\" \n# [2,] \"b\" \"e\" \"h\" \"k\" \n# [3,] \"c\" \"f\" \"i\" \"l\" \n\n# Coerces the numbers to character \n# cbind concatenates two matrices (or vectors) in one matrix \ncbind(M, lM) \n# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] \n# [1,] \"1\" \"4\" \"7\" \"10\" \"a\" \"d\" \"g\" \"j\" \n# [2,] \"2\" \"5\" \"8\" \"11\" \"b\" \"e\" \"h\" \"k\" \n# [3,] \"3\" \"6\" \"9\" \"12\" \"c\" \"f\" \"i\" \"l\" \n\nclass(M) \n# [1] \"matrix\" \nclass(lM) \n# [1] \"matrix\" \n\n# data.frame \n# One of the main objects of R, handles different data types in the same object. \n# It is possible to have numeric, character and factor vectors in the same data.frame \n\ndf = data.frame(n = 1:5, l = letters[1:5]) \ndf \n# n l \n# 1 1 a \n# 2 2 b \n# 3 3 c \n# 4 4 d \n# 5 5 e \n" }, { "code": null, "e": 6340, "s": 5918, "text": "As demonstrated in the previous example, it is possible to use different data types in the same object. In general, this is how data is presented in databases, APIs part of the data is text or character vectors and other numeric. In is the analyst job to determine which statistical data type to assign and then use the correct R data type for it. In statistics we normally consider variables are of the following types −" }, { "code": null, "e": 6348, "s": 6340, "text": "Numeric" }, { "code": null, "e": 6371, "s": 6348, "text": "Nominal or categorical" }, { "code": null, "e": 6379, "s": 6371, "text": "Ordinal" }, { "code": null, "e": 6428, "s": 6379, "text": "In R, a vector can be of the following classes −" }, { "code": null, "e": 6446, "s": 6428, "text": "Numeric - Integer" }, { "code": null, "e": 6453, "s": 6446, "text": "Factor" }, { "code": null, "e": 6468, "s": 6453, "text": "Ordered Factor" }, { "code": null, "e": 6628, "s": 6468, "text": "R provides a data type for each statistical type of variable. The ordered factor is however rarely used, but can be created by the function factor, or ordered." }, { "code": null, "e": 6814, "s": 6628, "text": "The following section treats the concept of indexing. This is a quite common operation, and deals with the problem of selecting sections of an object and making transformations to them." }, { "code": null, "e": 9738, "s": 6814, "text": "# Let's create a data.frame\ndf = data.frame(numbers = 1:26, letters) \nhead(df) \n# numbers letters \n# 1 1 a \n# 2 2 b \n# 3 3 c \n# 4 4 d \n# 5 5 e \n# 6 6 f \n\n# str gives the structure of a data.frame, it’s a good summary to inspect an object \nstr(df) \n# 'data.frame': 26 obs. of 2 variables: \n# $ numbers: int 1 2 3 4 5 6 7 8 9 10 ... \n# $ letters: Factor w/ 26 levels \"a\",\"b\",\"c\",\"d\",..: 1 2 3 4 5 6 7 8 9 10 ... \n\n# The latter shows the letters character vector was coerced as a factor. \n# This can be explained by the stringsAsFactors = TRUE argumnet in data.frame \n# read ?data.frame for more information \n\nclass(df) \n# [1] \"data.frame\" \n\n### Indexing\n# Get the first row \ndf[1, ] \n# numbers letters \n# 1 1 a \n\n# Used for programming normally - returns the output as a list \ndf[1, , drop = TRUE] \n# $numbers \n# [1] 1 \n# \n# $letters \n# [1] a \n# Levels: a b c d e f g h i j k l m n o p q r s t u v w x y z \n\n# Get several rows of the data.frame \ndf[5:7, ] \n# numbers letters \n# 5 5 e \n# 6 6 f \n# 7 7 g \n\n### Add one column that mixes the numeric column with the factor column \ndf$mixed = paste(df$numbers, df$letters, sep = ’’) \n\nstr(df) \n# 'data.frame': 26 obs. of 3 variables: \n# $ numbers: int 1 2 3 4 5 6 7 8 9 10 ...\n# $ letters: Factor w/ 26 levels \"a\",\"b\",\"c\",\"d\",..: 1 2 3 4 5 6 7 8 9 10 ... \n# $ mixed : chr \"1a\" \"2b\" \"3c\" \"4d\" ... \n\n### Get columns \n# Get the first column \ndf[, 1] \n# It returns a one dimensional vector with that column \n\n# Get two columns \ndf2 = df[, 1:2] \nhead(df2) \n\n# numbers letters \n# 1 1 a \n# 2 2 b \n# 3 3 c \n# 4 4 d \n# 5 5 e \n# 6 6 f \n\n# Get the first and third columns \ndf3 = df[, c(1, 3)] \ndf3[1:3, ] \n\n# numbers mixed \n# 1 1 1a\n# 2 2 2b \n# 3 3 3c \n\n### Index columns from their names \nnames(df) \n# [1] \"numbers\" \"letters\" \"mixed\" \n# This is the best practice in programming, as many times indeces change, but \nvariable names don’t \n# We create a variable with the names we want to subset \nkeep_vars = c(\"numbers\", \"mixed\") \ndf4 = df[, keep_vars] \n\nhead(df4) \n# numbers mixed \n# 1 1 1a \n# 2 2 2b \n# 3 3 3c \n# 4 4 4d \n# 5 5 5e \n# 6 6 6f \n\n### subset rows and columns \n# Keep the first five rows \ndf5 = df[1:5, keep_vars] \ndf5 \n\n# numbers mixed \n# 1 1 1a \n# 2 2 2b\n# 3 3 3c \n# 4 4 4d \n# 5 5 5e \n\n# subset rows using a logical condition \ndf6 = df[df$numbers < 10, keep_vars] \ndf6 \n\n# numbers mixed \n# 1 1 1a \n# 2 2 2b \n# 3 3 3c \n# 4 4 4d \n# 5 5 5e \n# 6 6 6f \n# 7 7 7g \n# 8 8 8h \n# 9 9 9i \n" }, { "code": null, "e": 9771, "s": 9738, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 9790, "s": 9771, "text": " Arnab Chakraborty" }, { "code": null, "e": 9825, "s": 9790, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9865, "s": 9825, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 9898, "s": 9865, "text": "\n 23 Lectures \n 2 hours \n" }, { "code": null, "e": 9909, "s": 9898, "text": " John Shea" }, { "code": null, "e": 9944, "s": 9909, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9964, "s": 9944, "text": " Pranjal Srivastava" }, { "code": null, "e": 9999, "s": 9964, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10019, "s": 9999, "text": " Pranjal Srivastava" }, { "code": null, "e": 10054, "s": 10019, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10094, "s": 10054, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 10101, "s": 10094, "text": " Print" }, { "code": null, "e": 10112, "s": 10101, "text": " Add Notes" } ]
Python Conditions
Python supports the usual logical conditions from mathematics: Equals: a == b Not Equals: a != b Less than: a < b Less than or equal to: a <= b Greater than: a > b Greater than or equal to: a >= b These conditions can be used in several ways, most commonly in "if statements" and loops. An "if statement" is written by using the if keyword. If statement: In this example we use two variables, a and b, which are used as part of the if statement to test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we print to screen that "b is greater than a". Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose. If statement, without indentation (will raise an error): The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition". In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we print to screen that "a and b are equal". The else keyword catches anything which isn't caught by the preceding conditions. In this example a is greater than b, so the first condition is not true, also the elif condition is not true, so we go to the else condition and print to screen that "a is greater than b". You can also have an else without the elif: If you have only one statement to execute, you can put it on the same line as the if statement. One line if statement: If you have only one statement to execute, one for if, and one for else, you can put it all on the same line: One line if else statement: This technique is known as Ternary Operators, or Conditional Expressions. You can also have multiple else statements on the same line: One line if else statement, with 3 conditions: The and keyword is a logical operator, and is used to combine conditional statements: Test if a is greater than b, AND if c is greater than a: The or keyword is a logical operator, and is used to combine conditional statements: Test if a is greater than b, OR if a is greater than c: You can have if statements inside if statements, this is called nested if statements. if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error. Print "Hello World" if a is greater than b. a = 50 b = 10 a b print("Hello World") Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 63, "s": 0, "text": "Python supports the usual logical conditions from mathematics:" }, { "code": null, "e": 78, "s": 63, "text": "Equals: a == b" }, { "code": null, "e": 97, "s": 78, "text": "Not Equals: a != b" }, { "code": null, "e": 114, "s": 97, "text": "Less than: a < b" }, { "code": null, "e": 144, "s": 114, "text": "Less than or equal to: a <= b" }, { "code": null, "e": 164, "s": 144, "text": "Greater than: a > b" }, { "code": null, "e": 197, "s": 164, "text": "Greater than or equal to: a >= b" }, { "code": null, "e": 287, "s": 197, "text": "These conditions can be used in several ways, most commonly in \"if statements\" and loops." }, { "code": null, "e": 341, "s": 287, "text": "An \"if statement\" is written by using the if keyword." }, { "code": null, "e": 355, "s": 341, "text": "If statement:" }, { "code": null, "e": 599, "s": 355, "text": "In this example we use two variables, a and b,\nwhich are used as part of the if statement to test whether b is greater than a.\nAs a is 33, and b is 200,\nwe know that 200 is greater than 33, and so we print to screen that \"b is greater than a\"." }, { "code": null, "e": 770, "s": 599, "text": "Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose.\n\n" }, { "code": null, "e": 827, "s": 770, "text": "If statement, without indentation (will raise an error):" }, { "code": null, "e": 939, "s": 827, "text": "The elif keyword is pythons way of saying \"if the previous conditions were not true, then \ntry this condition\"." }, { "code": null, "e": 1088, "s": 939, "text": "In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we print to screen that \"a and b are equal\"." }, { "code": null, "e": 1170, "s": 1088, "text": "The else keyword catches anything which isn't caught by the preceding conditions." }, { "code": null, "e": 1359, "s": 1170, "text": "In this example a is greater than b,\nso the first condition is not true, also the elif condition is not true,\nso we go to the else condition and print to screen that \"a is greater than b\"." }, { "code": null, "e": 1403, "s": 1359, "text": "You can also have an else without the\nelif:" }, { "code": null, "e": 1499, "s": 1403, "text": "If you have only one statement to execute, you can put it on the same line as the if statement." }, { "code": null, "e": 1522, "s": 1499, "text": "One line if statement:" }, { "code": null, "e": 1633, "s": 1522, "text": "If you have only one statement to execute, one for if, and one for else, you can put it \nall on the same line:" }, { "code": null, "e": 1661, "s": 1633, "text": "One line if else statement:" }, { "code": null, "e": 1738, "s": 1661, "text": "This technique is known as Ternary Operators, or Conditional \n Expressions." }, { "code": null, "e": 1799, "s": 1738, "text": "You can also have multiple else statements on the same line:" }, { "code": null, "e": 1846, "s": 1799, "text": "One line if else statement, with 3 conditions:" }, { "code": null, "e": 1933, "s": 1846, "text": "The and keyword is a logical operator, and \nis used to combine conditional statements:" }, { "code": null, "e": 1995, "s": 1933, "text": "Test if a is greater than\n b, AND if c \n is greater than a:" }, { "code": null, "e": 2081, "s": 1995, "text": "The or keyword is a logical operator, and \nis used to combine conditional statements:" }, { "code": null, "e": 2142, "s": 2081, "text": "Test if a is greater than\n b, OR if a \n is greater than c:" }, { "code": null, "e": 2229, "s": 2142, "text": "You can have if statements inside \nif statements, this is called nested\nif statements." }, { "code": null, "e": 2379, "s": 2229, "text": "if statements cannot be empty, but if you \nfor some reason have an if statement with no content, put in the pass statement to avoid getting an error." }, { "code": null, "e": 2423, "s": 2379, "text": "Print \"Hello World\" if a is greater than b." }, { "code": null, "e": 2467, "s": 2423, "text": "a = 50\nb = 10\n a b\n print(\"Hello World\")\n" }, { "code": null, "e": 2486, "s": 2467, "text": "Start the Exercise" }, { "code": null, "e": 2519, "s": 2486, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2561, "s": 2519, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2668, "s": 2561, "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": 2687, "s": 2668, "text": "[email protected]" } ]
Check if it is possible to make two matrices strictly increasing by swapping corresponding values only in Python
Suppose we have two matrices of size n x m named mat1 and mat2. We have to check where these two matrices are strictly increasing or not by swapping only two elements in different matrices only when they are at position (i, j) in both matrices. So, if the input is like then the output will be True as we can swap (7, 14) and (10, 17) pairs to make them strictly increasing. To solve this, we will follow these steps − row := row count of mat1 col := column count of mat1 for i in range 0 to row - 1, dofor j in range 0 to col - 1, doif mat1[i,j] > mat2[i,j], thenswap mat1[i, j] and mat2[i, j]for i in range 0 to row - 1, dofor j in range 0 to col-2, doif mat1[i, j] >= mat1[i, j + 1] or mat2[i, j] >= mat2[i, j + 1], thenreturn Falsefor i in range 0 to row-2, dofor j in range 0 to col - 1, doif mat1[i, j] >= mat1[i + 1, j] or mat2[i, j] >= mat2[i + 1, j], thenreturn False for j in range 0 to col - 1, doif mat1[i,j] > mat2[i,j], thenswap mat1[i, j] and mat2[i, j] if mat1[i,j] > mat2[i,j], thenswap mat1[i, j] and mat2[i, j] swap mat1[i, j] and mat2[i, j] for i in range 0 to row - 1, dofor j in range 0 to col-2, doif mat1[i, j] >= mat1[i, j + 1] or mat2[i, j] >= mat2[i, j + 1], thenreturn False for j in range 0 to col-2, doif mat1[i, j] >= mat1[i, j + 1] or mat2[i, j] >= mat2[i, j + 1], thenreturn False if mat1[i, j] >= mat1[i, j + 1] or mat2[i, j] >= mat2[i, j + 1], thenreturn False return False for i in range 0 to row-2, dofor j in range 0 to col - 1, doif mat1[i, j] >= mat1[i + 1, j] or mat2[i, j] >= mat2[i + 1, j], thenreturn False for j in range 0 to col - 1, doif mat1[i, j] >= mat1[i + 1, j] or mat2[i, j] >= mat2[i + 1, j], thenreturn False if mat1[i, j] >= mat1[i + 1, j] or mat2[i, j] >= mat2[i + 1, j], thenreturn False return False return True Let us see the following implementation to get better understanding − Live Demo def solve(mat1, mat2): row = len(mat1) col = len(mat1[0]) for i in range(row): for j in range(col): if mat1[i][j] > mat2[i][j]: mat1[i][j], mat2[i][j]= mat2[i][j], mat1[i][j] for i in range(row): for j in range(col-1): if mat1[i][j]>= mat1[i][j + 1] or mat2[i][j]>= mat2[i][j + 1]: return False for i in range(row-1): for j in range(col): if mat1[i][j]>= mat1[i + 1][j] or mat2[i][j]>= mat2[i + 1][j]: return False return True mat1 = [[7, 15], [16, 10]] mat2 = [[14, 9], [8, 17]] print(solve(mat1, mat2)) [[7, 15], [16, 10]], [[14, 9], [8, 17]] True
[ { "code": null, "e": 1307, "s": 1062, "text": "Suppose we have two matrices of size n x m named mat1 and mat2. We have to check where these two matrices are strictly increasing or not by swapping only two elements in different matrices only when they are at position (i, j) in both matrices." }, { "code": null, "e": 1332, "s": 1307, "text": "So, if the input is like" }, { "code": null, "e": 1437, "s": 1332, "text": "then the output will be True as we can swap (7, 14) and (10, 17) pairs to make them strictly increasing." }, { "code": null, "e": 1481, "s": 1437, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1506, "s": 1481, "text": "row := row count of mat1" }, { "code": null, "e": 1534, "s": 1506, "text": "col := column count of mat1" }, { "code": null, "e": 1939, "s": 1534, "text": "for i in range 0 to row - 1, dofor j in range 0 to col - 1, doif mat1[i,j] > mat2[i,j], thenswap mat1[i, j] and mat2[i, j]for i in range 0 to row - 1, dofor j in range 0 to col-2, doif mat1[i, j] >= mat1[i, j + 1] or mat2[i, j] >= mat2[i, j + 1], thenreturn Falsefor i in range 0 to row-2, dofor j in range 0 to col - 1, doif mat1[i, j] >= mat1[i + 1, j] or mat2[i, j] >= mat2[i + 1, j], thenreturn False" }, { "code": null, "e": 2031, "s": 1939, "text": "for j in range 0 to col - 1, doif mat1[i,j] > mat2[i,j], thenswap mat1[i, j] and mat2[i, j]" }, { "code": null, "e": 2092, "s": 2031, "text": "if mat1[i,j] > mat2[i,j], thenswap mat1[i, j] and mat2[i, j]" }, { "code": null, "e": 2123, "s": 2092, "text": "swap mat1[i, j] and mat2[i, j]" }, { "code": null, "e": 2265, "s": 2123, "text": "for i in range 0 to row - 1, dofor j in range 0 to col-2, doif mat1[i, j] >= mat1[i, j + 1] or mat2[i, j] >= mat2[i, j + 1], thenreturn False" }, { "code": null, "e": 2376, "s": 2265, "text": "for j in range 0 to col-2, doif mat1[i, j] >= mat1[i, j + 1] or mat2[i, j] >= mat2[i, j + 1], thenreturn False" }, { "code": null, "e": 2458, "s": 2376, "text": "if mat1[i, j] >= mat1[i, j + 1] or mat2[i, j] >= mat2[i, j + 1], thenreturn False" }, { "code": null, "e": 2471, "s": 2458, "text": "return False" }, { "code": null, "e": 2613, "s": 2471, "text": "for i in range 0 to row-2, dofor j in range 0 to col - 1, doif mat1[i, j] >= mat1[i + 1, j] or mat2[i, j] >= mat2[i + 1, j], thenreturn False" }, { "code": null, "e": 2726, "s": 2613, "text": "for j in range 0 to col - 1, doif mat1[i, j] >= mat1[i + 1, j] or mat2[i, j] >= mat2[i + 1, j], thenreturn False" }, { "code": null, "e": 2808, "s": 2726, "text": "if mat1[i, j] >= mat1[i + 1, j] or mat2[i, j] >= mat2[i + 1, j], thenreturn False" }, { "code": null, "e": 2821, "s": 2808, "text": "return False" }, { "code": null, "e": 2833, "s": 2821, "text": "return True" }, { "code": null, "e": 2903, "s": 2833, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2914, "s": 2903, "text": " Live Demo" }, { "code": null, "e": 3536, "s": 2914, "text": "def solve(mat1, mat2):\n row = len(mat1)\n col = len(mat1[0])\n for i in range(row):\n for j in range(col):\n if mat1[i][j] > mat2[i][j]:\n mat1[i][j], mat2[i][j]= mat2[i][j], mat1[i][j]\n for i in range(row):\n for j in range(col-1):\n if mat1[i][j]>= mat1[i][j + 1] or mat2[i][j]>= mat2[i][j + 1]:\n return False\n for i in range(row-1):\n for j in range(col):\n if mat1[i][j]>= mat1[i + 1][j] or mat2[i][j]>= mat2[i + 1][j]:\n return False\n return True\nmat1 = [[7, 15],\n [16, 10]]\nmat2 = [[14, 9],\n [8, 17]]\nprint(solve(mat1, mat2))" }, { "code": null, "e": 3576, "s": 3536, "text": "[[7, 15],\n[16, 10]],\n[[14, 9],\n[8, 17]]" }, { "code": null, "e": 3581, "s": 3576, "text": "True" } ]
Basic data structures of xarray. How to create DataArray and Dataset in... | by Udi Yosovzon | Towards Data Science
Xarray is a python package for working with labeled multi-dimensional (a.k.a. N-dimensional, ND) arrays, it includes functions for advanced analytics and visualization. Xarray is heavily inspired by pandas and it uses pandas internally. While pandas is a great tool for working with tabular data, it can get a little awkward when data is of higher dimension. Pandas’ main data structures are Series (for 1-dimensional data) and DataFrame (for 2-dimensional data). It used to have Panel (for 3-dimensional data) but it was removed in version 0.25.0. The reader is assumed to be familiar with pandas, if you do not know what pandas is, you should check it out before xarray. In many fields of science, there’s a need to map a data point to various properties (referred to as coordinates), for example, you want to map a certain temperature measurement to latitude, longitude, altitude and time. This is 4 dimensions! In python, the fundamental package for working with ND arrays is NumPy. Xarray has some built-in features that make working with ND arrays easier than NumPy: Instead of axis labels, xarray uses named dimensions, which makes it easy to select data and apply operations over dimensions. NumPy array can only have one data type, while xarray can hold heterogeneous data in an ND array. It also makes NaN handling easier. Keep track of arbitrary metadata on your object with obj.attrs . Xarray has two data structures: DataArray — for a single data variable Dataset — a container for multiple DataArrays (data variables) There’s a distinction between data variables and coordinates, according to CF conventions. Xarray follows these conventions, but it mostly semantic and you don’t have to follow it. I see it like this: a data variable is the data of interest, and a coordinate is a label to describe the data of interest. For example latitude, longitude and time are coordinates while the temperature is a data variable. This is because we are interested in measuring temperatures, all the rest is describing the measurement (the data point). In xarray docs, they say: Coordinates indicate constant/fixed/independent quantities, unlike the varying/measured/dependent quantities that belong in data. Okay, let’s see some code! # customary importsimport numpy as npimport pandas as pdimport xarray as xr First, we’ll create some toy temperature data to play with: We generated an array of random temperature values, along with arrays for the coordinates latitude and longitude (2 dimensions). First, let’s see how we can represent this data in pandas: df = pd.DataFrame({"temperature":temperature, "lat":lat, "lon":lon})df We will create a DataArray from this data, let’s have a look at four ways to do that: from a pandas Series from a pandas DataFrame using the DataArray constructor using the DataArray constructor with projected coordinates We’ll create a pandas Series and then a DataArray. Since we want to represent 2 dimensions in our data, we will create a series with a 2 level multi-index: idx = pd.MultiIndex.from_arrays(arrays=[lat,lon], names=["lat","lon"])s = pd.Series(data=temperature, index=idx)s# use from_series methodda = xr.DataArray.from_series(s)da This is what the data array looks like when printed. We can provide the DataArray constructor with a pandas DataFrame. It will consider the index of the data frame as the first dimension and the columns as the second. If the index or the columns have multiple levels xarray will create nested dimensions. Since we want latitude and longitude as our dimensions, the smartest way to achieve this would be to pivot our data frame using latitude as index and longitude as columns: df_pv = df.pivot(index="lat", columns="lon")# drop first level of columns as it's not necessarydf_pv = df_pv.droplevel(0, axis=1)df_pv With our data pivoted, we can easily create a DataArray by providing the DataArray constructor with our pivoted data frame: da = xr.DataArray(data=df_pv)da So we’ve seen two ways to create a DataArray from pandas objects. Now let’s see how we can create a DataArray manually. Since we want to represent 2 dimensions in our data, the data should be shaped in a 2-dimensional array so we can pass it directly to the DataArray constructor. We’ll use the data from the pivoted data frame, then we’ll need to specify the coordinates and dimensions explicitly: The important thing to notice here is that coordinate arrays must be 1 dimensional and have the length of the dimension they represent. We had a (4,4) shaped array of data, so we supplied the constructor with two coordinate arrays. Each one is 1-dimensional and has a length of 4. We’ll check out one final way to create a DataArray, with projected coordinates. They might be useful in some cases, but they have one disadvantage, which is the coordinates have no clear interpretability. The big advantage of using them is that we can pass to the DataArray constructor arrays of the same shape, for both data and coordinates, without having to think about pivoting our data before. In our case, we have temperature data, and we have two dimensions: latitude and longitude, so we can represent our data in a 2-dimensional array of any shape (it doesn’t have to be pivoted) and then provide the constructor with 2 coordinate arrays of the same shape for latitude and longitude: Below, notice the way the coordinates are specified in the DataArray constructor. It’s a dictionary that its keys are the names of the coordinates, and its values are tuples that their first item is a list of dimensions, and their second item is the coordinate values. da = xr.DataArray(data=temperature, coords={"lat": (["x","y"], lat), "lon": (["x","y"], lon)}, dims=["x","y"])da Notice that it says x and y are dimensions without coordinates. Notice, as well, that there’s no asterisk next to lat and lon because they are non-dimension coordinates. Now let’s create another dimension! Let’s create temperature data for 2 days, not 1 but 2! Like before for every day we need a 2-dimensional (latitude and longitude) array for temperature values. To represent data for 2 days we will want to stack the daily arrays together, resulting in a 3-dimensional array: Now we’ll pass the data to the DataArray constructor, with projected coordinates: da = xr.DataArray(data=temperature_3d, coords={"lat": (["x","y"], lat), "lon": (["x","y"], lon), "day": ["day1","day2"]}, dims=["x","y","day"])da We can also create the same thing using a pandas Series with a 3-level multi-index. To create a Series we will need to flatten the data, which means to make it 1-dimensional: # make data 1-dimensionaltemperature_1d = temperature_3d.flatten("F")lat = lat.flatten()lon = lon.flatten()day = ["day1","day2"] Now we’ll create a Series with a 3-level multi-index : And finally, we’ll create a DataArray using the from_series method: da = xr.DataArray.from_series(s)da Up until this point, we only dealt with temperature data. Let’s add pressure data: Now we’ll create a Dataset (not a DataArray) with temperature and pressure as data variables. With projected coordinates, the data_vars argument and the coords argument both expect a dictionary similar to the coords argument for DataArray: We can also create a DataArray for each data variable and then create a Dataset from the DataArrays. Let’s create two DataArrays, for temperature and pressure, using the from_series method, just like we did with the 3-dimensional case: Now we’ll create a Dataset using these two DataArrays: ds = xr.Dataset(data_vars={"temperature": da_temperature, "pressure": da_pressure})ds This was a quick introduction to xarray data structures. There are many more capabilities to xarray, like indexing, selecting and analyzing data. I won’t cover those here, because I want to keep this tutorial simple. I encourage you to take a look at xarray docs and try to play with it a little. Hope you found this article useful!
[ { "code": null, "e": 720, "s": 171, "text": "Xarray is a python package for working with labeled multi-dimensional (a.k.a. N-dimensional, ND) arrays, it includes functions for advanced analytics and visualization. Xarray is heavily inspired by pandas and it uses pandas internally. While pandas is a great tool for working with tabular data, it can get a little awkward when data is of higher dimension. Pandas’ main data structures are Series (for 1-dimensional data) and DataFrame (for 2-dimensional data). It used to have Panel (for 3-dimensional data) but it was removed in version 0.25.0." }, { "code": null, "e": 844, "s": 720, "text": "The reader is assumed to be familiar with pandas, if you do not know what pandas is, you should check it out before xarray." }, { "code": null, "e": 1086, "s": 844, "text": "In many fields of science, there’s a need to map a data point to various properties (referred to as coordinates), for example, you want to map a certain temperature measurement to latitude, longitude, altitude and time. This is 4 dimensions!" }, { "code": null, "e": 1244, "s": 1086, "text": "In python, the fundamental package for working with ND arrays is NumPy. Xarray has some built-in features that make working with ND arrays easier than NumPy:" }, { "code": null, "e": 1371, "s": 1244, "text": "Instead of axis labels, xarray uses named dimensions, which makes it easy to select data and apply operations over dimensions." }, { "code": null, "e": 1504, "s": 1371, "text": "NumPy array can only have one data type, while xarray can hold heterogeneous data in an ND array. It also makes NaN handling easier." }, { "code": null, "e": 1569, "s": 1504, "text": "Keep track of arbitrary metadata on your object with obj.attrs ." }, { "code": null, "e": 1601, "s": 1569, "text": "Xarray has two data structures:" }, { "code": null, "e": 1640, "s": 1601, "text": "DataArray — for a single data variable" }, { "code": null, "e": 1703, "s": 1640, "text": "Dataset — a container for multiple DataArrays (data variables)" }, { "code": null, "e": 2254, "s": 1703, "text": "There’s a distinction between data variables and coordinates, according to CF conventions. Xarray follows these conventions, but it mostly semantic and you don’t have to follow it. I see it like this: a data variable is the data of interest, and a coordinate is a label to describe the data of interest. For example latitude, longitude and time are coordinates while the temperature is a data variable. This is because we are interested in measuring temperatures, all the rest is describing the measurement (the data point). In xarray docs, they say:" }, { "code": null, "e": 2384, "s": 2254, "text": "Coordinates indicate constant/fixed/independent quantities, unlike the varying/measured/dependent quantities that belong in data." }, { "code": null, "e": 2411, "s": 2384, "text": "Okay, let’s see some code!" }, { "code": null, "e": 2487, "s": 2411, "text": "# customary importsimport numpy as npimport pandas as pdimport xarray as xr" }, { "code": null, "e": 2547, "s": 2487, "text": "First, we’ll create some toy temperature data to play with:" }, { "code": null, "e": 2735, "s": 2547, "text": "We generated an array of random temperature values, along with arrays for the coordinates latitude and longitude (2 dimensions). First, let’s see how we can represent this data in pandas:" }, { "code": null, "e": 2806, "s": 2735, "text": "df = pd.DataFrame({\"temperature\":temperature, \"lat\":lat, \"lon\":lon})df" }, { "code": null, "e": 2892, "s": 2806, "text": "We will create a DataArray from this data, let’s have a look at four ways to do that:" }, { "code": null, "e": 2913, "s": 2892, "text": "from a pandas Series" }, { "code": null, "e": 2937, "s": 2913, "text": "from a pandas DataFrame" }, { "code": null, "e": 2969, "s": 2937, "text": "using the DataArray constructor" }, { "code": null, "e": 3028, "s": 2969, "text": "using the DataArray constructor with projected coordinates" }, { "code": null, "e": 3184, "s": 3028, "text": "We’ll create a pandas Series and then a DataArray. Since we want to represent 2 dimensions in our data, we will create a series with a 2 level multi-index:" }, { "code": null, "e": 3356, "s": 3184, "text": "idx = pd.MultiIndex.from_arrays(arrays=[lat,lon], names=[\"lat\",\"lon\"])s = pd.Series(data=temperature, index=idx)s# use from_series methodda = xr.DataArray.from_series(s)da" }, { "code": null, "e": 3409, "s": 3356, "text": "This is what the data array looks like when printed." }, { "code": null, "e": 3661, "s": 3409, "text": "We can provide the DataArray constructor with a pandas DataFrame. It will consider the index of the data frame as the first dimension and the columns as the second. If the index or the columns have multiple levels xarray will create nested dimensions." }, { "code": null, "e": 3833, "s": 3661, "text": "Since we want latitude and longitude as our dimensions, the smartest way to achieve this would be to pivot our data frame using latitude as index and longitude as columns:" }, { "code": null, "e": 3968, "s": 3833, "text": "df_pv = df.pivot(index=\"lat\", columns=\"lon\")# drop first level of columns as it's not necessarydf_pv = df_pv.droplevel(0, axis=1)df_pv" }, { "code": null, "e": 4092, "s": 3968, "text": "With our data pivoted, we can easily create a DataArray by providing the DataArray constructor with our pivoted data frame:" }, { "code": null, "e": 4124, "s": 4092, "text": "da = xr.DataArray(data=df_pv)da" }, { "code": null, "e": 4405, "s": 4124, "text": "So we’ve seen two ways to create a DataArray from pandas objects. Now let’s see how we can create a DataArray manually. Since we want to represent 2 dimensions in our data, the data should be shaped in a 2-dimensional array so we can pass it directly to the DataArray constructor." }, { "code": null, "e": 4523, "s": 4405, "text": "We’ll use the data from the pivoted data frame, then we’ll need to specify the coordinates and dimensions explicitly:" }, { "code": null, "e": 4804, "s": 4523, "text": "The important thing to notice here is that coordinate arrays must be 1 dimensional and have the length of the dimension they represent. We had a (4,4) shaped array of data, so we supplied the constructor with two coordinate arrays. Each one is 1-dimensional and has a length of 4." }, { "code": null, "e": 5204, "s": 4804, "text": "We’ll check out one final way to create a DataArray, with projected coordinates. They might be useful in some cases, but they have one disadvantage, which is the coordinates have no clear interpretability. The big advantage of using them is that we can pass to the DataArray constructor arrays of the same shape, for both data and coordinates, without having to think about pivoting our data before." }, { "code": null, "e": 5498, "s": 5204, "text": "In our case, we have temperature data, and we have two dimensions: latitude and longitude, so we can represent our data in a 2-dimensional array of any shape (it doesn’t have to be pivoted) and then provide the constructor with 2 coordinate arrays of the same shape for latitude and longitude:" }, { "code": null, "e": 5767, "s": 5498, "text": "Below, notice the way the coordinates are specified in the DataArray constructor. It’s a dictionary that its keys are the names of the coordinates, and its values are tuples that their first item is a list of dimensions, and their second item is the coordinate values." }, { "code": null, "e": 5939, "s": 5767, "text": "da = xr.DataArray(data=temperature, coords={\"lat\": ([\"x\",\"y\"], lat), \"lon\": ([\"x\",\"y\"], lon)}, dims=[\"x\",\"y\"])da" }, { "code": null, "e": 6109, "s": 5939, "text": "Notice that it says x and y are dimensions without coordinates. Notice, as well, that there’s no asterisk next to lat and lon because they are non-dimension coordinates." }, { "code": null, "e": 6200, "s": 6109, "text": "Now let’s create another dimension! Let’s create temperature data for 2 days, not 1 but 2!" }, { "code": null, "e": 6419, "s": 6200, "text": "Like before for every day we need a 2-dimensional (latitude and longitude) array for temperature values. To represent data for 2 days we will want to stack the daily arrays together, resulting in a 3-dimensional array:" }, { "code": null, "e": 6501, "s": 6419, "text": "Now we’ll pass the data to the DataArray constructor, with projected coordinates:" }, { "code": null, "e": 6732, "s": 6501, "text": "da = xr.DataArray(data=temperature_3d, coords={\"lat\": ([\"x\",\"y\"], lat), \"lon\": ([\"x\",\"y\"], lon), \"day\": [\"day1\",\"day2\"]}, dims=[\"x\",\"y\",\"day\"])da" }, { "code": null, "e": 6907, "s": 6732, "text": "We can also create the same thing using a pandas Series with a 3-level multi-index. To create a Series we will need to flatten the data, which means to make it 1-dimensional:" }, { "code": null, "e": 7036, "s": 6907, "text": "# make data 1-dimensionaltemperature_1d = temperature_3d.flatten(\"F\")lat = lat.flatten()lon = lon.flatten()day = [\"day1\",\"day2\"]" }, { "code": null, "e": 7091, "s": 7036, "text": "Now we’ll create a Series with a 3-level multi-index :" }, { "code": null, "e": 7159, "s": 7091, "text": "And finally, we’ll create a DataArray using the from_series method:" }, { "code": null, "e": 7194, "s": 7159, "text": "da = xr.DataArray.from_series(s)da" }, { "code": null, "e": 7277, "s": 7194, "text": "Up until this point, we only dealt with temperature data. Let’s add pressure data:" }, { "code": null, "e": 7517, "s": 7277, "text": "Now we’ll create a Dataset (not a DataArray) with temperature and pressure as data variables. With projected coordinates, the data_vars argument and the coords argument both expect a dictionary similar to the coords argument for DataArray:" }, { "code": null, "e": 7753, "s": 7517, "text": "We can also create a DataArray for each data variable and then create a Dataset from the DataArrays. Let’s create two DataArrays, for temperature and pressure, using the from_series method, just like we did with the 3-dimensional case:" }, { "code": null, "e": 7808, "s": 7753, "text": "Now we’ll create a Dataset using these two DataArrays:" }, { "code": null, "e": 7894, "s": 7808, "text": "ds = xr.Dataset(data_vars={\"temperature\": da_temperature, \"pressure\": da_pressure})ds" } ]
Boost your efficiency and process Excel-files with Python | by Benedikt Droste | Towards Data Science
If you work with data, you will get in touch with excel. Even if you don ́t use it by yourself, your clients or colleagues will use it. Excel is great for what it is made: table calculation for smaller data sets. But I always hated the kind of excel sheets with one million rows and hundreds of columns. This workbooks are slow and tend to crash after some calculation. So I started to use python for handling large excel files which offer another big advantage: You create code which is reproducible and provide documentation as well. Let ́s jump in! The file we want to process contains nearly 1 million rows and 16 columns: Python provides read_excel() to read Excel-files as DataFrame: import pandas as pdimport numpy as npdf = pd.read_excel(...\\Excel-Tutorial.xlsx') As you can see the data looks clean so far but our column header seems to be wrong. A lot of excel maps contain headlines or other information to guide the reader. We can skip this parts and define a header row: df = pd.read_excel('...\\Excel-Tutorial.xlsx', header=[1]).reset_index() The argument header=[1] specifies that we want to use the second row in the excel sheet as header. All previous rows are skipped. A typical question of the marketing department could be how much sales we had for the different countries in each year: We finished this calculation in 86 ms. One big advantage of processing Excel-files with Python is that any kind of calculation is much faster done as in Excel itself. The more complex the operations, the greater the speed advantages. Another requirement could be that the sales department needs the data for each country grouped by years and categories. Since they want to supply the data to the national markets, we have to save the calculations in different worksheets: In a next step, we want to save our files as Excel again to supply it to the sales and marketing department. We will create a pd.ExcelWriter object and create the different worksheets: Easy, isn ́t it? Let ́s have a look at the new created workbook: As you can see our DataFrames were saved correctly to the specified worksheets. After we sent our great result to both departments, we receive a mail on the next day: They ask for some formatting and visualization. Since we have to transform this kind of data every month, we decide to perform the tasks in Python as well. To add formatting and visualization, we have to create a writer object again: As you can see the first part of the code is the same as in the first example. We create a writer object. xlsxwriter gives us access to Excel-features such as charts and formatting. To gain access to this features, we need to get the workbook object workbook = writer.book and the worksheet object worksheet = writer.sheet['Sales_Sums'] . In this example, we will perform the modifications on our first sheet. We add a chart, specify the range for the data ( =Sales_Sums!$B$2:$B$7' ) and add it to our worksheet in cell A9 . In the same way we add formatting for our sales data. We add a 3 color scale on the range B2:B7 to visually highlight low or high values. We also adjust the width of the first and second column worksheet.set_column(0,1,30) . We also format the column header for our sales data and rename it to 2019 Sales Data . In a last step, we save out the file: This result is much better and provides a big advantage compared to Excel. We can reproduce exactly the same file next month with one click. Python is great for processing Excel-files. You can handle large files much easier, you create reproducible code and you provide a documentation for your colleagues. We also saw the we have easily access to advanced features of Python. You could automate your whole reporting process. Creating charts: pandas-xlsxwriter-charts.readthedocs.io Excel reports with Pandas pivots: pbpython.com Formatting Excel-files with Python: xlsxwriter.readthedocs.io If you enjoy Medium and Towards Data Science and didn’t sign up yet, feel free to use my referral link to join the community.
[ { "code": null, "e": 723, "s": 171, "text": "If you work with data, you will get in touch with excel. Even if you don ́t use it by yourself, your clients or colleagues will use it. Excel is great for what it is made: table calculation for smaller data sets. But I always hated the kind of excel sheets with one million rows and hundreds of columns. This workbooks are slow and tend to crash after some calculation. So I started to use python for handling large excel files which offer another big advantage: You create code which is reproducible and provide documentation as well. Let ́s jump in!" }, { "code": null, "e": 798, "s": 723, "text": "The file we want to process contains nearly 1 million rows and 16 columns:" }, { "code": null, "e": 861, "s": 798, "text": "Python provides read_excel() to read Excel-files as DataFrame:" }, { "code": null, "e": 944, "s": 861, "text": "import pandas as pdimport numpy as npdf = pd.read_excel(...\\\\Excel-Tutorial.xlsx')" }, { "code": null, "e": 1156, "s": 944, "text": "As you can see the data looks clean so far but our column header seems to be wrong. A lot of excel maps contain headlines or other information to guide the reader. We can skip this parts and define a header row:" }, { "code": null, "e": 1229, "s": 1156, "text": "df = pd.read_excel('...\\\\Excel-Tutorial.xlsx', header=[1]).reset_index()" }, { "code": null, "e": 1359, "s": 1229, "text": "The argument header=[1] specifies that we want to use the second row in the excel sheet as header. All previous rows are skipped." }, { "code": null, "e": 1479, "s": 1359, "text": "A typical question of the marketing department could be how much sales we had for the different countries in each year:" }, { "code": null, "e": 1713, "s": 1479, "text": "We finished this calculation in 86 ms. One big advantage of processing Excel-files with Python is that any kind of calculation is much faster done as in Excel itself. The more complex the operations, the greater the speed advantages." }, { "code": null, "e": 1951, "s": 1713, "text": "Another requirement could be that the sales department needs the data for each country grouped by years and categories. Since they want to supply the data to the national markets, we have to save the calculations in different worksheets:" }, { "code": null, "e": 2136, "s": 1951, "text": "In a next step, we want to save our files as Excel again to supply it to the sales and marketing department. We will create a pd.ExcelWriter object and create the different worksheets:" }, { "code": null, "e": 2201, "s": 2136, "text": "Easy, isn ́t it? Let ́s have a look at the new created workbook:" }, { "code": null, "e": 2524, "s": 2201, "text": "As you can see our DataFrames were saved correctly to the specified worksheets. After we sent our great result to both departments, we receive a mail on the next day: They ask for some formatting and visualization. Since we have to transform this kind of data every month, we decide to perform the tasks in Python as well." }, { "code": null, "e": 2602, "s": 2524, "text": "To add formatting and visualization, we have to create a writer object again:" }, { "code": null, "e": 3127, "s": 2602, "text": "As you can see the first part of the code is the same as in the first example. We create a writer object. xlsxwriter gives us access to Excel-features such as charts and formatting. To gain access to this features, we need to get the workbook object workbook = writer.book and the worksheet object worksheet = writer.sheet['Sales_Sums'] . In this example, we will perform the modifications on our first sheet. We add a chart, specify the range for the data ( =Sales_Sums!$B$2:$B$7' ) and add it to our worksheet in cell A9 ." }, { "code": null, "e": 3477, "s": 3127, "text": "In the same way we add formatting for our sales data. We add a 3 color scale on the range B2:B7 to visually highlight low or high values. We also adjust the width of the first and second column worksheet.set_column(0,1,30) . We also format the column header for our sales data and rename it to 2019 Sales Data . In a last step, we save out the file:" }, { "code": null, "e": 3618, "s": 3477, "text": "This result is much better and provides a big advantage compared to Excel. We can reproduce exactly the same file next month with one click." }, { "code": null, "e": 3903, "s": 3618, "text": "Python is great for processing Excel-files. You can handle large files much easier, you create reproducible code and you provide a documentation for your colleagues. We also saw the we have easily access to advanced features of Python. You could automate your whole reporting process." }, { "code": null, "e": 3920, "s": 3903, "text": "Creating charts:" }, { "code": null, "e": 3960, "s": 3920, "text": "pandas-xlsxwriter-charts.readthedocs.io" }, { "code": null, "e": 3994, "s": 3960, "text": "Excel reports with Pandas pivots:" }, { "code": null, "e": 4007, "s": 3994, "text": "pbpython.com" }, { "code": null, "e": 4043, "s": 4007, "text": "Formatting Excel-files with Python:" }, { "code": null, "e": 4069, "s": 4043, "text": "xlsxwriter.readthedocs.io" } ]
How to Improve your Supply Chain with Deep Reinforcement Learning | by Christian Hubbs | Towards Data Science
What has set Amazon apart from the competition in online retail? Their supply chain. In fact, this has long been one of the greatest strengths of one of their chief competitors, Walmart. Supply chains are highly complex systems consisting of hundreds if not thousands of manufacturers and logistics carriers around the world who combine resources to create the products we use and consume every day. To track all of the inputs to a single, simple product would be staggering. Yet supply chain organizations inside vertically integrated corporations are tasked with managing inputs from raw materials, to manufacturing, warehousing, and distribution to customers. The companies that do this best cut down on waste from excess storage, to unneeded transportation costs, and lost time to get products and materials to later stages in the system. Optimizing these systems is a key component in businesses as dissimilar as Apple and Saudi Aramco. A lot of time and effort has been put into building effective supply chain optimization models, but due to their size and complexity, they can be difficult to build and manage. With advances in machine learning, particularly reinforcement learning, we can train a machine learning model to make these decisions for us, and in many cases, do so better than traditional approaches! We train a deep reinforcement learning model using Ray and or-gym to optimize a multi-echelon inventory management model and benchmark it against a derivative free optimization model using Powell’s Method. In our example, we’re going to work with a multi-echelon supply chain model with lead times. This means that we have different stages of our supply chain that we need to make decisions for, and each decision that we make at different levels are going to affect decisions downstream. In our case, we have M stages going back to the producer of our raw materials all the way to our customers. Each stage along the way has a different lead time, or time it takes for the output of one stage to arrive and become the input for the next stage in the chain. This may be 5 days, 10 days, whatever. The longer these lead times become, the earlier you need to anticipate customer orders and demand to ensure you don’t stock out or lose sales! The OR-Gym library has a few multi-echelon supply chain models ready to go to simulate this structure. For this, we’ll use the InvManagement-v1 environment, which has the structure shown above, but results in lost sales if you don't have sufficient inventory to meet customer demand. If you haven’t already, go ahead and install the package with: pip install or-gym Once installed, we can set up our environment with: env = or_gym.make('InvManagement-v1') This is a four-echelon supply chain by default. The actions determine how much material to order from the echelon above at each time step. The orders quantities are limited by the capacity of the supplier and their current inventory. So, if you order 150 widgets from a supplier that has a shipment capacity of 100 widgets and only has 90 widgets on hand, you’re going to only get 90 sent. Each echelon has its own costs structure, pricing, and lead times. The last echelon (Stage 3 in this case) provides raw materials, and we don’t have any inventory constraints on this stage, assuming that the mine, oil well, forest — or whatever produces your raw material inputs — is large enough that this isn’t a constraint we need to concern ourselves with. As with all or-gym environments, if these settings don't suit you, simply pass an environment configuration dictionary to the make function to customize your supply chain accordingly (an example is given here). To train your environment, we’re going to leverage the Ray library to speed up our training, so go ahead and import your packages. import or_gymfrom or_gym.utils import create_envimport rayfrom ray.rllib import agentsfrom ray import tune To get started, we’re going to need a brief registration function to ensure that Ray knows about the environment we want to run. We can register that with the register_env function shown below. def register_env(env_name, env_config={}): env = create_env(env_name) tune.register_env(env_name, lambda env_name: env(env_name, env_config=env_config)) From here, we can set up our RL configuration and everything we need to train the model. # Environment and RL Configuration Settingsenv_name = 'InvManagement-v1'env_config = {} # Change environment parameters hererl_config = dict( env=env_name, num_workers=2, env_config=env_config, model=dict( vf_share_layers=False, fcnet_activation='elu', fcnet_hiddens=[256, 256] ), lr=1e-5)# Register environmentregister_env(env_name, env_config) The rl_config dictionary is where you can set all of the relevant hyperparameters or set your system to run on a GPU. Here, we're just going to use 2 workers for parallelization, and train a two-layer network with an ELU activation function. Additionally, if you're going to use tune for hyperparameter tuning, then you can use tools like tune.gridsearch() to systematically update learning rates, change the network, or whatever you like. Once your happy with that, go head and choose your algorithm and get to training! Below, I just use the PPO algorithm because I find it trains well on most environments. # Initialize Ray and Build Agentray.init(ignore_reinit_error=True)agent = agents.ppo.PPOTrainer(env=env_name, config=rl_config)results = []for i in range(500): res = agent.train() results.append(res) if (i+1) % 5 == 0: print('\rIter: {}\tReward: {:.2f}'.format( i+1, res['episode_reward_mean']), end='')ray.shutdown() The code above will initialize ray, then build the agent according to the configuration you specified previously. If you're happy with that, then let it run for a bit and see how it does! One thing to note with this environment: if the learning rate is too high, the policy function will begin to diverge such that the loss becomes astronomically large. At that point, you’ll wind up getting an error, typically stemming from Ray’s default pre-processor with state showing bizarre values because the actions being given by the network are all nan. This is easy to fix by bringing the learning rate down a bit and trying again. Let’s take a look at the performance. import numpy as npimport matplotlib.pyplot as pltfrom matplotlib import gridspec# Unpack values from each iterationrewards = np.hstack([i['hist_stats']['episode_reward'] for i in results])pol_loss = [ i['info']['learner']['default_policy']['policy_loss'] for i in results]vf_loss = [ i['info']['learner']['default_policy']['vf_loss'] for i in results]p = 100mean_rewards = np.array([np.mean(rewards[i-p:i+1]) if i >= p else np.mean(rewards[:i+1]) for i, _ in enumerate(rewards)])std_rewards = np.array([np.std(rewards[i-p:i+1]) if i >= p else np.std(rewards[:i+1]) for i, _ in enumerate(rewards)])fig = plt.figure(constrained_layout=True, figsize=(20, 10))gs = fig.add_gridspec(2, 4)ax0 = fig.add_subplot(gs[:, :-2])ax0.fill_between(np.arange(len(mean_rewards)), mean_rewards - std_rewards, mean_rewards + std_rewards, label='Standard Deviation', alpha=0.3)ax0.plot(mean_rewards, label='Mean Rewards')ax0.set_ylabel('Rewards')ax0.set_xlabel('Episode')ax0.set_title('Training Rewards')ax0.legend()ax1 = fig.add_subplot(gs[0, 2:])ax1.plot(pol_loss)ax1.set_ylabel('Loss')ax1.set_xlabel('Iteration')ax1.set_title('Policy Loss')ax2 = fig.add_subplot(gs[1, 2:])ax2.plot(vf_loss)ax2.set_ylabel('Loss')ax2.set_xlabel('Iteration')ax2.set_title('Value Function Loss')plt.show() It looks like our agent learned a decent policy! One of the difficulties of deep reinforcement learning for these classic, operations research problems is the lack of optimality guarantees. In other words, we can look at that training curve above and see that it is learning a better and better policy — and it seems to be converging on a policy — but we don’t know how good that policy is. Could we do better? Should we invest more time (and money) into hyperparameter tuning? To answer this, we need to turn to some different methods and develop a benchmark. A good way to benchmark an RL model is with derivative free optimization (DFO). Like RL, DFO treats the system as a black-box model providing inputs and getting some feedback in return to try again as it seeks the optimal value. Unlike RL, DFO has no concept of a state. This means that we will try to find a fixed re-order policy to bring inventory up to a certain level to balance holding costs and profit from sales. For example, if the policy at stage 0 is to re-order up to 10 widgets, and the currently, we have 4 widgets, then the policy states we’re going to re-order 6. In the RL case, it would take into account the current pipeline and all of the other information that we provide into the state. So RL is more adaptive and ought to outperform a straightforward DFO implementation. If it doesn’t, then we know we need to go back to the drawing board. While it may sound simplistic, this fixed re-order policy isn’t unusual in industrial applications, partly because real supply chains consist of many more variables and interrelated decisions than we’re modeling here. So a fixed policy is tractable and something that supply chain professionals can easily work with. There are a lot of different algorithms and solvers out there for DFO. For our purposes, we’re going to leverage Scipy’s optimize library to implement Powell's Method. We won't get into the details here, but this is a way to quickly find minima on functions and can be used for discrete optimization - like we have here. from scipy.optimize import minimize Because we’re going to be working with a fixed re-order policy, we need a quick function to translate inventory levels into actions to evaluate. def base_stock_policy(policy, env): ''' Implements a re-order up-to policy. This means that for each node in the network, if the inventory at that node falls below the level denoted by the policy, we will re-order inventory to bring it to the policy level. For example, policy at a node is 10, current inventory is 5: the action is to order 5 units. ''' assert len(policy) == len(env.init_inv), ( 'Policy should match number of nodes in network' + '({}, {}).'.format( len(policy), len(env.init_inv))) # Get echelon inventory levels if env.period == 0: inv_ech = np.cumsum(env.I[env.period] + env.T[env.period]) else: inv_ech = np.cumsum(env.I[env.period] + env.T[env.period] - env.B[env.period-1, :-1]) # Get unconstrained actions unc_actions = policy - inv_ech unc_actions = np.where(unc_actions>0, unc_actions, 0) # Ensure that actions can be fulfilled by checking # constraints inv_const = np.hstack([env.I[env.period, 1:], np.Inf]) actions = np.minimum(env.c, np.minimum(unc_actions, inv_const)) return actions The base_stock_policy function takes the policy levels we supply and calculates the difference between the level and the inventory as described above. One thing to note, when we calculate the inventory level, we include all of the inventory in transit to the stage as well (given in env.T). For example, if the current inventory on hand for stage 0 is 100, and there is a lead time of 5 days between stage 0 and stage 1, then we take all of those orders for the past 5 days into account as well. So, if stage 0 ordered 10 units each day, then the inventory at this echelon would be 150. This makes policy levels greater than capacity meaningful because we're looking at more than just the inventory in our warehouse today, but looking at everything in transit too. Our DFO method needs to make function evaluation calls to see how the selected variables perform. In our case, we have an environment to evaluate, so we need a function that will run an episode of our environment and return the appropriate results. def dfo_func(policy, env, *args): ''' Runs an episode based on current base-stock model settings. This allows us to use our environment for the DFO optimizer. ''' env.reset() # Ensure env is fresh rewards = [] done = False while not done: action = base_stock_policy(policy, env) state, reward, done, _ = env.step(action) rewards.append(reward) if done: break rewards = np.array(rewards) prob = env.demand_dist.pmf(env.D, **env.dist_param) # Return negative of expected profit return -1 / env.num_periods * np.sum(prob * rewards) Rather than return the sum of the rewards, we’re returning the negative expectation of our rewards. The reason for the negative is the Scipy function we’re using seeks to minimize whereas our environment is designed to maximize the reward, so we invert this to ensure everything is pointing in the right direction. We calculate the expected rewards by multiplying by the probability of our demand based on the distribution. We could take more samples to estimate the distribution and calculate our expectation that way (and for many real-world applications, this would be required), but here, we have access to the true distribution so we can use that to reduce our computational burden. Finally, we’re ready to optimize. The following function will build an environment based on your configuration settings, take our dfo_func to evaluate, and apply Powell's Method to the problem. It will return our policy and ensure that our answer contains only positive integers (e.g. we can't order half a widget or a negative number of widgets). def optimize_inventory_policy(env_name, fun, init_policy=None, env_config={}, method='Powell'): env = or_gym.make(env_name, env_config=env_config) if init_policy is None: init_policy = np.ones(env.num_stages-1) # Optimize policy out = minimize(fun=fun, x0=init_policy, args=env, method=method) policy = out.x.copy() # Policy must be positive integer policy = np.round(np.maximum(policy, 0), 0).astype(int) return policy, out Now it’s time to put it all together. policy, out = optimize_inventory_policy('InvManagement-v1', dfo_func)print("Re-order levels: {}".format(policy))print("DFO Info:\n{}".format(out))Re-order levels: [540 216 81]DFO Info: direc: array([[ 0. , 0. , 1. ], [ 0. , 1. , 0. ], [206.39353826, 81.74560612, 28.78995703]]) fun: -0.9450780368543933 message: 'Optimization terminated successfully.' nfev: 212 nit: 5 status: 0 success: True x: array([539.7995151 , 216.38046861, 80.66902905]) Our DFO model found a fixed-stock policy with re-order levels at 540 for stage 0, 216 for stage 1, and 81 for stage 2. It did this with only 212 function evaluations, i.e. it simulated 212 episodes to find the optimal value. We can run then feed this policy into our environment, say 1,000 times, to generate some statistics and compare it to our RL solution. env = or_gym.make(env_name, env_config=env_config)eps = 1000rewards = []for i in range(eps): env.reset() reward = 0 while True: action = base_stock_policy(policy, eenv) s, r, done, _ = env.step(action) reward += r if done: rewards.append(reward) break Before we get into the reward comparisons, note that these are not perfect, 1:1 comparisons. As mentioned before, DFO yields us a fixed policy whereas RL has a more flexible, dynamic policy that changes based on state information. Our DFO approach was also given some information in terms of probabilities of demand to calculate the expectation on, RL had to infer that from additional sampling. So while RL learned from nearly ~65k episodes and DFO only had to make 212 function calls, they aren’t exactly comparable. Considering that to enumerate every meaningful fixed policy once would require ~200 million episodes, then RL doesn’t look so sample inefficient given its task. So, how do these stack up? What we can see above is that RL does indeed outperform our DFO policy by 11% on average (460 to 414). The RL model overtook the DFO policy after ~15k episodes and improved steadily after that. There is some higher variance with the RL policy however, with a few terrible episodes thrown in to the mix. All things considered, we did get stronger results overall from the RL approach, as expected. In this case, neither method was very difficult to implement nor computationally intensive. I forgot to change my rl_config settings to run on my GPU and it still only took about 25 minutes to train on my laptop while the DFO model took ~2 seconds to run. More complex models may not be so friendly in either case. Another thing to note, both methods can be very sensitive to initial conditions and neither are guaranteed to find the optimum policy in every case. If you have a problem you’d like to apply RL to, maybe use a simple DFO solver first, try a few initial conditions to get a feel for the problem, then spin up the full, RL model. You may find that the DFO policy is sufficient for your task. Hopefully this gave a good overview of how to use these methods and the or-gym library. Leave feedback or questions if you have any!
[ { "code": null, "e": 358, "s": 171, "text": "What has set Amazon apart from the competition in online retail? Their supply chain. In fact, this has long been one of the greatest strengths of one of their chief competitors, Walmart." }, { "code": null, "e": 1113, "s": 358, "text": "Supply chains are highly complex systems consisting of hundreds if not thousands of manufacturers and logistics carriers around the world who combine resources to create the products we use and consume every day. To track all of the inputs to a single, simple product would be staggering. Yet supply chain organizations inside vertically integrated corporations are tasked with managing inputs from raw materials, to manufacturing, warehousing, and distribution to customers. The companies that do this best cut down on waste from excess storage, to unneeded transportation costs, and lost time to get products and materials to later stages in the system. Optimizing these systems is a key component in businesses as dissimilar as Apple and Saudi Aramco." }, { "code": null, "e": 1493, "s": 1113, "text": "A lot of time and effort has been put into building effective supply chain optimization models, but due to their size and complexity, they can be difficult to build and manage. With advances in machine learning, particularly reinforcement learning, we can train a machine learning model to make these decisions for us, and in many cases, do so better than traditional approaches!" }, { "code": null, "e": 1699, "s": 1493, "text": "We train a deep reinforcement learning model using Ray and or-gym to optimize a multi-echelon inventory management model and benchmark it against a derivative free optimization model using Powell’s Method." }, { "code": null, "e": 2433, "s": 1699, "text": "In our example, we’re going to work with a multi-echelon supply chain model with lead times. This means that we have different stages of our supply chain that we need to make decisions for, and each decision that we make at different levels are going to affect decisions downstream. In our case, we have M stages going back to the producer of our raw materials all the way to our customers. Each stage along the way has a different lead time, or time it takes for the output of one stage to arrive and become the input for the next stage in the chain. This may be 5 days, 10 days, whatever. The longer these lead times become, the earlier you need to anticipate customer orders and demand to ensure you don’t stock out or lose sales!" }, { "code": null, "e": 2717, "s": 2433, "text": "The OR-Gym library has a few multi-echelon supply chain models ready to go to simulate this structure. For this, we’ll use the InvManagement-v1 environment, which has the structure shown above, but results in lost sales if you don't have sufficient inventory to meet customer demand." }, { "code": null, "e": 2780, "s": 2717, "text": "If you haven’t already, go ahead and install the package with:" }, { "code": null, "e": 2799, "s": 2780, "text": "pip install or-gym" }, { "code": null, "e": 2851, "s": 2799, "text": "Once installed, we can set up our environment with:" }, { "code": null, "e": 2889, "s": 2851, "text": "env = or_gym.make('InvManagement-v1')" }, { "code": null, "e": 3279, "s": 2889, "text": "This is a four-echelon supply chain by default. The actions determine how much material to order from the echelon above at each time step. The orders quantities are limited by the capacity of the supplier and their current inventory. So, if you order 150 widgets from a supplier that has a shipment capacity of 100 widgets and only has 90 widgets on hand, you’re going to only get 90 sent." }, { "code": null, "e": 3640, "s": 3279, "text": "Each echelon has its own costs structure, pricing, and lead times. The last echelon (Stage 3 in this case) provides raw materials, and we don’t have any inventory constraints on this stage, assuming that the mine, oil well, forest — or whatever produces your raw material inputs — is large enough that this isn’t a constraint we need to concern ourselves with." }, { "code": null, "e": 3851, "s": 3640, "text": "As with all or-gym environments, if these settings don't suit you, simply pass an environment configuration dictionary to the make function to customize your supply chain accordingly (an example is given here)." }, { "code": null, "e": 3982, "s": 3851, "text": "To train your environment, we’re going to leverage the Ray library to speed up our training, so go ahead and import your packages." }, { "code": null, "e": 4089, "s": 3982, "text": "import or_gymfrom or_gym.utils import create_envimport rayfrom ray.rllib import agentsfrom ray import tune" }, { "code": null, "e": 4283, "s": 4089, "text": "To get started, we’re going to need a brief registration function to ensure that Ray knows about the environment we want to run. We can register that with the register_env function shown below." }, { "code": null, "e": 4461, "s": 4283, "text": "def register_env(env_name, env_config={}): env = create_env(env_name) tune.register_env(env_name, lambda env_name: env(env_name, env_config=env_config))" }, { "code": null, "e": 4550, "s": 4461, "text": "From here, we can set up our RL configuration and everything we need to train the model." }, { "code": null, "e": 4935, "s": 4550, "text": "# Environment and RL Configuration Settingsenv_name = 'InvManagement-v1'env_config = {} # Change environment parameters hererl_config = dict( env=env_name, num_workers=2, env_config=env_config, model=dict( vf_share_layers=False, fcnet_activation='elu', fcnet_hiddens=[256, 256] ), lr=1e-5)# Register environmentregister_env(env_name, env_config)" }, { "code": null, "e": 5375, "s": 4935, "text": "The rl_config dictionary is where you can set all of the relevant hyperparameters or set your system to run on a GPU. Here, we're just going to use 2 workers for parallelization, and train a two-layer network with an ELU activation function. Additionally, if you're going to use tune for hyperparameter tuning, then you can use tools like tune.gridsearch() to systematically update learning rates, change the network, or whatever you like." }, { "code": null, "e": 5545, "s": 5375, "text": "Once your happy with that, go head and choose your algorithm and get to training! Below, I just use the PPO algorithm because I find it trains well on most environments." }, { "code": null, "e": 5897, "s": 5545, "text": "# Initialize Ray and Build Agentray.init(ignore_reinit_error=True)agent = agents.ppo.PPOTrainer(env=env_name, config=rl_config)results = []for i in range(500): res = agent.train() results.append(res) if (i+1) % 5 == 0: print('\\rIter: {}\\tReward: {:.2f}'.format( i+1, res['episode_reward_mean']), end='')ray.shutdown()" }, { "code": null, "e": 6085, "s": 5897, "text": "The code above will initialize ray, then build the agent according to the configuration you specified previously. If you're happy with that, then let it run for a bit and see how it does!" }, { "code": null, "e": 6524, "s": 6085, "text": "One thing to note with this environment: if the learning rate is too high, the policy function will begin to diverge such that the loss becomes astronomically large. At that point, you’ll wind up getting an error, typically stemming from Ray’s default pre-processor with state showing bizarre values because the actions being given by the network are all nan. This is easy to fix by bringing the learning rate down a bit and trying again." }, { "code": null, "e": 6562, "s": 6524, "text": "Let’s take a look at the performance." }, { "code": null, "e": 7959, "s": 6562, "text": "import numpy as npimport matplotlib.pyplot as pltfrom matplotlib import gridspec# Unpack values from each iterationrewards = np.hstack([i['hist_stats']['episode_reward'] for i in results])pol_loss = [ i['info']['learner']['default_policy']['policy_loss'] for i in results]vf_loss = [ i['info']['learner']['default_policy']['vf_loss'] for i in results]p = 100mean_rewards = np.array([np.mean(rewards[i-p:i+1]) if i >= p else np.mean(rewards[:i+1]) for i, _ in enumerate(rewards)])std_rewards = np.array([np.std(rewards[i-p:i+1]) if i >= p else np.std(rewards[:i+1]) for i, _ in enumerate(rewards)])fig = plt.figure(constrained_layout=True, figsize=(20, 10))gs = fig.add_gridspec(2, 4)ax0 = fig.add_subplot(gs[:, :-2])ax0.fill_between(np.arange(len(mean_rewards)), mean_rewards - std_rewards, mean_rewards + std_rewards, label='Standard Deviation', alpha=0.3)ax0.plot(mean_rewards, label='Mean Rewards')ax0.set_ylabel('Rewards')ax0.set_xlabel('Episode')ax0.set_title('Training Rewards')ax0.legend()ax1 = fig.add_subplot(gs[0, 2:])ax1.plot(pol_loss)ax1.set_ylabel('Loss')ax1.set_xlabel('Iteration')ax1.set_title('Policy Loss')ax2 = fig.add_subplot(gs[1, 2:])ax2.plot(vf_loss)ax2.set_ylabel('Loss')ax2.set_xlabel('Iteration')ax2.set_title('Value Function Loss')plt.show()" }, { "code": null, "e": 8008, "s": 7959, "text": "It looks like our agent learned a decent policy!" }, { "code": null, "e": 8520, "s": 8008, "text": "One of the difficulties of deep reinforcement learning for these classic, operations research problems is the lack of optimality guarantees. In other words, we can look at that training curve above and see that it is learning a better and better policy — and it seems to be converging on a policy — but we don’t know how good that policy is. Could we do better? Should we invest more time (and money) into hyperparameter tuning? To answer this, we need to turn to some different methods and develop a benchmark." }, { "code": null, "e": 8749, "s": 8520, "text": "A good way to benchmark an RL model is with derivative free optimization (DFO). Like RL, DFO treats the system as a black-box model providing inputs and getting some feedback in return to try again as it seeks the optimal value." }, { "code": null, "e": 9382, "s": 8749, "text": "Unlike RL, DFO has no concept of a state. This means that we will try to find a fixed re-order policy to bring inventory up to a certain level to balance holding costs and profit from sales. For example, if the policy at stage 0 is to re-order up to 10 widgets, and the currently, we have 4 widgets, then the policy states we’re going to re-order 6. In the RL case, it would take into account the current pipeline and all of the other information that we provide into the state. So RL is more adaptive and ought to outperform a straightforward DFO implementation. If it doesn’t, then we know we need to go back to the drawing board." }, { "code": null, "e": 9699, "s": 9382, "text": "While it may sound simplistic, this fixed re-order policy isn’t unusual in industrial applications, partly because real supply chains consist of many more variables and interrelated decisions than we’re modeling here. So a fixed policy is tractable and something that supply chain professionals can easily work with." }, { "code": null, "e": 10020, "s": 9699, "text": "There are a lot of different algorithms and solvers out there for DFO. For our purposes, we’re going to leverage Scipy’s optimize library to implement Powell's Method. We won't get into the details here, but this is a way to quickly find minima on functions and can be used for discrete optimization - like we have here." }, { "code": null, "e": 10056, "s": 10020, "text": "from scipy.optimize import minimize" }, { "code": null, "e": 10201, "s": 10056, "text": "Because we’re going to be working with a fixed re-order policy, we need a quick function to translate inventory levels into actions to evaluate." }, { "code": null, "e": 11376, "s": 10201, "text": "def base_stock_policy(policy, env): ''' Implements a re-order up-to policy. This means that for each node in the network, if the inventory at that node falls below the level denoted by the policy, we will re-order inventory to bring it to the policy level. For example, policy at a node is 10, current inventory is 5: the action is to order 5 units. ''' assert len(policy) == len(env.init_inv), ( 'Policy should match number of nodes in network' + '({}, {}).'.format( len(policy), len(env.init_inv))) # Get echelon inventory levels if env.period == 0: inv_ech = np.cumsum(env.I[env.period] + env.T[env.period]) else: inv_ech = np.cumsum(env.I[env.period] + env.T[env.period] - env.B[env.period-1, :-1]) # Get unconstrained actions unc_actions = policy - inv_ech unc_actions = np.where(unc_actions>0, unc_actions, 0) # Ensure that actions can be fulfilled by checking # constraints inv_const = np.hstack([env.I[env.period, 1:], np.Inf]) actions = np.minimum(env.c, np.minimum(unc_actions, inv_const)) return actions" }, { "code": null, "e": 12141, "s": 11376, "text": "The base_stock_policy function takes the policy levels we supply and calculates the difference between the level and the inventory as described above. One thing to note, when we calculate the inventory level, we include all of the inventory in transit to the stage as well (given in env.T). For example, if the current inventory on hand for stage 0 is 100, and there is a lead time of 5 days between stage 0 and stage 1, then we take all of those orders for the past 5 days into account as well. So, if stage 0 ordered 10 units each day, then the inventory at this echelon would be 150. This makes policy levels greater than capacity meaningful because we're looking at more than just the inventory in our warehouse today, but looking at everything in transit too." }, { "code": null, "e": 12390, "s": 12141, "text": "Our DFO method needs to make function evaluation calls to see how the selected variables perform. In our case, we have an environment to evaluate, so we need a function that will run an episode of our environment and return the appropriate results." }, { "code": null, "e": 13015, "s": 12390, "text": "def dfo_func(policy, env, *args): ''' Runs an episode based on current base-stock model settings. This allows us to use our environment for the DFO optimizer. ''' env.reset() # Ensure env is fresh rewards = [] done = False while not done: action = base_stock_policy(policy, env) state, reward, done, _ = env.step(action) rewards.append(reward) if done: break rewards = np.array(rewards) prob = env.demand_dist.pmf(env.D, **env.dist_param) # Return negative of expected profit return -1 / env.num_periods * np.sum(prob * rewards)" }, { "code": null, "e": 13703, "s": 13015, "text": "Rather than return the sum of the rewards, we’re returning the negative expectation of our rewards. The reason for the negative is the Scipy function we’re using seeks to minimize whereas our environment is designed to maximize the reward, so we invert this to ensure everything is pointing in the right direction. We calculate the expected rewards by multiplying by the probability of our demand based on the distribution. We could take more samples to estimate the distribution and calculate our expectation that way (and for many real-world applications, this would be required), but here, we have access to the true distribution so we can use that to reduce our computational burden." }, { "code": null, "e": 13737, "s": 13703, "text": "Finally, we’re ready to optimize." }, { "code": null, "e": 14051, "s": 13737, "text": "The following function will build an environment based on your configuration settings, take our dfo_func to evaluate, and apply Powell's Method to the problem. It will return our policy and ensure that our answer contains only positive integers (e.g. we can't order half a widget or a negative number of widgets)." }, { "code": null, "e": 14542, "s": 14051, "text": "def optimize_inventory_policy(env_name, fun, init_policy=None, env_config={}, method='Powell'): env = or_gym.make(env_name, env_config=env_config) if init_policy is None: init_policy = np.ones(env.num_stages-1) # Optimize policy out = minimize(fun=fun, x0=init_policy, args=env, method=method) policy = out.x.copy() # Policy must be positive integer policy = np.round(np.maximum(policy, 0), 0).astype(int) return policy, out" }, { "code": null, "e": 14580, "s": 14542, "text": "Now it’s time to put it all together." }, { "code": null, "e": 15116, "s": 14580, "text": "policy, out = optimize_inventory_policy('InvManagement-v1', dfo_func)print(\"Re-order levels: {}\".format(policy))print(\"DFO Info:\\n{}\".format(out))Re-order levels: [540 216 81]DFO Info: direc: array([[ 0. , 0. , 1. ], [ 0. , 1. , 0. ], [206.39353826, 81.74560612, 28.78995703]]) fun: -0.9450780368543933 message: 'Optimization terminated successfully.' nfev: 212 nit: 5 status: 0 success: True x: array([539.7995151 , 216.38046861, 80.66902905])" }, { "code": null, "e": 15341, "s": 15116, "text": "Our DFO model found a fixed-stock policy with re-order levels at 540 for stage 0, 216 for stage 1, and 81 for stage 2. It did this with only 212 function evaluations, i.e. it simulated 212 episodes to find the optimal value." }, { "code": null, "e": 15476, "s": 15341, "text": "We can run then feed this policy into our environment, say 1,000 times, to generate some statistics and compare it to our RL solution." }, { "code": null, "e": 15787, "s": 15476, "text": "env = or_gym.make(env_name, env_config=env_config)eps = 1000rewards = []for i in range(eps): env.reset() reward = 0 while True: action = base_stock_policy(policy, eenv) s, r, done, _ = env.step(action) reward += r if done: rewards.append(reward) break" }, { "code": null, "e": 16467, "s": 15787, "text": "Before we get into the reward comparisons, note that these are not perfect, 1:1 comparisons. As mentioned before, DFO yields us a fixed policy whereas RL has a more flexible, dynamic policy that changes based on state information. Our DFO approach was also given some information in terms of probabilities of demand to calculate the expectation on, RL had to infer that from additional sampling. So while RL learned from nearly ~65k episodes and DFO only had to make 212 function calls, they aren’t exactly comparable. Considering that to enumerate every meaningful fixed policy once would require ~200 million episodes, then RL doesn’t look so sample inefficient given its task." }, { "code": null, "e": 16494, "s": 16467, "text": "So, how do these stack up?" }, { "code": null, "e": 16891, "s": 16494, "text": "What we can see above is that RL does indeed outperform our DFO policy by 11% on average (460 to 414). The RL model overtook the DFO policy after ~15k episodes and improved steadily after that. There is some higher variance with the RL policy however, with a few terrible episodes thrown in to the mix. All things considered, we did get stronger results overall from the RL approach, as expected." }, { "code": null, "e": 17206, "s": 16891, "text": "In this case, neither method was very difficult to implement nor computationally intensive. I forgot to change my rl_config settings to run on my GPU and it still only took about 25 minutes to train on my laptop while the DFO model took ~2 seconds to run. More complex models may not be so friendly in either case." }, { "code": null, "e": 17596, "s": 17206, "text": "Another thing to note, both methods can be very sensitive to initial conditions and neither are guaranteed to find the optimum policy in every case. If you have a problem you’d like to apply RL to, maybe use a simple DFO solver first, try a few initial conditions to get a feel for the problem, then spin up the full, RL model. You may find that the DFO policy is sufficient for your task." } ]
Saving and Loading Keras model using JSON and YAML files | by Renu Khandelwal | Towards Data Science
How can you share a deep learning model you trained that is giving awesome results with other team members working in a different part of the world or How to save a deep learning model and it’s trained weights during or after training or How to resume training of a model from where you left off? To answer the above questions we need to save the Model architecture Trained weights or Parameters of the model Sharing the saved files will allow others to recreate the model to make inferences or to resume further training from you left off. The model can be recreated by loading the model, and it’s trained weight from the saved files containing the model architecture and the pre-trained weights. Different methods to save and load the deep learning model are using JSON files YAML files Checkpoints In this article, you will learn how to save a deep learning model developed in Keras to JSON or YAML file format and then reload the model. To save the model, we first create a basic deep learning model. I have used the Fashion MNIST dataset, which we use to save and then reload the model using different methods. We need to install two libraries : pyyaml and h5py pip install pyyamlpip install h5py I am using Tensorflow 1.14.0 #Importing required libarariesimport osimport tensorflow as tffrom tensorflow import keras#Loading Fashion MNIST dataset(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.fashion_mnist.load_data()#creating a smaller dataset train_labels = train_labels[:1000]test_labels = test_labels[:1000]#Normalizing the datasettrain_images = train_images[:1000].astype('float32') / 255test_images = test_images[:1000].astype('float32') / 255# Reshaping the data for inputing into the modeltrain_images = train_images.reshape((train_images.shape[0], 28, 28,1))test_images = test_images.reshape((test_images.shape[0], 28, 28,1))#Defining and compiling the keras modeldef create_model(): model = tf.keras.Sequential() # Must define the input shape in the first layer of the neural network model.add(tf.keras.layers.Conv2D(filters=64, kernel_size=2, padding='same', activation='relu', input_shape=(28,28,1))) model.add(tf.keras.layers.MaxPooling2D(pool_size=2)) model.add(tf.keras.layers.Dropout(0.3)) model.add(tf.keras.layers.Conv2D(filters=32, kernel_size=2, padding='same', activation='relu')) model.add(tf.keras.layers.MaxPooling2D(pool_size=2)) model.add(tf.keras.layers.Dropout(0.3)) model.add(tf.keras.layers.Flatten()) model.add(tf.keras.layers.Dense(256, activation='relu')) model.add(tf.keras.layers.Dropout(0.5)) model.add(tf.keras.layers.Dense(10, activation='softmax')) #Compiling the model model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model# Create a basic model instancemodel = create_model()model.summary() Steps for saving and loading model to a JSON file Fit the train data to the model The model architecture will be saved to a JSON file using to_json(). The returned string will be saved in a JSON file Save the trained weights using save_weights() Reload the model architecture from the JSON file by reading the JSON file and then reload the model architecture to a new model using model_from_json() The trained weights will be reloaded using and load_weights() Fitting the train data to the model #Fit the train data to the modelmodel.fit(train_images, train_labels, batch_size=64, epochs=100, validation_data=(test_images,test_labels)) Saving the model architecture and weights to JSON file Write the model architecture to a JSON file using to_json() and save the weights of the trained model using save_weights() from keras.models import model_from_json# serialize model to jsonjson_model = model.to_json()#save the model architecture to JSON filewith open('fashionmnist_model.json', 'w') as json_file: json_file.write(json_model)#saving the weights of the modelmodel.save_weights('FashionMNIST_weights.h5')#Model loss and accuracyloss,acc = model.evaluate(test_images, test_labels, verbose=2) Reloading the model architecture from JSON File to a new model We have created a new model: model_j, which will have the same architecture as the saved model I added the glorot_uniform library as I was getting a warning for the initializer from keras.initializers import glorot_uniform#Reading the model from JSON filewith open('fashionmnist_model.json', 'r') as json_file: json_savedModel= json_file.read()#load the model architecture model_j = tf.keras.models.model_from_json(json_savedModel)model_j.summary() The new model has the same architecture as the previously saved model Reloading the trained weights to the new model Use load_weights() to load the pre-trained weights to the new model model_j.load_weights('FashionMNIST_weights.h5') Only the model architecture and pre-trained weights are loaded to the new model, but the model compilation details are missing, so we need to compile the model. We can specify different optimizers to compile the model, like changing the optimizer from Adam to “Rmsprop” or “SGD.” #Compiling the modelmodel_j.compile(loss='sparse_categorical_crossentropy', optimizer='SGD', metrics=['accuracy']) We can check the loss and accuracy of the new model to confirm if the same trained weights were loaded loss,acc = model_j.evaluate(test_images, test_labels, verbose=2) Steps for saving and loading model to a YAML file Fit the train data to the model The model architecture will be saved to a YAML file using to_yaml(). The returned string will be saved in a YAML file Save the trained weights using save() in an H5 file. Reload the model architecture from the YAML file by reading the YAML file and then reload the model architecture to a new model using model_from_yaml() The trained weights will be saved using save() and loaded to a new model using load_model() We will use the previous model for saving to a YAML file. We will not fit the model again as it was already trained. Saving the model architecture to YAML file Write the model architecture to a YAML file using to_yaml() #saving the model to a YAML fileyaml_model= model.to_yaml()# writing the yaml model to the yaml filewith open('fashionmnist_yamlmodel.yaml', 'w') as yaml_file: yaml_file.write(yaml_model) Reloading the model architecture from YAML File to a new model Read the model architecture from the YAML and restore it to a new model, model_y using model_from_yaml() We get the same model architecture as the original model #Read the model architecture from YAML filewith open('fashionmnist_yamlmodel.yaml', 'r') as yaml_file: yaml_savedModel=yaml_file.read()# Load the saved Yaml modelfrom keras.models import model_from_yamlmodel_y= tf.keras.models.model_from_yaml(yaml_savedModel)model_y.summary() Save the weights using Save() in HDF5 format in a single file/folder The architecture of the model so that we can recreate it anywhere anytime Trained weights of the model Training configuration like loss function, optimizer, etc. State of the optimizer Save() helps to export a model and recreate the entire model or resume training from where you left off. The model could be reinstated using load_model(), which also takes care of compiling the model using the saved training configurations. #saving the smodel's architecture, weights, and training configuration in a single file/folder.model.save('fashionmnist.h5') Reinstating the model # loading the model from the HDF5 filemodel_h5 = tf.keras.models.load_model('fashionmnist.h5') Let’s evaluate the new reinstated model on test images. Note we are not compiling the model here loss,acc = model_h5.evaluate(test_images, test_labels, verbose=2) We get approximately the same loss and accuracy as we have not set the seed here. code for saving the model and reloading model using Fashion MNIST We can now save weights and reload them into a new model using the JSON file or YAML file that will allow you to share your excellent deep learning work with the world or resume your training for better performance. Saving and loading the model using checkpoint is discussed in the next article
[ { "code": null, "e": 469, "s": 172, "text": "How can you share a deep learning model you trained that is giving awesome results with other team members working in a different part of the world or How to save a deep learning model and it’s trained weights during or after training or How to resume training of a model from where you left off?" }, { "code": null, "e": 519, "s": 469, "text": "To answer the above questions we need to save the" }, { "code": null, "e": 538, "s": 519, "text": "Model architecture" }, { "code": null, "e": 581, "s": 538, "text": "Trained weights or Parameters of the model" }, { "code": null, "e": 870, "s": 581, "text": "Sharing the saved files will allow others to recreate the model to make inferences or to resume further training from you left off. The model can be recreated by loading the model, and it’s trained weight from the saved files containing the model architecture and the pre-trained weights." }, { "code": null, "e": 939, "s": 870, "text": "Different methods to save and load the deep learning model are using" }, { "code": null, "e": 950, "s": 939, "text": "JSON files" }, { "code": null, "e": 961, "s": 950, "text": "YAML files" }, { "code": null, "e": 973, "s": 961, "text": "Checkpoints" }, { "code": null, "e": 1113, "s": 973, "text": "In this article, you will learn how to save a deep learning model developed in Keras to JSON or YAML file format and then reload the model." }, { "code": null, "e": 1288, "s": 1113, "text": "To save the model, we first create a basic deep learning model. I have used the Fashion MNIST dataset, which we use to save and then reload the model using different methods." }, { "code": null, "e": 1339, "s": 1288, "text": "We need to install two libraries : pyyaml and h5py" }, { "code": null, "e": 1374, "s": 1339, "text": "pip install pyyamlpip install h5py" }, { "code": null, "e": 1403, "s": 1374, "text": "I am using Tensorflow 1.14.0" }, { "code": null, "e": 3072, "s": 1403, "text": "#Importing required libarariesimport osimport tensorflow as tffrom tensorflow import keras#Loading Fashion MNIST dataset(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.fashion_mnist.load_data()#creating a smaller dataset train_labels = train_labels[:1000]test_labels = test_labels[:1000]#Normalizing the datasettrain_images = train_images[:1000].astype('float32') / 255test_images = test_images[:1000].astype('float32') / 255# Reshaping the data for inputing into the modeltrain_images = train_images.reshape((train_images.shape[0], 28, 28,1))test_images = test_images.reshape((test_images.shape[0], 28, 28,1))#Defining and compiling the keras modeldef create_model(): model = tf.keras.Sequential() # Must define the input shape in the first layer of the neural network model.add(tf.keras.layers.Conv2D(filters=64, kernel_size=2, padding='same', activation='relu', input_shape=(28,28,1))) model.add(tf.keras.layers.MaxPooling2D(pool_size=2)) model.add(tf.keras.layers.Dropout(0.3)) model.add(tf.keras.layers.Conv2D(filters=32, kernel_size=2, padding='same', activation='relu')) model.add(tf.keras.layers.MaxPooling2D(pool_size=2)) model.add(tf.keras.layers.Dropout(0.3)) model.add(tf.keras.layers.Flatten()) model.add(tf.keras.layers.Dense(256, activation='relu')) model.add(tf.keras.layers.Dropout(0.5)) model.add(tf.keras.layers.Dense(10, activation='softmax')) #Compiling the model model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model# Create a basic model instancemodel = create_model()model.summary()" }, { "code": null, "e": 3122, "s": 3072, "text": "Steps for saving and loading model to a JSON file" }, { "code": null, "e": 3154, "s": 3122, "text": "Fit the train data to the model" }, { "code": null, "e": 3272, "s": 3154, "text": "The model architecture will be saved to a JSON file using to_json(). The returned string will be saved in a JSON file" }, { "code": null, "e": 3318, "s": 3272, "text": "Save the trained weights using save_weights()" }, { "code": null, "e": 3470, "s": 3318, "text": "Reload the model architecture from the JSON file by reading the JSON file and then reload the model architecture to a new model using model_from_json()" }, { "code": null, "e": 3532, "s": 3470, "text": "The trained weights will be reloaded using and load_weights()" }, { "code": null, "e": 3568, "s": 3532, "text": "Fitting the train data to the model" }, { "code": null, "e": 3747, "s": 3568, "text": "#Fit the train data to the modelmodel.fit(train_images, train_labels, batch_size=64, epochs=100, validation_data=(test_images,test_labels))" }, { "code": null, "e": 3802, "s": 3747, "text": "Saving the model architecture and weights to JSON file" }, { "code": null, "e": 3925, "s": 3802, "text": "Write the model architecture to a JSON file using to_json() and save the weights of the trained model using save_weights()" }, { "code": null, "e": 4310, "s": 3925, "text": "from keras.models import model_from_json# serialize model to jsonjson_model = model.to_json()#save the model architecture to JSON filewith open('fashionmnist_model.json', 'w') as json_file: json_file.write(json_model)#saving the weights of the modelmodel.save_weights('FashionMNIST_weights.h5')#Model loss and accuracyloss,acc = model.evaluate(test_images, test_labels, verbose=2)" }, { "code": null, "e": 4373, "s": 4310, "text": "Reloading the model architecture from JSON File to a new model" }, { "code": null, "e": 4468, "s": 4373, "text": "We have created a new model: model_j, which will have the same architecture as the saved model" }, { "code": null, "e": 4550, "s": 4468, "text": "I added the glorot_uniform library as I was getting a warning for the initializer" }, { "code": null, "e": 4825, "s": 4550, "text": "from keras.initializers import glorot_uniform#Reading the model from JSON filewith open('fashionmnist_model.json', 'r') as json_file: json_savedModel= json_file.read()#load the model architecture model_j = tf.keras.models.model_from_json(json_savedModel)model_j.summary()" }, { "code": null, "e": 4895, "s": 4825, "text": "The new model has the same architecture as the previously saved model" }, { "code": null, "e": 4942, "s": 4895, "text": "Reloading the trained weights to the new model" }, { "code": null, "e": 5010, "s": 4942, "text": "Use load_weights() to load the pre-trained weights to the new model" }, { "code": null, "e": 5058, "s": 5010, "text": "model_j.load_weights('FashionMNIST_weights.h5')" }, { "code": null, "e": 5219, "s": 5058, "text": "Only the model architecture and pre-trained weights are loaded to the new model, but the model compilation details are missing, so we need to compile the model." }, { "code": null, "e": 5338, "s": 5219, "text": "We can specify different optimizers to compile the model, like changing the optimizer from Adam to “Rmsprop” or “SGD.”" }, { "code": null, "e": 5469, "s": 5338, "text": "#Compiling the modelmodel_j.compile(loss='sparse_categorical_crossentropy', optimizer='SGD', metrics=['accuracy'])" }, { "code": null, "e": 5572, "s": 5469, "text": "We can check the loss and accuracy of the new model to confirm if the same trained weights were loaded" }, { "code": null, "e": 5638, "s": 5572, "text": "loss,acc = model_j.evaluate(test_images, test_labels, verbose=2)" }, { "code": null, "e": 5688, "s": 5638, "text": "Steps for saving and loading model to a YAML file" }, { "code": null, "e": 5720, "s": 5688, "text": "Fit the train data to the model" }, { "code": null, "e": 5838, "s": 5720, "text": "The model architecture will be saved to a YAML file using to_yaml(). The returned string will be saved in a YAML file" }, { "code": null, "e": 5891, "s": 5838, "text": "Save the trained weights using save() in an H5 file." }, { "code": null, "e": 6043, "s": 5891, "text": "Reload the model architecture from the YAML file by reading the YAML file and then reload the model architecture to a new model using model_from_yaml()" }, { "code": null, "e": 6135, "s": 6043, "text": "The trained weights will be saved using save() and loaded to a new model using load_model()" }, { "code": null, "e": 6252, "s": 6135, "text": "We will use the previous model for saving to a YAML file. We will not fit the model again as it was already trained." }, { "code": null, "e": 6295, "s": 6252, "text": "Saving the model architecture to YAML file" }, { "code": null, "e": 6355, "s": 6295, "text": "Write the model architecture to a YAML file using to_yaml()" }, { "code": null, "e": 6546, "s": 6355, "text": "#saving the model to a YAML fileyaml_model= model.to_yaml()# writing the yaml model to the yaml filewith open('fashionmnist_yamlmodel.yaml', 'w') as yaml_file: yaml_file.write(yaml_model)" }, { "code": null, "e": 6609, "s": 6546, "text": "Reloading the model architecture from YAML File to a new model" }, { "code": null, "e": 6714, "s": 6609, "text": "Read the model architecture from the YAML and restore it to a new model, model_y using model_from_yaml()" }, { "code": null, "e": 6771, "s": 6714, "text": "We get the same model architecture as the original model" }, { "code": null, "e": 7053, "s": 6771, "text": "#Read the model architecture from YAML filewith open('fashionmnist_yamlmodel.yaml', 'r') as yaml_file: yaml_savedModel=yaml_file.read()# Load the saved Yaml modelfrom keras.models import model_from_yamlmodel_y= tf.keras.models.model_from_yaml(yaml_savedModel)model_y.summary()" }, { "code": null, "e": 7122, "s": 7053, "text": "Save the weights using Save() in HDF5 format in a single file/folder" }, { "code": null, "e": 7196, "s": 7122, "text": "The architecture of the model so that we can recreate it anywhere anytime" }, { "code": null, "e": 7225, "s": 7196, "text": "Trained weights of the model" }, { "code": null, "e": 7284, "s": 7225, "text": "Training configuration like loss function, optimizer, etc." }, { "code": null, "e": 7307, "s": 7284, "text": "State of the optimizer" }, { "code": null, "e": 7412, "s": 7307, "text": "Save() helps to export a model and recreate the entire model or resume training from where you left off." }, { "code": null, "e": 7548, "s": 7412, "text": "The model could be reinstated using load_model(), which also takes care of compiling the model using the saved training configurations." }, { "code": null, "e": 7673, "s": 7548, "text": "#saving the smodel's architecture, weights, and training configuration in a single file/folder.model.save('fashionmnist.h5')" }, { "code": null, "e": 7695, "s": 7673, "text": "Reinstating the model" }, { "code": null, "e": 7790, "s": 7695, "text": "# loading the model from the HDF5 filemodel_h5 = tf.keras.models.load_model('fashionmnist.h5')" }, { "code": null, "e": 7887, "s": 7790, "text": "Let’s evaluate the new reinstated model on test images. Note we are not compiling the model here" }, { "code": null, "e": 7953, "s": 7887, "text": "loss,acc = model_h5.evaluate(test_images, test_labels, verbose=2)" }, { "code": null, "e": 8035, "s": 7953, "text": "We get approximately the same loss and accuracy as we have not set the seed here." }, { "code": null, "e": 8101, "s": 8035, "text": "code for saving the model and reloading model using Fashion MNIST" }, { "code": null, "e": 8317, "s": 8101, "text": "We can now save weights and reload them into a new model using the JSON file or YAML file that will allow you to share your excellent deep learning work with the world or resume your training for better performance." } ]
Interpretability in PyTorch, Integrated Gradient | Towards Data Science
Neural networks have been taking the world by storm. Not a week passes without great news about how GPT-3 supposedly automates yet another language task. Or how AI is helping doctors during the current pandemic. But an increasing share of the population is becoming more and more skeptical about the turn AI is taking. Did it pick this treatment method because it is the right treatment method? Or because it happened to be the best one for that other 5.29-year-old patient in the training set? Entire population groups warn us of the implications of bad designs in AI, and we should better listen. After all, racial and gender-related features have been used in the recent hiring process algorithms in discriminating ways! How can we, as an AI-community, Make sure we build inclusive tools.Make sure our models do what we think they are doing.Explain to others what our models are doing. Make sure we build inclusive tools. Make sure our models do what we think they are doing. Explain to others what our models are doing. The answer to 1,2 and 3 is clear Interpretability! It has been taking in the world of Deep Learning by storm. Let’s learn today what it is and how we can easily integrate it into our process. We will build a Neural Network to predict the survival chance of a titanic passenger. And finally, understand what we did, and interpret our model using Captum. All using the mighty Lightning framework. We will start by importing our dependencies. # Our ML thingsimport pytorch_lightning as plimport torchfrom torch.utils.data import DataLoader, Datasetfrom captum.attr import IntegratedGradientsfrom pytorch_lightning import seed_everythingfrom pytorch_lightning import Trainer# Visualizationimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt# Utilsfrom enum import Enumimport pandas as pdfrom sklearn.metrics import classification_report To make this minimal example, we will work with the Titanic dataset (one small file). It can be downloaded here. Once you downloaded it, put it into a new folder ‘data/train.csv..’ This dataset is probably the most popular Kaggle dataset ever and therefore allows us to verify our results. It contains the 890 different passengers of the Titanic. For each passenger, we are going to predict if they survived! To do so, we are given several features. PassengerId Survived Pclass ... Fare Cabin Embarked0 1 0 ... 7.2500 NaN S We will only work with a small subset of these, namely: Survived Pclass Sex Age SibSp Fare0 0 3 male 22.0 1 7.2500 Now that we got an overview, let’s define the Dataset. A Dataset is a class from PyTorch. It needs to define 3 private functions, init(), len(), getitem(). If you are not familiar with this, you can find an easy explanation here (1. The Dataset). The goal here is to make a minimal preprocessing to show our interpretation later. # Simple enum that helps organizing# Not really importantclass TrainType(Enum): train = 1 test = 2# Our Custom Dataset classclass RMSTitanic(Dataset): def __init__(self, type: TrainType): file = "data/train.csv" # Preprocessing df = pd.read_csv(file) # Select relevant fields df = df[['Survived', 'Pclass', "Sex", "Age", "SibSp", "Fare"]] # Convert Sex -> 0/1 m = {'male': 1, 'female': 0} df['Sex'] = df['Sex'].str.lower().map(m) # Fix the non available vals # Also normalize df = df.fillna(df.median()) df -= df.min() df /= df.max() # The first 80% are Train if type == TrainType.train: self.df = df.loc[:int(0.8 * len(df))] if type == TrainType.test: self.df = df.loc[int(0.8 * len(df)):] # We will use this later for interpretation self.base = torch.tensor(df[ ['Pclass', "Sex", "Age", "SibSp", "Fare"] ].mean()).cuda().float() def __len__(self): return len(self.df) def __getitem__(self, item): # This function return the i-th elem row = self.df.iloc[item] label = row['Survived'] features = row[['Pclass', "Sex", "Age", "SibSp", "Fare"]] # return the (label,features) return ( torch.tensor(features).cuda().float(), torch.tensor(label).cuda().float() ) And that’s already our minimal Dataset. Keep in mind that this is only a small helper class. It helps Pytorch Lightning do its magic, so we save more code down the line. The features we got and what their interpretation is. Pclass "What class is person traveling in? First being best"Sex "Male or Female"Age "How old in years?"SibSp "How many Sibiling/Spouses are there onboard"Fare "Amount in money spend" We will now build a short but powerful model. It will call the following layers in order. | Name | Type | ------------------------0 | input | Linear | 1 | r1 | PReLU | 2 | l1 | Linear |3 | r2 | PReLU | 4 | out | Linear | 5 | sigmoid | Sigmoid | We will now define a PytorchModel called MyHeartWillGoOn. Basically, only the forward function is crucial. class MyHeartWillGoOn(pl.LightningModule): def __init__(self): # Setting up our model super().__init__() # way to fancy model self.lr = 0.01 self.batch_size = 512 l1 = 128 # We send our 5 features into first layer self.input = torch.nn.Linear(5, l1) # PRELU is just a fancy activation function self.r1 = torch.nn.PReLU() # More Layers self.l1 = torch.nn.Linear(l1, l1) self.r2 = torch.nn.PReLU() self.out = torch.nn.Linear(l1, 1) # Befor the Output use a sigmoid self.sigmoid = torch.nn.Sigmoid() # Define loss self.criterion = torch.nn.BCELoss() def forward(self, x): # Heart of our model x = self.input(x) x = self.l1(x) x = self.r1(x) x = self.out(x) x = self.r2(x) x = self.sigmoid(x) return x def train_dataloader(self): # Load our Dataset: TRAIN return DataLoader( RMSTitanic(type=TrainType.train), batch_size=self.batch_size, shuffle=True) def val_dataloader(self): # Load our Dataset: TEST # Simplification: TEST=VAL return DataLoader( RMSTitanic(type=TrainType.test), batch_size=self.batch_size, shuffle=False) def configure_optimizers(self): return torch.optim.Adam(self.parameters(), lr=self.lr) def training_step(self, batch, batch_idx): # Here we just log some basics # We can look at them later in tensorboard x, y = batch y_hat = self(x) y = torch.reshape(y, (y.size()[0], 1)) loss = self.criterion(y_hat, y) tensorboard_logs = {'loss': loss} return {'loss': loss, 'log': tensorboard_logs} Training with PyTorch Lightning is done with a nice little Trainer. if __name__ == '__main__': # Seed so we can reproduce seed_everything(404) # Load model to GPU device = torch.device("cuda") model = MyHeartWillGoOn().to(device) # Make the Trainer do the work trainer = Trainer(max_epochs=20, min_epochs=1, auto_lr_find=True, progress_bar_refresh_rate=10) trainer.fit(model) # Accuracy #ToBeMeasured ts = RMSTitanic(TrainType.test) # Bit of Hacking x = torch.stack( [ts.__getitem__(i)[0] for i in range(ts.__len__())] ) y = torch.stack( [ts.__getitem__(i)[1] for i in range(ts.__len__())] ).cpu().detach().numpy() y_hat = model.forward(x).cpu().detach().numpy() y_hat = (y_hat > 0.5) # Accuracy and other metrics print("REPORT:\n", classification_report(y, y_hat)) Training our model on a GPU for 20 epochs will give us the following results. SURVIVED precision recall f1-score supportFALSE 0.84 0.94 0.89 115TRUE 0.86 0.67 0.75 64accuracy 0.84 179macro avg 0.85 0.81 0.82 179weighted avg 0.85 0.84 0.84 179 As we can see, we get an easy 84% accuracy, which is acceptable for this task. We are more interested in interpreting this time. If you want to know how to get a perfect score on this task, have a look at Kaggle. Since Pytorch Lightning is really new, and Captum is even newer ;) We are pretty cutting edge here. We need to get around a few little problems, which yet have not been solved properly. To get this right, we need to add a smaller wrapper function to present later to Captum. Basically, Captum is a Library that has several methods available. These methods predict the importance of input features to Neural models. They do so in several ways. We will use the probably most popular method IntegratedGradient. I will give an intuition of this method below. # Let's start with the interpretationSTEP_AMOUNT = 50SAMPLE_DIM = 5# Since Captum is not directly# made for Lightning,# we need this wrapperdef modified_f(in_vec): # Changes the shapes correctly # X:Shape([SAMPLE_DIM*STEP_AMOUNT]=250) x = torch.reshape(in_vec, (int(in_vec.size()[0] / SAMPLE_DIM), SAMPLE_DIM) ) # RES:Shape([50,5]) # Since we have 50ti Batches and 5 features res = model.forward(x) # Again reshape to correct dims res = torch.reshape(res, (res.size()[0], 1)) return resig = IntegratedGradients(modified_f) Now we can start learning how our model thinks. Give this object IntegratedGradients. We can use its main method attribute()! attribute() is a function that takes as an input a tensor and returns us a tensor of the same shape This means that when we tell our model, our case study object: Pclass Sex Age SibSp Fare3 male 22.0 1 7.2500 (I am not normalized) It will make a prediction using these 5 features. Let’s say 0.3, which means 0.3% survival chance, for this 22-year-old man paying 7.25 in the fare. After predicting, we will send this 30% Survival rate ->0 %, meaning he died. Now Integrated gradient returns us a tensor, also having 5 values. Each of these values will tell us how important the respective feature is. This may be a difference in y. E.g. Pclass Sex Age SibSp Fare0.1619, -0.1594, 0.0196, -0.0024, 0.0068 A little theory lesson in the middle. Integrated Gradients has been proposed in “Axiomatic Attribution for Deep Networks.” Integrated Gradients is used to understand how our Neural Network works. Integrated Gradients is a so-called interpretability algorithm. There are several interpretability algorithms used in today's AI community, but IG is one of the first and most established ones. The scientific community has not clearly decided which algorithm is the best. Feel free to test some of the other ones, like DeepLift. This is a simplified explanation, please refer to the paper for more details “Axiomatic Attribution for Deep Networks” To optimize a loss function in a Neural Network fashion, we build a gradient. To understand how much each input feature contributes to our loss function, we reverse this process (called Integration), so we Integrate the Gradient. Now, calculating the Integral is hard, and the answer is not clear. This is why we have to approximate it. We approximate this Integral using a Riemann Sum. We approximate the value by using a hyperparameter n_steps and a baseline. The baseline is what we compare our input to (we look at this in detail below). The n_steps is the number of times we backpropagate to estimate the integral. N_steps basically controls how precise our estimate of the integral is. We now have 3 things: A Trained modelA Test setIntegrated Gradient A Trained model A Test set Integrated Gradient Using these things, we will understand our model # Test to understand the basics# First get the 6th test exampleval = ts.__getitem__(6)[0]print("IN X1:", val)# Predict the importance of the features# for the male exampleimp_m = ig.attribute(inputs=val, baselines=ts.base, n_steps=STEP_AMOUNT)print("IMPORTANCE X_m:", imp_m)print("Probability SURVIVAl X_m:", modified_f(val))# Predict the importance of the features# for the female exampleprint("Let's Change the gender ->X2")val_f = valval_f[1] = 0imp_f = ig.attribute(inputs=val_f, baselines=ts.base, n_steps=STEP_AMOUNT)print("IMPORTANCE X_f:", imp_f)print("Probability SURVIVAl X_f:", modified_f(val_f)) This code will print: IN X1: [1.0000, 1.0000, 0.3466, 0.0000, 0.0303]IMPORTANCE X_m:[-0.0593, -0.1121, -0.0010, 0.0019, -0.0040]Probability SURVIVAl X_m:0.1265IMPORTANCE X_f:[-0.1178, 0.4049, -0.0020, 0.0037, -0.0080]Probability SURVIVAl X_f:0.5817 As you can see, when we give Captum, these two identical examples. With the exception of Gender. We get drastically different survival rates. # MALEPclass Sex Age SibSp Fare3 male 22.0 1 7.2500 (I am not normalized)# FEMALEPclass Sex Age SibSp Fare3 female 22.0 1 7.2500 (I am not normalized) And the Survival guess for the male is 12% and 58% for the female! The two Importance values we got are: Pclass Sex Age SibSp Fare IMPORTANCE X_m:[-0.0593, -0.1121, -0.0010, 0.0019, -0.0040]IMPORTANCE X_f:[-0.1178, 0.4049, -0.0020, 0.0037, -0.0080] As we can see in both cases, the importance is the strongest (in absolute terms) in the feature SEX. This indicates that this is the most important feature! Interpreting the sign: We can think of it as something that adds to the prediction (+) or deducted from the prediction (-). I.e. + makes it more likely to be (1) or less likely to be (1). We can see that depending on the Sex(Male\Female), the resulting vector is quite different. The baseline is what we compare our value. In order to understand its impact, we will compare the most obvious choices. In the initial paper, the ideas of noise and black images (zeros) were used. We will compare 4 different baselines. Compare to: 1.the average! 2. noise, compared to random 3. all ones 4. all zeros To following, code will produce the desired interpretation. # define a collectionto_be_df = []# Compare each element of the test set to out baselines# we will than use thisfor i in range(0, 1): # ts.__len__()): # load our test example in_val = ts.__getitem__(i)[0] # compare it to the 4 baselines att_b = ig.attribute( inputs=in_val, baselines=ts.base, n_steps=STEP_AMOUNT).detach().cpu().numpy() att_r = ig.attribute( inputs=in_val, baselines=torch.rand( 5).cuda(), n_steps=STEP_AMOUNT).detach().cpu().numpy() att_z = ig.attribute( inputs=in_val, baselines=torch.zeros( 5).cuda(), n_steps=STEP_AMOUNT).detach().cpu().numpy() att_1 = ig.attribute( inputs=in_val, baselines=torch.ones( 5).cuda(), n_steps=STEP_AMOUNT).detach().cpu().numpy() # save result, this will produce a df # you can skip the details for base_type, vals in [ ("mean-base", att_b), ("random-base", att_r), ("zero-base", att_z), ('one-base', att_1), ]: for i, name in enumerate(['Pclass', "Sex", "Age", "SibSp", "Fare"]): to_be_df.append({ "base-type": base_type, "feature": name, "value": vals[i], })# Convert our data to a pandasdf = pd.DataFrame(to_be_df)df.to_csv('data/interpretation_results.csv')print("OUR INTERPRETATION:\n\n", df) Our results look something like this. base-type feature value0 mean-base Pclass 0.1620041 mean-base Sex -0.1594212 mean-base Age 0.0196523 mean-base SibSp -0.0024334 mean-base Fare 0.0068215 random-base Pclass 0.117517 Now we found what we are after! Once we have done the work, we can sit back and enjoy it! # Aggregate and Visualize# Load Datadf = pd.read_csv('data/interpretation_results.csv')# Defined the color map for our heatmap to be red to greencmap = sns.diverging_palette(h_neg=10, h_pos=130, s=99, l=55, sep=3, as_cmap=True)# Aggregate the CSV by meandf = df.groupby(["base-type", 'feature', 'epoch'], as_index=False).mean()df = df[df['epoch'] == max_epoch]# Make one plot per baseline to comparefor b in ["mean-base", "random-base", "zero-base", 'one-base']: # Let's plot them isolated tmp = df[df['base-type'] == b] # Create a pivot frame tmp = tmp.pivot(index='base-type', columns='feature', values='value') print("We will plot:\n",tmp) A pivot data frame is basically just taking a different view on the same data. Here we tell it to have the index (the rows on the base-type) and the columns on the ‘features.’ This looks something like this. feature Age Fare Pclass Sex SibSpmean-base 0.023202 0.004757 0.116368 0.225421 0.022177 Now all that is left to do is plot it using # Create a pivot frame tmp = tmp.pivot(index='base-type', columns='feature', values='value')# Some code to make a heatmap using seabornfig, ax = plt.subplots()fig.set_size_inches(10, 2.5)plt.title("Feature Importance ", fontsize=15)sns.heatmap(tmp, ax=ax, cmap=cmap, annot=True)plt.text(0, 0, 'By Sandro Luck\nTwitter:@san_sluck', horizontalalignment='center', verticalalignment='bottom', fontsize=10)plt.savefig(f'data/{b}.png') Great, now I hope also the last skeptic is convinced Sex is Great! We can clearly see that the impact of the feature Sex is significant. When we look at the dataset, we could notice that being a man increases your chance of dying significantly. “Women and children first” is the way they go with ships, after all. Here we see quite a difference between the baselines. If we compare the two baselines with the Mean-Base, we notice that the importance of SibSp changes drastically. This generally should illustrate that using baselines such as 1 and 0 is not advisable. The reason for this is that we calculate how much the prediction changes between baseline and value. For Images for example using a 0-baseline might make sense. The reason is that a black square represents in this case the absence of information. The surprise of the day comes for me in the form of the success of Random baselines. The authors of Integrated Gradients mentioned that using a random baseline is advisable. But i did not anticipate it working so well for this example. GIFs are crucial when making people pay attention to your data on certain platforms. Especially on social media, animation can make the difference between a click and a quick glimpse. Since this article is already pretty long, please refer to my article “How to make GIFS with Python and Seaborn From Google Trends Data” to learn at lightning speed to create the GIF above. We have learned what Interpretability is and how we can use it in PyTorch. We have seen how easy we can use it in our Prototyping and how to connect it to PyTorch Lightning. I hope this introduction to the world of Interpretability was easy and painless. Understanding what you are building can help our customers and us. It increases their confidence in our predictions significantly. If you enjoyed this article, I would be excited to connect on Twitter or LinkedIn. Make sure to check out my YouTube channel, where I will be publishing new videos every week.
[ { "code": null, "e": 384, "s": 172, "text": "Neural networks have been taking the world by storm. Not a week passes without great news about how GPT-3 supposedly automates yet another language task. Or how AI is helping doctors during the current pandemic." }, { "code": null, "e": 667, "s": 384, "text": "But an increasing share of the population is becoming more and more skeptical about the turn AI is taking. Did it pick this treatment method because it is the right treatment method? Or because it happened to be the best one for that other 5.29-year-old patient in the training set?" }, { "code": null, "e": 896, "s": 667, "text": "Entire population groups warn us of the implications of bad designs in AI, and we should better listen. After all, racial and gender-related features have been used in the recent hiring process algorithms in discriminating ways!" }, { "code": null, "e": 928, "s": 896, "text": "How can we, as an AI-community," }, { "code": null, "e": 1061, "s": 928, "text": "Make sure we build inclusive tools.Make sure our models do what we think they are doing.Explain to others what our models are doing." }, { "code": null, "e": 1097, "s": 1061, "text": "Make sure we build inclusive tools." }, { "code": null, "e": 1151, "s": 1097, "text": "Make sure our models do what we think they are doing." }, { "code": null, "e": 1196, "s": 1151, "text": "Explain to others what our models are doing." }, { "code": null, "e": 1388, "s": 1196, "text": "The answer to 1,2 and 3 is clear Interpretability! It has been taking in the world of Deep Learning by storm. Let’s learn today what it is and how we can easily integrate it into our process." }, { "code": null, "e": 1591, "s": 1388, "text": "We will build a Neural Network to predict the survival chance of a titanic passenger. And finally, understand what we did, and interpret our model using Captum. All using the mighty Lightning framework." }, { "code": null, "e": 1636, "s": 1591, "text": "We will start by importing our dependencies." }, { "code": null, "e": 2049, "s": 1636, "text": "# Our ML thingsimport pytorch_lightning as plimport torchfrom torch.utils.data import DataLoader, Datasetfrom captum.attr import IntegratedGradientsfrom pytorch_lightning import seed_everythingfrom pytorch_lightning import Trainer# Visualizationimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt# Utilsfrom enum import Enumimport pandas as pdfrom sklearn.metrics import classification_report" }, { "code": null, "e": 2339, "s": 2049, "text": "To make this minimal example, we will work with the Titanic dataset (one small file). It can be downloaded here. Once you downloaded it, put it into a new folder ‘data/train.csv..’ This dataset is probably the most popular Kaggle dataset ever and therefore allows us to verify our results." }, { "code": null, "e": 2458, "s": 2339, "text": "It contains the 890 different passengers of the Titanic. For each passenger, we are going to predict if they survived!" }, { "code": null, "e": 2499, "s": 2458, "text": "To do so, we are given several features." }, { "code": null, "e": 2618, "s": 2499, "text": "PassengerId Survived Pclass ... Fare Cabin Embarked0 1 0 ... 7.2500 NaN S" }, { "code": null, "e": 2674, "s": 2618, "text": "We will only work with a small subset of these, namely:" }, { "code": null, "e": 2772, "s": 2674, "text": "Survived Pclass Sex Age SibSp Fare0 0 3 male 22.0 1 7.2500" }, { "code": null, "e": 2928, "s": 2772, "text": "Now that we got an overview, let’s define the Dataset. A Dataset is a class from PyTorch. It needs to define 3 private functions, init(), len(), getitem()." }, { "code": null, "e": 3102, "s": 2928, "text": "If you are not familiar with this, you can find an easy explanation here (1. The Dataset). The goal here is to make a minimal preprocessing to show our interpretation later." }, { "code": null, "e": 4721, "s": 3102, "text": "# Simple enum that helps organizing# Not really importantclass TrainType(Enum): train = 1 test = 2# Our Custom Dataset classclass RMSTitanic(Dataset): def __init__(self, type: TrainType): file = \"data/train.csv\" # Preprocessing df = pd.read_csv(file) # Select relevant fields df = df[['Survived', 'Pclass', \"Sex\", \"Age\", \"SibSp\", \"Fare\"]] # Convert Sex -> 0/1 m = {'male': 1, 'female': 0} df['Sex'] = df['Sex'].str.lower().map(m) # Fix the non available vals # Also normalize df = df.fillna(df.median()) df -= df.min() df /= df.max() # The first 80% are Train if type == TrainType.train: self.df = df.loc[:int(0.8 * len(df))] if type == TrainType.test: self.df = df.loc[int(0.8 * len(df)):] # We will use this later for interpretation self.base = torch.tensor(df[ ['Pclass', \"Sex\", \"Age\", \"SibSp\", \"Fare\"] ].mean()).cuda().float() def __len__(self): return len(self.df) def __getitem__(self, item): # This function return the i-th elem row = self.df.iloc[item] label = row['Survived'] features = row[['Pclass', \"Sex\", \"Age\", \"SibSp\", \"Fare\"]] # return the (label,features) return ( torch.tensor(features).cuda().float(), torch.tensor(label).cuda().float() )" }, { "code": null, "e": 4891, "s": 4721, "text": "And that’s already our minimal Dataset. Keep in mind that this is only a small helper class. It helps Pytorch Lightning do its magic, so we save more code down the line." }, { "code": null, "e": 4945, "s": 4891, "text": "The features we got and what their interpretation is." }, { "code": null, "e": 5147, "s": 4945, "text": "Pclass \"What class is person traveling in? First being best\"Sex \"Male or Female\"Age \"How old in years?\"SibSp \"How many Sibiling/Spouses are there onboard\"Fare \"Amount in money spend\"" }, { "code": null, "e": 5237, "s": 5147, "text": "We will now build a short but powerful model. It will call the following layers in order." }, { "code": null, "e": 5459, "s": 5237, "text": " | Name | Type | ------------------------0 | input | Linear | 1 | r1 | PReLU | 2 | l1 | Linear |3 | r2 | PReLU | 4 | out | Linear | 5 | sigmoid | Sigmoid |" }, { "code": null, "e": 5566, "s": 5459, "text": "We will now define a PytorchModel called MyHeartWillGoOn. Basically, only the forward function is crucial." }, { "code": null, "e": 7335, "s": 5566, "text": "class MyHeartWillGoOn(pl.LightningModule): def __init__(self): # Setting up our model super().__init__() # way to fancy model self.lr = 0.01 self.batch_size = 512 l1 = 128 # We send our 5 features into first layer self.input = torch.nn.Linear(5, l1) # PRELU is just a fancy activation function self.r1 = torch.nn.PReLU() # More Layers self.l1 = torch.nn.Linear(l1, l1) self.r2 = torch.nn.PReLU() self.out = torch.nn.Linear(l1, 1) # Befor the Output use a sigmoid self.sigmoid = torch.nn.Sigmoid() # Define loss self.criterion = torch.nn.BCELoss() def forward(self, x): # Heart of our model x = self.input(x) x = self.l1(x) x = self.r1(x) x = self.out(x) x = self.r2(x) x = self.sigmoid(x) return x def train_dataloader(self): # Load our Dataset: TRAIN return DataLoader( RMSTitanic(type=TrainType.train), batch_size=self.batch_size, shuffle=True) def val_dataloader(self): # Load our Dataset: TEST # Simplification: TEST=VAL return DataLoader( RMSTitanic(type=TrainType.test), batch_size=self.batch_size, shuffle=False) def configure_optimizers(self): return torch.optim.Adam(self.parameters(), lr=self.lr) def training_step(self, batch, batch_idx): # Here we just log some basics # We can look at them later in tensorboard x, y = batch y_hat = self(x) y = torch.reshape(y, (y.size()[0], 1)) loss = self.criterion(y_hat, y) tensorboard_logs = {'loss': loss} return {'loss': loss, 'log': tensorboard_logs}" }, { "code": null, "e": 7403, "s": 7335, "text": "Training with PyTorch Lightning is done with a nice little Trainer." }, { "code": null, "e": 8181, "s": 7403, "text": "if __name__ == '__main__': # Seed so we can reproduce seed_everything(404) # Load model to GPU device = torch.device(\"cuda\") model = MyHeartWillGoOn().to(device) # Make the Trainer do the work trainer = Trainer(max_epochs=20, min_epochs=1, auto_lr_find=True, progress_bar_refresh_rate=10) trainer.fit(model) # Accuracy #ToBeMeasured ts = RMSTitanic(TrainType.test) # Bit of Hacking x = torch.stack( [ts.__getitem__(i)[0] for i in range(ts.__len__())] ) y = torch.stack( [ts.__getitem__(i)[1] for i in range(ts.__len__())] ).cpu().detach().numpy() y_hat = model.forward(x).cpu().detach().numpy() y_hat = (y_hat > 0.5) # Accuracy and other metrics print(\"REPORT:\\n\", classification_report(y, y_hat))" }, { "code": null, "e": 8259, "s": 8181, "text": "Training our model on a GPU for 20 epochs will give us the following results." }, { "code": null, "e": 8556, "s": 8259, "text": "SURVIVED precision recall f1-score supportFALSE 0.84 0.94 0.89 115TRUE 0.86 0.67 0.75 64accuracy 0.84 179macro avg 0.85 0.81 0.82 179weighted avg 0.85 0.84 0.84 179" }, { "code": null, "e": 8769, "s": 8556, "text": "As we can see, we get an easy 84% accuracy, which is acceptable for this task. We are more interested in interpreting this time. If you want to know how to get a perfect score on this task, have a look at Kaggle." }, { "code": null, "e": 8869, "s": 8769, "text": "Since Pytorch Lightning is really new, and Captum is even newer ;) We are pretty cutting edge here." }, { "code": null, "e": 9324, "s": 8869, "text": "We need to get around a few little problems, which yet have not been solved properly. To get this right, we need to add a smaller wrapper function to present later to Captum. Basically, Captum is a Library that has several methods available. These methods predict the importance of input features to Neural models. They do so in several ways. We will use the probably most popular method IntegratedGradient. I will give an intuition of this method below." }, { "code": null, "e": 9884, "s": 9324, "text": "# Let's start with the interpretationSTEP_AMOUNT = 50SAMPLE_DIM = 5# Since Captum is not directly# made for Lightning,# we need this wrapperdef modified_f(in_vec): # Changes the shapes correctly # X:Shape([SAMPLE_DIM*STEP_AMOUNT]=250) x = torch.reshape(in_vec, (int(in_vec.size()[0] / SAMPLE_DIM), SAMPLE_DIM) ) # RES:Shape([50,5]) # Since we have 50ti Batches and 5 features res = model.forward(x) # Again reshape to correct dims res = torch.reshape(res, (res.size()[0], 1)) return resig = IntegratedGradients(modified_f)" }, { "code": null, "e": 10010, "s": 9884, "text": "Now we can start learning how our model thinks. Give this object IntegratedGradients. We can use its main method attribute()!" }, { "code": null, "e": 10110, "s": 10010, "text": "attribute() is a function that takes as an input a tensor and returns us a tensor of the same shape" }, { "code": null, "e": 10173, "s": 10110, "text": "This means that when we tell our model, our case study object:" }, { "code": null, "e": 10267, "s": 10173, "text": "Pclass Sex Age SibSp Fare3 male 22.0 1 7.2500 (I am not normalized)" }, { "code": null, "e": 10494, "s": 10267, "text": "It will make a prediction using these 5 features. Let’s say 0.3, which means 0.3% survival chance, for this 22-year-old man paying 7.25 in the fare. After predicting, we will send this 30% Survival rate ->0 %, meaning he died." }, { "code": null, "e": 10672, "s": 10494, "text": "Now Integrated gradient returns us a tensor, also having 5 values. Each of these values will tell us how important the respective feature is. This may be a difference in y. E.g." }, { "code": null, "e": 10748, "s": 10672, "text": "Pclass Sex Age SibSp Fare0.1619, -0.1594, 0.0196, -0.0024, 0.0068" }, { "code": null, "e": 11008, "s": 10748, "text": "A little theory lesson in the middle. Integrated Gradients has been proposed in “Axiomatic Attribution for Deep Networks.” Integrated Gradients is used to understand how our Neural Network works. Integrated Gradients is a so-called interpretability algorithm." }, { "code": null, "e": 11273, "s": 11008, "text": "There are several interpretability algorithms used in today's AI community, but IG is one of the first and most established ones. The scientific community has not clearly decided which algorithm is the best. Feel free to test some of the other ones, like DeepLift." }, { "code": null, "e": 11392, "s": 11273, "text": "This is a simplified explanation, please refer to the paper for more details “Axiomatic Attribution for Deep Networks”" }, { "code": null, "e": 11622, "s": 11392, "text": "To optimize a loss function in a Neural Network fashion, we build a gradient. To understand how much each input feature contributes to our loss function, we reverse this process (called Integration), so we Integrate the Gradient." }, { "code": null, "e": 11779, "s": 11622, "text": "Now, calculating the Integral is hard, and the answer is not clear. This is why we have to approximate it. We approximate this Integral using a Riemann Sum." }, { "code": null, "e": 12084, "s": 11779, "text": "We approximate the value by using a hyperparameter n_steps and a baseline. The baseline is what we compare our input to (we look at this in detail below). The n_steps is the number of times we backpropagate to estimate the integral. N_steps basically controls how precise our estimate of the integral is." }, { "code": null, "e": 12106, "s": 12084, "text": "We now have 3 things:" }, { "code": null, "e": 12151, "s": 12106, "text": "A Trained modelA Test setIntegrated Gradient" }, { "code": null, "e": 12167, "s": 12151, "text": "A Trained model" }, { "code": null, "e": 12178, "s": 12167, "text": "A Test set" }, { "code": null, "e": 12198, "s": 12178, "text": "Integrated Gradient" }, { "code": null, "e": 12247, "s": 12198, "text": "Using these things, we will understand our model" }, { "code": null, "e": 12935, "s": 12247, "text": "# Test to understand the basics# First get the 6th test exampleval = ts.__getitem__(6)[0]print(\"IN X1:\", val)# Predict the importance of the features# for the male exampleimp_m = ig.attribute(inputs=val, baselines=ts.base, n_steps=STEP_AMOUNT)print(\"IMPORTANCE X_m:\", imp_m)print(\"Probability SURVIVAl X_m:\", modified_f(val))# Predict the importance of the features# for the female exampleprint(\"Let's Change the gender ->X2\")val_f = valval_f[1] = 0imp_f = ig.attribute(inputs=val_f, baselines=ts.base, n_steps=STEP_AMOUNT)print(\"IMPORTANCE X_f:\", imp_f)print(\"Probability SURVIVAl X_f:\", modified_f(val_f))" }, { "code": null, "e": 12957, "s": 12935, "text": "This code will print:" }, { "code": null, "e": 13187, "s": 12957, "text": "IN X1: [1.0000, 1.0000, 0.3466, 0.0000, 0.0303]IMPORTANCE X_m:[-0.0593, -0.1121, -0.0010, 0.0019, -0.0040]Probability SURVIVAl X_m:0.1265IMPORTANCE X_f:[-0.1178, 0.4049, -0.0020, 0.0037, -0.0080]Probability SURVIVAl X_f:0.5817" }, { "code": null, "e": 13329, "s": 13187, "text": "As you can see, when we give Captum, these two identical examples. With the exception of Gender. We get drastically different survival rates." }, { "code": null, "e": 13534, "s": 13329, "text": "# MALEPclass Sex Age SibSp Fare3 male 22.0 1 7.2500 (I am not normalized)# FEMALEPclass Sex Age SibSp Fare3 female 22.0 1 7.2500 (I am not normalized)" }, { "code": null, "e": 13639, "s": 13534, "text": "And the Survival guess for the male is 12% and 58% for the female! The two Importance values we got are:" }, { "code": null, "e": 13821, "s": 13639, "text": " Pclass Sex Age SibSp Fare IMPORTANCE X_m:[-0.0593, -0.1121, -0.0010, 0.0019, -0.0040]IMPORTANCE X_f:[-0.1178, 0.4049, -0.0020, 0.0037, -0.0080]" }, { "code": null, "e": 13978, "s": 13821, "text": "As we can see in both cases, the importance is the strongest (in absolute terms) in the feature SEX. This indicates that this is the most important feature!" }, { "code": null, "e": 14166, "s": 13978, "text": "Interpreting the sign: We can think of it as something that adds to the prediction (+) or deducted from the prediction (-). I.e. + makes it more likely to be (1) or less likely to be (1)." }, { "code": null, "e": 14258, "s": 14166, "text": "We can see that depending on the Sex(Male\\Female), the resulting vector is quite different." }, { "code": null, "e": 14455, "s": 14258, "text": "The baseline is what we compare our value. In order to understand its impact, we will compare the most obvious choices. In the initial paper, the ideas of noise and black images (zeros) were used." }, { "code": null, "e": 14494, "s": 14455, "text": "We will compare 4 different baselines." }, { "code": null, "e": 14506, "s": 14494, "text": "Compare to:" }, { "code": null, "e": 14521, "s": 14506, "text": "1.the average!" }, { "code": null, "e": 14550, "s": 14521, "text": "2. noise, compared to random" }, { "code": null, "e": 14562, "s": 14550, "text": "3. all ones" }, { "code": null, "e": 14575, "s": 14562, "text": "4. all zeros" }, { "code": null, "e": 14635, "s": 14575, "text": "To following, code will produce the desired interpretation." }, { "code": null, "e": 16187, "s": 14635, "text": "# define a collectionto_be_df = []# Compare each element of the test set to out baselines# we will than use thisfor i in range(0, 1): # ts.__len__()): # load our test example in_val = ts.__getitem__(i)[0] # compare it to the 4 baselines att_b = ig.attribute( inputs=in_val, baselines=ts.base, n_steps=STEP_AMOUNT).detach().cpu().numpy() att_r = ig.attribute( inputs=in_val, baselines=torch.rand( 5).cuda(), n_steps=STEP_AMOUNT).detach().cpu().numpy() att_z = ig.attribute( inputs=in_val, baselines=torch.zeros( 5).cuda(), n_steps=STEP_AMOUNT).detach().cpu().numpy() att_1 = ig.attribute( inputs=in_val, baselines=torch.ones( 5).cuda(), n_steps=STEP_AMOUNT).detach().cpu().numpy() # save result, this will produce a df # you can skip the details for base_type, vals in [ (\"mean-base\", att_b), (\"random-base\", att_r), (\"zero-base\", att_z), ('one-base', att_1), ]: for i, name in enumerate(['Pclass', \"Sex\", \"Age\", \"SibSp\", \"Fare\"]): to_be_df.append({ \"base-type\": base_type, \"feature\": name, \"value\": vals[i], })# Convert our data to a pandasdf = pd.DataFrame(to_be_df)df.to_csv('data/interpretation_results.csv')print(\"OUR INTERPRETATION:\\n\\n\", df)" }, { "code": null, "e": 16225, "s": 16187, "text": "Our results look something like this." }, { "code": null, "e": 16457, "s": 16225, "text": " base-type feature value0 mean-base Pclass 0.1620041 mean-base Sex -0.1594212 mean-base Age 0.0196523 mean-base SibSp -0.0024334 mean-base Fare 0.0068215 random-base Pclass 0.117517" }, { "code": null, "e": 16489, "s": 16457, "text": "Now we found what we are after!" }, { "code": null, "e": 16547, "s": 16489, "text": "Once we have done the work, we can sit back and enjoy it!" }, { "code": null, "e": 17294, "s": 16547, "text": "# Aggregate and Visualize# Load Datadf = pd.read_csv('data/interpretation_results.csv')# Defined the color map for our heatmap to be red to greencmap = sns.diverging_palette(h_neg=10, h_pos=130, s=99, l=55, sep=3, as_cmap=True)# Aggregate the CSV by meandf = df.groupby([\"base-type\", 'feature', 'epoch'], as_index=False).mean()df = df[df['epoch'] == max_epoch]# Make one plot per baseline to comparefor b in [\"mean-base\", \"random-base\", \"zero-base\", 'one-base']: # Let's plot them isolated tmp = df[df['base-type'] == b] # Create a pivot frame tmp = tmp.pivot(index='base-type', columns='feature', values='value') print(\"We will plot:\\n\",tmp)" }, { "code": null, "e": 17502, "s": 17294, "text": "A pivot data frame is basically just taking a different view on the same data. Here we tell it to have the index (the rows on the base-type) and the columns on the ‘features.’ This looks something like this." }, { "code": null, "e": 17621, "s": 17502, "text": "feature Age Fare Pclass Sex SibSpmean-base 0.023202 0.004757 0.116368 0.225421 0.022177" }, { "code": null, "e": 17665, "s": 17621, "text": "Now all that is left to do is plot it using" }, { "code": null, "e": 18146, "s": 17665, "text": "# Create a pivot frame tmp = tmp.pivot(index='base-type', columns='feature', values='value')# Some code to make a heatmap using seabornfig, ax = plt.subplots()fig.set_size_inches(10, 2.5)plt.title(\"Feature Importance \", fontsize=15)sns.heatmap(tmp, ax=ax, cmap=cmap, annot=True)plt.text(0, 0, 'By Sandro Luck\\nTwitter:@san_sluck', horizontalalignment='center', verticalalignment='bottom', fontsize=10)plt.savefig(f'data/{b}.png')" }, { "code": null, "e": 18460, "s": 18146, "text": "Great, now I hope also the last skeptic is convinced Sex is Great! We can clearly see that the impact of the feature Sex is significant. When we look at the dataset, we could notice that being a man increases your chance of dying significantly. “Women and children first” is the way they go with ships, after all." }, { "code": null, "e": 18815, "s": 18460, "text": "Here we see quite a difference between the baselines. If we compare the two baselines with the Mean-Base, we notice that the importance of SibSp changes drastically. This generally should illustrate that using baselines such as 1 and 0 is not advisable. The reason for this is that we calculate how much the prediction changes between baseline and value." }, { "code": null, "e": 18961, "s": 18815, "text": "For Images for example using a 0-baseline might make sense. The reason is that a black square represents in this case the absence of information." }, { "code": null, "e": 19197, "s": 18961, "text": "The surprise of the day comes for me in the form of the success of Random baselines. The authors of Integrated Gradients mentioned that using a random baseline is advisable. But i did not anticipate it working so well for this example." }, { "code": null, "e": 19381, "s": 19197, "text": "GIFs are crucial when making people pay attention to your data on certain platforms. Especially on social media, animation can make the difference between a click and a quick glimpse." }, { "code": null, "e": 19571, "s": 19381, "text": "Since this article is already pretty long, please refer to my article “How to make GIFS with Python and Seaborn From Google Trends Data” to learn at lightning speed to create the GIF above." }, { "code": null, "e": 19745, "s": 19571, "text": "We have learned what Interpretability is and how we can use it in PyTorch. We have seen how easy we can use it in our Prototyping and how to connect it to PyTorch Lightning." }, { "code": null, "e": 19957, "s": 19745, "text": "I hope this introduction to the world of Interpretability was easy and painless. Understanding what you are building can help our customers and us. It increases their confidence in our predictions significantly." }, { "code": null, "e": 20040, "s": 19957, "text": "If you enjoyed this article, I would be excited to connect on Twitter or LinkedIn." } ]
How to get last 2 characters from string in C# using Regex?
Set the string − string str = "Cookie and Session"; Use the following Regex to get the last 2 characters from string − Regex.Match(str,@"(.{2})\s*$") The following is the code − Live Demo using System; using System.Text.RegularExpressions; public class Demo { public static void Main() { string str = "Cookie and Session"; Console.WriteLine(Regex.Match(str,@"(.{2})\s*$")); } } on
[ { "code": null, "e": 1079, "s": 1062, "text": "Set the string −" }, { "code": null, "e": 1114, "s": 1079, "text": "string str = \"Cookie and Session\";" }, { "code": null, "e": 1181, "s": 1114, "text": "Use the following Regex to get the last 2 characters from string −" }, { "code": null, "e": 1212, "s": 1181, "text": "Regex.Match(str,@\"(.{2})\\s*$\")" }, { "code": null, "e": 1240, "s": 1212, "text": "The following is the code −" }, { "code": null, "e": 1251, "s": 1240, "text": " Live Demo" }, { "code": null, "e": 1459, "s": 1251, "text": "using System;\nusing System.Text.RegularExpressions;\npublic class Demo {\n public static void Main() {\n string str = \"Cookie and Session\";\n Console.WriteLine(Regex.Match(str,@\"(.{2})\\s*$\"));\n }\n}" }, { "code": null, "e": 1462, "s": 1459, "text": "on" } ]
JSTL - fn:startsWith() Function
The fn:startsWith() function determines if an input string starts with a specified substring. The fn:startsWith() function has the following syntax − boolean startsWith(java.lang.String, java.lang.String) Following example explains the functionality of the fn:startsWith() function − <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %> <%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %> <html> <head> <title>Using JSTL Functions</title> </head> <body> <c:set var = "string" value = "Second: This is first String."/> <c:if test = "${fn:startsWith(string, 'First')}"> <p>String starts with First</p> </c:if> <br /> <c:if test = "${fn:startsWith(string, 'Second')}"> <p>String starts with Second</p> </c:if> </body> </html> You will receive the following result − String starts with Second 108 Lectures 11 hours Chaand Sheikh 517 Lectures 57 hours Chaand Sheikh 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 44 Lectures 15 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2333, "s": 2239, "text": "The fn:startsWith() function determines if an input string starts with a specified substring." }, { "code": null, "e": 2389, "s": 2333, "text": "The fn:startsWith() function has the following syntax −" }, { "code": null, "e": 2445, "s": 2389, "text": "boolean startsWith(java.lang.String, java.lang.String)\n" }, { "code": null, "e": 2524, "s": 2445, "text": "Following example explains the functionality of the fn:startsWith() function −" }, { "code": null, "e": 3094, "s": 2524, "text": "<%@ taglib uri = \"http://java.sun.com/jsp/jstl/core\" prefix = \"c\" %>\n<%@ taglib uri = \"http://java.sun.com/jsp/jstl/functions\" prefix = \"fn\" %>\n\n<html>\n <head>\n <title>Using JSTL Functions</title>\n </head>\n\n <body>\n <c:set var = \"string\" value = \"Second: This is first String.\"/>\n \n <c:if test = \"${fn:startsWith(string, 'First')}\">\n <p>String starts with First</p>\n </c:if>\n \n <br />\n <c:if test = \"${fn:startsWith(string, 'Second')}\">\n <p>String starts with Second</p>\n </c:if>\n \n </body>\n</html>" }, { "code": null, "e": 3134, "s": 3094, "text": "You will receive the following result −" }, { "code": null, "e": 3161, "s": 3134, "text": "String starts with Second\n" }, { "code": null, "e": 3196, "s": 3161, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 3211, "s": 3196, "text": " Chaand Sheikh" }, { "code": null, "e": 3246, "s": 3211, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 3261, "s": 3246, "text": " Chaand Sheikh" }, { "code": null, "e": 3296, "s": 3261, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3310, "s": 3296, "text": " Karthikeya T" }, { "code": null, "e": 3345, "s": 3310, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3361, "s": 3345, "text": " TELCOMA Global" }, { "code": null, "e": 3394, "s": 3361, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 3410, "s": 3394, "text": " TELCOMA Global" }, { "code": null, "e": 3444, "s": 3410, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 3452, "s": 3444, "text": " Uplatz" }, { "code": null, "e": 3459, "s": 3452, "text": " Print" }, { "code": null, "e": 3470, "s": 3459, "text": " Add Notes" } ]
How to use SVG images in HTML5?
To use SVG images in HTML5, use <img> element or <svg>. To add SVG files, you can use <img> <object>, or <embed> element in HTML. Choose any one of them according to your requirement. Here’s how you can add SVG images. If the SVG is saved as a file, it can be directly used as an SVG image: You can try to run the following code to use SVG Images Live Demo <!DOCTYPE html> <html> <head> <style> #svgelem { position: relative; left: 50%; -webkit-transform: translateX(-20%); -ms-transform: translateX(-20%); transform: translateX(-20%); } </style> <title>HTML5 SVG Image</title> </head> <body> <h2 align="center">HTML5 SVG Image</h2> <img src="https://www.tutorialspoint.com/html5/src/svg/extensions/imagelib/smiley.svg" alt="smile" height="100px" width="100px" /> </body> </html>
[ { "code": null, "e": 1246, "s": 1062, "text": "To use SVG images in HTML5, use <img> element or <svg>. To add SVG files, you can use <img> <object>, or <embed> element in HTML. Choose any one of them according to your requirement." }, { "code": null, "e": 1353, "s": 1246, "text": "Here’s how you can add SVG images. If the SVG is saved as a file, it can be directly used as an SVG image:" }, { "code": null, "e": 1409, "s": 1353, "text": "You can try to run the following code to use SVG Images" }, { "code": null, "e": 1419, "s": 1409, "text": "Live Demo" }, { "code": null, "e": 1962, "s": 1419, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n #svgelem {\n position: relative;\n left: 50%;\n -webkit-transform: translateX(-20%);\n -ms-transform: translateX(-20%);\n transform: translateX(-20%);\n }\n </style>\n <title>HTML5 SVG Image</title>\n </head>\n <body>\n <h2 align=\"center\">HTML5 SVG Image</h2>\n <img src=\"https://www.tutorialspoint.com/html5/src/svg/extensions/imagelib/smiley.svg\" alt=\"smile\" height=\"100px\" width=\"100px\" />\n </body>\n</html>" } ]
C# Tutorial (C Sharp)
C# (C-Sharp) is a programming language developed by Microsoft that runs on the .NET Framework. C# is used to develop web apps, desktop apps, mobile apps, games and much more. Our "Try it Yourself" tool makes it easy to learn C#. You can edit C# code and view the result in your browser. using System; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } } Try it Yourself » Click on the "Run example" button to see how it works. We recommend reading this tutorial, in the sequence listed in the left menu. Insert the missing part of the code below to output "Hello World!". static void (string[] args) { .("Hello World!"); } 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: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 96, "s": 0, "text": "C# (C-Sharp) is a programming language developed by Microsoft that runs on the .NET \nFramework." }, { "code": null, "e": 177, "s": 96, "text": "C# is used to develop web apps, desktop apps, mobile apps, games and much \nmore." }, { "code": null, "e": 289, "s": 177, "text": "Our \"Try it Yourself\" tool makes it easy to learn C#. You can edit C# code and view the result in your browser." }, { "code": null, "e": 446, "s": 289, "text": "using System;\n\nnamespace HelloWorld\n{\n class Program\n {\n static void Main(string[] args)\n {\n Console.WriteLine(\"Hello World!\"); \n }\n }\n}" }, { "code": null, "e": 466, "s": 446, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 521, "s": 466, "text": "Click on the \"Run example\" button to see how it works." }, { "code": null, "e": 598, "s": 521, "text": "We recommend reading this tutorial, in the sequence listed in the left menu." }, { "code": null, "e": 666, "s": 598, "text": "Insert the missing part of the code below to output \"Hello World!\"." }, { "code": null, "e": 724, "s": 666, "text": "static void (string[] args)\n{\n .(\"Hello World!\"); \n}\n" }, { "code": null, "e": 743, "s": 724, "text": "Start the Exercise" }, { "code": null, "e": 831, "s": 743, "text": "Learn by examples! This tutorial supplements all explanations with clarifying examples." }, { "code": null, "e": 851, "s": 831, "text": "See All C# Examples" }, { "code": null, "e": 955, "s": 851, "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": 969, "s": 955, "text": "Start C# Quiz" }, { "code": null, "e": 1011, "s": 969, "text": "Get certified by completing the C# course" }, { "code": null, "e": 1044, "s": 1011, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1086, "s": 1044, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1193, "s": 1086, "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": 1212, "s": 1193, "text": "[email protected]" } ]
Return type of getchar(), fgetc() and getc() in C
Details about getchar(), fgetc() and getc() functions in C programming are given as follows − The getchar() function obtains a character from stdin. It returns the character that was read in the form of an integer or EOF if an error occurs. A program that demonstrates this is as follows − Live Demo #include <stdio.h> int main (){ int i; printf("Enter a character: "); i = getchar(); printf("\nThe character entered is: "); putchar(i); return(0); } The output of the above program is as follows − Enter a character: G The character entered is: G Now let us understand the above program. The value obtained using the getchar() function is stored in i which is an integer variable. Then the character value is displayed using putchar(). The code snippet that shows this is as follows − int i; printf("Enter a character: "); i = getchar(); printf("\nThe character entered is: "); putchar(i); The fgetc() function obtains a character from a file stream which is a pointer to a FILE object. This function returns the character that was read in the form of an integer or EOF if an error occurs. A program that demonstrates this is as follows − Live Demo #include <stdio.h> int main (){ FILE *fp; fp = fopen("file.txt", "w"); fprintf(fp, "Apple"); fclose(fp); int i; fp = fopen("file.txt","r"); if(fp == NULL){ perror("Error in opening file"); return(-1); } while((i=fgetc(fp))!=EOF){ printf("%c",i); } fclose(fp); return(0); } The output of the above program is as follows − Apple Now let us understand the above program. First, the file is created and the data "Apple" is stored inside it. Then the file is closed. The code snippet that shows this is as follows − FILE *fp; fp = fopen("file.txt", "w"); fprintf(fp, "Apple"); fclose(fp); The file is opened again in reading mode. If fp is NULL then error message is displayed. Otherwise the contents of the file are displayed using the fgetc() function. The code snippet that shows this is as follows − fp = fopen("file.txt","r"); if(fp == NULL){ perror("Error in opening file"); return(-1); } while((i=fgetc(fp))!=EOF){ printf("%c",i); } fclose(fp); The getc() function obtains a character from the stream that is specified. It returns the character that was read in the form of an integer or EOF if an error occurs. A program that demonstrates this is as follows − Live Demo #include <stdio.h> int main (){ int i; printf("Enter a character: "); i = getc(stdin); printf("\nThe character entered is: "); putchar(i); return(0); } The output of the above program is as follows − Enter a character: K The character entered is: K Now let us understand the above program. The getc() function obtains a character from the stream stdin as specified. This value is stored in int variable i. Then the character value is displayed using putchar(). The code snippet that shows this is as follows − int i; printf("Enter a character: "); i = getc(stdin); printf("\nThe character entered is: "); putchar(i);
[ { "code": null, "e": 1156, "s": 1062, "text": "Details about getchar(), fgetc() and getc() functions in C programming are given as follows −" }, { "code": null, "e": 1303, "s": 1156, "text": "The getchar() function obtains a character from stdin. It returns the character that was read in the form of an integer or EOF if an error occurs." }, { "code": null, "e": 1352, "s": 1303, "text": "A program that demonstrates this is as follows −" }, { "code": null, "e": 1363, "s": 1352, "text": " Live Demo" }, { "code": null, "e": 1535, "s": 1363, "text": "#include <stdio.h>\n\nint main (){\n int i;\n\n printf(\"Enter a character: \");\n i = getchar();\n\n printf(\"\\nThe character entered is: \");\n putchar(i);\n\n return(0);\n}" }, { "code": null, "e": 1583, "s": 1535, "text": "The output of the above program is as follows −" }, { "code": null, "e": 1632, "s": 1583, "text": "Enter a character: G\nThe character entered is: G" }, { "code": null, "e": 1673, "s": 1632, "text": "Now let us understand the above program." }, { "code": null, "e": 1870, "s": 1673, "text": "The value obtained using the getchar() function is stored in i which is an integer variable. Then the character value is displayed using putchar(). The code snippet that shows this is as follows −" }, { "code": null, "e": 1977, "s": 1870, "text": "int i;\n\nprintf(\"Enter a character: \");\ni = getchar();\n\nprintf(\"\\nThe character entered is: \");\nputchar(i);" }, { "code": null, "e": 2177, "s": 1977, "text": "The fgetc() function obtains a character from a file stream which is a pointer to a FILE object. This function returns the character that was read in the form of an integer or EOF if an error occurs." }, { "code": null, "e": 2226, "s": 2177, "text": "A program that demonstrates this is as follows −" }, { "code": null, "e": 2237, "s": 2226, "text": " Live Demo" }, { "code": null, "e": 2573, "s": 2237, "text": "#include <stdio.h>\n\nint main (){\n FILE *fp;\n fp = fopen(\"file.txt\", \"w\");\n fprintf(fp, \"Apple\");\n fclose(fp);\n\n int i;\n\n fp = fopen(\"file.txt\",\"r\");\n \n if(fp == NULL){\n perror(\"Error in opening file\");\n return(-1);\n }\n\n while((i=fgetc(fp))!=EOF){\n printf(\"%c\",i);\n }\n\n fclose(fp);\n return(0);\n}" }, { "code": null, "e": 2621, "s": 2573, "text": "The output of the above program is as follows −" }, { "code": null, "e": 2627, "s": 2621, "text": "Apple" }, { "code": null, "e": 2668, "s": 2627, "text": "Now let us understand the above program." }, { "code": null, "e": 2811, "s": 2668, "text": "First, the file is created and the data \"Apple\" is stored inside it. Then the file is closed. The code snippet that shows this is as follows −" }, { "code": null, "e": 2884, "s": 2811, "text": "FILE *fp;\nfp = fopen(\"file.txt\", \"w\");\nfprintf(fp, \"Apple\");\nfclose(fp);" }, { "code": null, "e": 3099, "s": 2884, "text": "The file is opened again in reading mode. If fp is NULL then error message is displayed. Otherwise the contents of the file are displayed using the fgetc() function. The code snippet that shows this is as follows −" }, { "code": null, "e": 3259, "s": 3099, "text": "fp = fopen(\"file.txt\",\"r\");\n\nif(fp == NULL){\n perror(\"Error in opening file\");\n return(-1);\n}\n\nwhile((i=fgetc(fp))!=EOF){\n printf(\"%c\",i);\n}\n\nfclose(fp);" }, { "code": null, "e": 3426, "s": 3259, "text": "The getc() function obtains a character from the stream that is specified. It returns the character that was read in the form of an integer or EOF if an error occurs." }, { "code": null, "e": 3475, "s": 3426, "text": "A program that demonstrates this is as follows −" }, { "code": null, "e": 3486, "s": 3475, "text": " Live Demo" }, { "code": null, "e": 3660, "s": 3486, "text": "#include <stdio.h>\n\nint main (){\n int i;\n\n printf(\"Enter a character: \");\n i = getc(stdin);\n\n printf(\"\\nThe character entered is: \");\n putchar(i);\n\n return(0);\n}" }, { "code": null, "e": 3708, "s": 3660, "text": "The output of the above program is as follows −" }, { "code": null, "e": 3757, "s": 3708, "text": "Enter a character: K\nThe character entered is: K" }, { "code": null, "e": 3798, "s": 3757, "text": "Now let us understand the above program." }, { "code": null, "e": 4018, "s": 3798, "text": "The getc() function obtains a character from the stream stdin as specified. This value is stored in int variable i. Then the character value is displayed using putchar(). The code snippet that shows this is as follows −" }, { "code": null, "e": 4127, "s": 4018, "text": "int i;\n\nprintf(\"Enter a character: \");\ni = getc(stdin);\n\nprintf(\"\\nThe character entered is: \");\nputchar(i);" } ]
How to declare variables in JavaScript?
Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container. Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows. <script> <!-- var money; var name; //--> </script> You can also declare multiple variables with the same var keyword as follows − <script> <!-- var money, name; //--> </script> Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or at a later point in time when you need that variable.
[ { "code": null, "e": 1276, "s": 1062, "text": "Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container." }, { "code": null, "e": 1404, "s": 1276, "text": "Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows." }, { "code": null, "e": 1473, "s": 1404, "text": "<script>\n <!--\n var money;\n var name;\n //-->\n</script>" }, { "code": null, "e": 1552, "s": 1473, "text": "You can also declare multiple variables with the same var keyword as follows −" }, { "code": null, "e": 1611, "s": 1552, "text": "<script>\n <!--\n var money, name;\n //-->\n</script>" }, { "code": null, "e": 1801, "s": 1611, "text": "Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or at a later point in time when you need that variable." } ]
Fetch records from interval of past 3 days from current date in MySQL and add the corresponding records
Let us first create a table − mysql> create table DemoTable ( ProductAmount int, PurchaseDate datetime ); Query OK, 0 rows affected (0.94 sec) Note − Let’s say the current date is 2010-09-15. Insert some records in the table using insert command − mysql> insert into DemoTable values(567,'2019-09-10'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values(1347,'2019-09-14'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(2033,'2019-09-13'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values(1256,'2019-09-11'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(1000,'2019-09-16'); Query OK, 1 row affected (0.14 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +---------------+---------------------+ | ProductAmount | PurchaseDate | +---------------+---------------------+ | 567 | 2019-09-10 00 :00 :00 | | 1347 | 2019-09-14 00:00 :00 | | 2033 | 2019-09-13 00:00 :00 | | 1256 | 2019-09-11 00:00 :00 | | 1000 | 2019-09-16 00:00 :00 | +---------------+---------------------+ 5 rows in set (0.00 sec) Following is the query to use now() function in MySQL query − mysql> select sum(ProductAmount) from DemoTable where PurchaseDate > NOW()- interval 3 day; This will produce the following output − +--------------------+ | sum(ProductAmount) | +--------------------+ | 4380 | +--------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1211, "s": 1092, "text": "mysql> create table DemoTable\n(\n ProductAmount int,\n PurchaseDate datetime\n);\nQuery OK, 0 rows affected (0.94 sec)" }, { "code": null, "e": 1260, "s": 1211, "text": "Note − Let’s say the current date is 2010-09-15." }, { "code": null, "e": 1316, "s": 1260, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1775, "s": 1316, "text": "mysql> insert into DemoTable values(567,'2019-09-10');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable values(1347,'2019-09-14');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable values(2033,'2019-09-13');\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into DemoTable values(1256,'2019-09-11');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable values(1000,'2019-09-16');\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 1835, "s": 1775, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1866, "s": 1835, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1907, "s": 1866, "text": "This will produce the following output −" }, { "code": null, "e": 2298, "s": 1907, "text": "+---------------+---------------------+\n| ProductAmount | PurchaseDate |\n+---------------+---------------------+\n| 567 | 2019-09-10 00 :00 :00 |\n| 1347 | 2019-09-14 00:00 :00 |\n| 2033 | 2019-09-13 00:00 :00 |\n| 1256 | 2019-09-11 00:00 :00 |\n| 1000 | 2019-09-16 00:00 :00 |\n+---------------+---------------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2360, "s": 2298, "text": "Following is the query to use now() function in MySQL query −" }, { "code": null, "e": 2455, "s": 2360, "text": "mysql> select sum(ProductAmount) from DemoTable\n where PurchaseDate > NOW()- interval 3 day;" }, { "code": null, "e": 2496, "s": 2455, "text": "This will produce the following output −" }, { "code": null, "e": 2635, "s": 2496, "text": "+--------------------+\n| sum(ProductAmount) |\n+--------------------+\n| 4380 |\n+--------------------+\n1 row in set (0.00 sec)" } ]
Python - Searching Algorithms
Searching is a very basic necessity when you store data in different data structures. The simplest approach is to go across every element in the data structure and match it with the value you are searching for.This is known as Linear search. It is inefficient and rarely used, but creating a program for it gives an idea about how we can implement some advanced search algorithms. In this type of search, a sequential search is made over all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data structure. def linear_search(values, search_for): search_at = 0 search_res = False # Match the value with each data element while search_at < len(values) and search_res is False: if values[search_at] == search_for: search_res = True else: search_at = search_at + 1 return search_res l = [64, 34, 25, 12, 22, 11, 90] print(linear_search(l, 12)) print(linear_search(l, 91)) When the above code is executed, it produces the following result − True False This search algorithm works on the probing position of the required value. For this algorithm to work properly, the data collection should be in a sorted form and equally distributed.Initially, the probe position is the position of the middle most item of the collection.If a match occurs, then the index of the item is returned.If the middle item is greater than the item, then the probe position is again calculated in the sub-array to the right of the middle item. Otherwise, the item is searched in the subarray to the left of the middle item. This process continues on the sub-array as well until the size of subarray reduces to zero. There is a specific formula to calculate the middle position which is indicated in the program below − def intpolsearch(values,x ): idx0 = 0 idxn = (len(values) - 1) while idx0 <= idxn and x >= values[idx0] and x <= values[idxn]: # Find the mid point mid = idx0 +\ int(((float(idxn - idx0)/( values[idxn] - values[idx0])) * ( x - values[idx0]))) # Compare the value at mid point with search value if values[mid] == x: return "Found "+str(x)+" at index "+str(mid) if values[mid] < x: idx0 = mid + 1 return "Searched element not in the list" l = [2, 6, 11, 19, 27, 31, 45, 121] print(intpolsearch(l, 2)) When the above code is executed, it produces the following result − Found 2 at index 0 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2708, "s": 2327, "text": "Searching is a very basic necessity when you store data in different data structures. The simplest approach is to go across every element in the data structure and match it with the value you are searching for.This is known as Linear search. It is inefficient and rarely used, but creating a program for it gives an idea about how we can implement some advanced search algorithms." }, { "code": null, "e": 2939, "s": 2708, "text": "In this type of search, a sequential search is made over all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data structure." }, { "code": null, "e": 3343, "s": 2939, "text": "def linear_search(values, search_for):\n search_at = 0\n search_res = False\n# Match the value with each data element\t\n while search_at < len(values) and search_res is False:\n if values[search_at] == search_for:\n search_res = True\n else:\n search_at = search_at + 1\n return search_res\nl = [64, 34, 25, 12, 22, 11, 90]\nprint(linear_search(l, 12))\nprint(linear_search(l, 91))" }, { "code": null, "e": 3411, "s": 3343, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 3423, "s": 3411, "text": "True\nFalse\n" }, { "code": null, "e": 4063, "s": 3423, "text": "This search algorithm works on the probing position of the required value. For this algorithm to work properly, the data collection should be in a sorted form and equally distributed.Initially, the probe position is the position of the middle most item of the collection.If a match occurs, then the index of the item is returned.If the middle item is greater than the item, then the probe position is again calculated in the sub-array to the right of the middle item. Otherwise, the item is searched in the subarray to the left of the middle item. This process continues on the sub-array as well until the size of subarray reduces to zero." }, { "code": null, "e": 4166, "s": 4063, "text": "There is a specific formula to calculate the middle position which is indicated in the program below −" }, { "code": null, "e": 4710, "s": 4166, "text": "def intpolsearch(values,x ):\n idx0 = 0\n idxn = (len(values) - 1)\n while idx0 <= idxn and x >= values[idx0] and x <= values[idxn]:\n# Find the mid point\n\tmid = idx0 +\\\n int(((float(idxn - idx0)/( values[idxn] - values[idx0]))\n * ( x - values[idx0])))\n# Compare the value at mid point with search value \n if values[mid] == x:\n return \"Found \"+str(x)+\" at index \"+str(mid)\n if values[mid] < x:\n idx0 = mid + 1\n return \"Searched element not in the list\"\n\nl = [2, 6, 11, 19, 27, 31, 45, 121]\nprint(intpolsearch(l, 2))" }, { "code": null, "e": 4778, "s": 4710, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 4798, "s": 4778, "text": "Found 2 at index 0\n" }, { "code": null, "e": 4835, "s": 4798, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4851, "s": 4835, "text": " Malhar Lathkar" }, { "code": null, "e": 4884, "s": 4851, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 4903, "s": 4884, "text": " Arnab Chakraborty" }, { "code": null, "e": 4938, "s": 4903, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 4960, "s": 4938, "text": " In28Minutes Official" }, { "code": null, "e": 4994, "s": 4960, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 5022, "s": 4994, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5057, "s": 5022, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 5071, "s": 5057, "text": " Lets Kode It" }, { "code": null, "e": 5104, "s": 5071, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 5121, "s": 5104, "text": " Abhilash Nelson" }, { "code": null, "e": 5128, "s": 5121, "text": " Print" }, { "code": null, "e": 5139, "s": 5128, "text": " Add Notes" } ]
Bottom-left to upward-right Traversal in a Binary Tree - GeeksforGeeks
15 Sep, 2021 Given a Binary Tree, the task is to print the Bottom-left to Upward-right Traversal of the given Binary Tree i.e., the level order traversal having level as Bottom-left to Upward-right node. Examples: Input: Below is the given Tree: Output: 2 7 2 5 6 5 11 4 9Explanation: Level 1: 2 7 2 (going upwards from bottom left to right to root) Level 2: 5 6 5 (right from each node in layer 1/or bottom left to upwards right in this layer)Level 3: 11 4 9 (right from each node in layer 2/or bottom left to upwards right in this layer) Input: 1 2 3 4 5 6 7Output: 4 2 1 5 6 3 2ExplanationLayer 1: 4 2 1 (going upwards from bottom left to right to root)Layer 2: 5 6 3 (right from each node in layer 1/or bottom left to upwards right in this layer)Layer 3: 2 (right from each node in layer 2/or bottom left to upwards right in this layer) Approach: The idea is to use the Breadth-First Search technique. Follow the steps needed to solve this problem: Initialize a layer in a binary tree. It is a list of nodes starting from the bottom-left most node next to the previous layer and ends with the upper-right most node next to the previous layer. Create a stack to stores all nodes in every layer. Initialize a queue to maintain “roots” in each layer, a root in a layer is a node from which one may go downwards using left children only. Push the root node of the first layer (the tree root) in the queue. Define an indicator (say lyr_root) a node expected at the end of a layer which is the current layer head, a layer head is the first node in a layer. Traverse until the queue is nonempty and do the following:Get a layer root from the front of the queueIf this layer root is the layer head of a new layer, then, pop every element in the stack i.e., of the previous layer element, and print it.Traverse the layer from the upper-right to the bottom-left and for each element, if it has a right child, then check if the traversed node is the layer head or not. If found to be true then, change the expected indicator to indicate to the next layer head.Push the right child to the root in the queue.Push the traversed node in the stack. Get a layer root from the front of the queue If this layer root is the layer head of a new layer, then, pop every element in the stack i.e., of the previous layer element, and print it. Traverse the layer from the upper-right to the bottom-left and for each element, if it has a right child, then check if the traversed node is the layer head or not. If found to be true then, change the expected indicator to indicate to the next layer head. Push the right child to the root in the queue. Push the traversed node in the stack. After traversing all the layers, the final layer may still be in the stack, so we need to pop every element from it and print it. Below is the implementation of the above approach: C++ // C++ program for the above approach#include <bits/stdc++.h>#include <iostream>using namespace std; // Node Structurestypedef struct Node { int data; Node* left; Node* right;} Node; // Function to add the new Node in// the Binary TreeNode* newNode(int data){ Node* n; // Create a new Node n = new Node(); n->data = data; n->right = NULL; n->left = NULL; return n;} // Function to traverse the tree in the// order of bottom left to the upward// right ordervector<int>leftBottomTopRightTraversal(Node* root){ // Stores the data of the node vector<int> rr; // Stores every element in each layer stack<int> r; // Stores the roots in the layers queue<Node*> roots; // Push the layer head of the // first layer roots.push(root); // Define the first layer head // as the tree root Node* lyr_root = root; // Traverse all layers while (!roots.empty()) { // get current layer root Node* n = roots.front(); // Pop element from roots roots.pop(); if (lyr_root == n) { // Layer root was also // the layer head while (!r.empty()) { rr.push_back(r.top()); // Pop every element // from the stack r.pop(); } } while (n) { if (n->right) { // Current traversed node // has right child then // this root is next layer if (n == lyr_root) { lyr_root = n->right; } // Push the right child // to layer roots queue roots.push(n->right); } // Push node to the // layer stack r.push(n->data); n = n->left; } } // Insert all remaining elements // for the traversal while (!r.empty()) { // After all of the layer // roots traversed check the // final layer in stack rr.push_back(r.top()); r.pop(); } // Return the traversal of nodes return rr;} // Function that builds the binary tree// from the given stringNode* buildBinaryTree(char* t){ Node* root = NULL; // Using queue to build tree queue<Node**> q; int data = 0; // Stores the status of last // node to be ignored or not bool ignore_last = false; while (*t != '\0') { int d = *t - '0'; // If the current character // is a digits then form the // number of it if (d >= 0 && d <= 9) { data *= 10; data += d; ignore_last = false; } // If the current character // is N then it is the // NULL node else if (*t == 'N') { data = 0; q.pop(); ignore_last = true; } // If space occured then // add the number formed else if (*t == ' ') { // If last is ignored if (!ignore_last) { // If root node is not NULL if (root) { Node** p = q.front(); q.pop(); if (p != NULL) { *p = newNode(data); q.push(&((*p)->left)); q.push(&((*p)->right)); } } // Else create a new // root node else { root = newNode(data); q.push(&(root->left)); q.push(&(root->right)); } data = 0; } } // Increment t t++; } // Return the root node of the tree return root;} // Driver Codeint main(){ // Given order of nodes char T[] = "2 7 5 2 6 N 9 N N 5 11 4 N"; // Builds the Binary Tree Node* root = buildBinaryTree(T); // Function Call vector<int> result = leftBottomTopRightTraversal(root); // Print the final traversal for (int i = 0; i < result.size(); ++i) { cout << result[i] << " "; } return 0;} 2 7 2 5 6 5 11 4 9 Time Complexity: O(N)Auxiliary Space: O(N) adnanirshad158 Binary Tree Tree Traversals Stack Tree Stack Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Real-time application of Data Structures Reverse individual words ZigZag Tree Traversal Sort a stack using a temporary stack Evaluation of Prefix Expressions Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Binary Tree | Set 3 (Types of Binary Tree)
[ { "code": null, "e": 24297, "s": 24269, "text": "\n15 Sep, 2021" }, { "code": null, "e": 24488, "s": 24297, "text": "Given a Binary Tree, the task is to print the Bottom-left to Upward-right Traversal of the given Binary Tree i.e., the level order traversal having level as Bottom-left to Upward-right node." }, { "code": null, "e": 24498, "s": 24488, "text": "Examples:" }, { "code": null, "e": 24530, "s": 24498, "text": "Input: Below is the given Tree:" }, { "code": null, "e": 24570, "s": 24530, "text": "Output: 2 7 2 5 6 5 11 4 9Explanation: " }, { "code": null, "e": 24826, "s": 24570, "text": "Level 1: 2 7 2 (going upwards from bottom left to right to root) Level 2: 5 6 5 (right from each node in layer 1/or bottom left to upwards right in this layer)Level 3: 11 4 9 (right from each node in layer 2/or bottom left to upwards right in this layer) " }, { "code": null, "e": 25127, "s": 24826, "text": "Input: 1 2 3 4 5 6 7Output: 4 2 1 5 6 3 2ExplanationLayer 1: 4 2 1 (going upwards from bottom left to right to root)Layer 2: 5 6 3 (right from each node in layer 1/or bottom left to upwards right in this layer)Layer 3: 2 (right from each node in layer 2/or bottom left to upwards right in this layer)" }, { "code": null, "e": 25239, "s": 25127, "text": "Approach: The idea is to use the Breadth-First Search technique. Follow the steps needed to solve this problem:" }, { "code": null, "e": 25433, "s": 25239, "text": "Initialize a layer in a binary tree. It is a list of nodes starting from the bottom-left most node next to the previous layer and ends with the upper-right most node next to the previous layer." }, { "code": null, "e": 25484, "s": 25433, "text": "Create a stack to stores all nodes in every layer." }, { "code": null, "e": 25624, "s": 25484, "text": "Initialize a queue to maintain “roots” in each layer, a root in a layer is a node from which one may go downwards using left children only." }, { "code": null, "e": 25692, "s": 25624, "text": "Push the root node of the first layer (the tree root) in the queue." }, { "code": null, "e": 25841, "s": 25692, "text": "Define an indicator (say lyr_root) a node expected at the end of a layer which is the current layer head, a layer head is the first node in a layer." }, { "code": null, "e": 26423, "s": 25841, "text": "Traverse until the queue is nonempty and do the following:Get a layer root from the front of the queueIf this layer root is the layer head of a new layer, then, pop every element in the stack i.e., of the previous layer element, and print it.Traverse the layer from the upper-right to the bottom-left and for each element, if it has a right child, then check if the traversed node is the layer head or not. If found to be true then, change the expected indicator to indicate to the next layer head.Push the right child to the root in the queue.Push the traversed node in the stack." }, { "code": null, "e": 26468, "s": 26423, "text": "Get a layer root from the front of the queue" }, { "code": null, "e": 26609, "s": 26468, "text": "If this layer root is the layer head of a new layer, then, pop every element in the stack i.e., of the previous layer element, and print it." }, { "code": null, "e": 26866, "s": 26609, "text": "Traverse the layer from the upper-right to the bottom-left and for each element, if it has a right child, then check if the traversed node is the layer head or not. If found to be true then, change the expected indicator to indicate to the next layer head." }, { "code": null, "e": 26913, "s": 26866, "text": "Push the right child to the root in the queue." }, { "code": null, "e": 26951, "s": 26913, "text": "Push the traversed node in the stack." }, { "code": null, "e": 27081, "s": 26951, "text": "After traversing all the layers, the final layer may still be in the stack, so we need to pop every element from it and print it." }, { "code": null, "e": 27132, "s": 27081, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27136, "s": 27132, "text": "C++" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>#include <iostream>using namespace std; // Node Structurestypedef struct Node { int data; Node* left; Node* right;} Node; // Function to add the new Node in// the Binary TreeNode* newNode(int data){ Node* n; // Create a new Node n = new Node(); n->data = data; n->right = NULL; n->left = NULL; return n;} // Function to traverse the tree in the// order of bottom left to the upward// right ordervector<int>leftBottomTopRightTraversal(Node* root){ // Stores the data of the node vector<int> rr; // Stores every element in each layer stack<int> r; // Stores the roots in the layers queue<Node*> roots; // Push the layer head of the // first layer roots.push(root); // Define the first layer head // as the tree root Node* lyr_root = root; // Traverse all layers while (!roots.empty()) { // get current layer root Node* n = roots.front(); // Pop element from roots roots.pop(); if (lyr_root == n) { // Layer root was also // the layer head while (!r.empty()) { rr.push_back(r.top()); // Pop every element // from the stack r.pop(); } } while (n) { if (n->right) { // Current traversed node // has right child then // this root is next layer if (n == lyr_root) { lyr_root = n->right; } // Push the right child // to layer roots queue roots.push(n->right); } // Push node to the // layer stack r.push(n->data); n = n->left; } } // Insert all remaining elements // for the traversal while (!r.empty()) { // After all of the layer // roots traversed check the // final layer in stack rr.push_back(r.top()); r.pop(); } // Return the traversal of nodes return rr;} // Function that builds the binary tree// from the given stringNode* buildBinaryTree(char* t){ Node* root = NULL; // Using queue to build tree queue<Node**> q; int data = 0; // Stores the status of last // node to be ignored or not bool ignore_last = false; while (*t != '\\0') { int d = *t - '0'; // If the current character // is a digits then form the // number of it if (d >= 0 && d <= 9) { data *= 10; data += d; ignore_last = false; } // If the current character // is N then it is the // NULL node else if (*t == 'N') { data = 0; q.pop(); ignore_last = true; } // If space occured then // add the number formed else if (*t == ' ') { // If last is ignored if (!ignore_last) { // If root node is not NULL if (root) { Node** p = q.front(); q.pop(); if (p != NULL) { *p = newNode(data); q.push(&((*p)->left)); q.push(&((*p)->right)); } } // Else create a new // root node else { root = newNode(data); q.push(&(root->left)); q.push(&(root->right)); } data = 0; } } // Increment t t++; } // Return the root node of the tree return root;} // Driver Codeint main(){ // Given order of nodes char T[] = \"2 7 5 2 6 N 9 N N 5 11 4 N\"; // Builds the Binary Tree Node* root = buildBinaryTree(T); // Function Call vector<int> result = leftBottomTopRightTraversal(root); // Print the final traversal for (int i = 0; i < result.size(); ++i) { cout << result[i] << \" \"; } return 0;}", "e": 31269, "s": 27136, "text": null }, { "code": null, "e": 31291, "s": 31272, "text": "2 7 2 5 6 5 11 4 9" }, { "code": null, "e": 31338, "s": 31295, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 31355, "s": 31340, "text": "adnanirshad158" }, { "code": null, "e": 31367, "s": 31355, "text": "Binary Tree" }, { "code": null, "e": 31383, "s": 31367, "text": "Tree Traversals" }, { "code": null, "e": 31389, "s": 31383, "text": "Stack" }, { "code": null, "e": 31394, "s": 31389, "text": "Tree" }, { "code": null, "e": 31400, "s": 31394, "text": "Stack" }, { "code": null, "e": 31405, "s": 31400, "text": "Tree" }, { "code": null, "e": 31503, "s": 31405, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31512, "s": 31503, "text": "Comments" }, { "code": null, "e": 31525, "s": 31512, "text": "Old Comments" }, { "code": null, "e": 31566, "s": 31525, "text": "Real-time application of Data Structures" }, { "code": null, "e": 31591, "s": 31566, "text": "Reverse individual words" }, { "code": null, "e": 31613, "s": 31591, "text": "ZigZag Tree Traversal" }, { "code": null, "e": 31650, "s": 31613, "text": "Sort a stack using a temporary stack" }, { "code": null, "e": 31683, "s": 31650, "text": "Evaluation of Prefix Expressions" }, { "code": null, "e": 31733, "s": 31683, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 31768, "s": 31733, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 31802, "s": 31768, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 31831, "s": 31802, "text": "AVL Tree | Set 1 (Insertion)" } ]
Sum of the series 2^0 + 2^1 + 2^2 +...+ 2^n in C++
In this problem, we are given a number n which defines the n-th term of the series 2^0, 2^1, 2^2, ..., 2^n. Our task is to create a program to find the sum of the series 2^0 + 2^1 + 2^2 +...+ 2^n. Input n=6 Output Explanation sum = 2^0 + 2^1 + 2^2 + 2^3 + 2^4 + 2^5 + 2^6 sum = 1 + 2 + 4 + 8 + 16 + 32 + 64 = 127 A simple solution to the problem is by using the loop. Finding the 2^i, for each value from 0 to n and add it to the sum variable. Initialize sum = 0 Step 1: Iterate from i = 0 to n. And follow : Step 1.1: Update sum, sum += 2^i. Step 2: Print sum. Program to illustrate the working of our solution, Live Demo #include <iostream> #include <math.h> using namespace std; int calcSeriesSum(int n) { int sum = 0; for (int i = 0; i <= n; i++) sum += pow(2, i); return sum; } int main() { int n = 11; cout<<"Sum of the series 2^0 + 2^1 + 2^2 +...+ 2^"<<n<<" is "<<calcSeriesSum(n); return 0; } Sum of the series 2^0 + 2^1 + 2^2 +...+ 2^11 is 4095 This is not the most effective method to solve this problem as it uses a loop that makes its time complexity of the order O(n). A more effective solution, we will use the mathematical formula for the sum. It is given by 2^(n+1) - 1 Program to illustrate the working of our solution, Live Demo #include <iostream> #include <math.h> using namespace std; int calcSeriesSum(int n) { return ( (pow(2, (n+1)) - 1) ); } int main() { int n = 11; cout<<"Sum of the series 2^0 + 2^1 + 2^2 +...+ 2^"<<n<<" is "<<calcSeriesSum(n); return 0; } Sum of the series 2^0 + 2^1 + 2^2 +...+ 2^11 is 4095
[ { "code": null, "e": 1259, "s": 1062, "text": "In this problem, we are given a number n which defines the n-th term of the series 2^0, 2^1, 2^2, ..., 2^n. Our task is to create a program to find the sum of the series 2^0 + 2^1 + 2^2 +...+ 2^n." }, { "code": null, "e": 1265, "s": 1259, "text": "Input" }, { "code": null, "e": 1269, "s": 1265, "text": "n=6" }, { "code": null, "e": 1277, "s": 1269, "text": "Output " }, { "code": null, "e": 1290, "s": 1277, "text": "Explanation " }, { "code": null, "e": 1377, "s": 1290, "text": "sum = 2^0 + 2^1 + 2^2 + 2^3 + 2^4 + 2^5 + 2^6\nsum = 1 + 2 + 4 + 8 + 16 + 32 + 64 = 127" }, { "code": null, "e": 1508, "s": 1377, "text": "A simple solution to the problem is by using the loop. Finding the 2^i, for each value from 0 to n and add it to the sum variable." }, { "code": null, "e": 1626, "s": 1508, "text": "Initialize sum = 0\nStep 1: Iterate from i = 0 to n. And follow :\nStep 1.1: Update sum, sum += 2^i.\nStep 2: Print sum." }, { "code": null, "e": 1677, "s": 1626, "text": "Program to illustrate the working of our solution," }, { "code": null, "e": 1688, "s": 1677, "text": " Live Demo" }, { "code": null, "e": 1987, "s": 1688, "text": "#include <iostream>\n#include <math.h>\nusing namespace std;\nint calcSeriesSum(int n) {\n int sum = 0;\n for (int i = 0; i <= n; i++)\n sum += pow(2, i);\n return sum;\n}\nint main() {\n int n = 11;\n cout<<\"Sum of the series 2^0 + 2^1 + 2^2 +...+ 2^\"<<n<<\" is \"<<calcSeriesSum(n);\n return 0;\n}" }, { "code": null, "e": 2040, "s": 1987, "text": "Sum of the series 2^0 + 2^1 + 2^2 +...+ 2^11 is 4095" }, { "code": null, "e": 2168, "s": 2040, "text": "This is not the most effective method to solve this problem as it uses a loop that makes its time complexity of the order O(n)." }, { "code": null, "e": 2260, "s": 2168, "text": "A more effective solution, we will use the mathematical formula for the sum. It is given by" }, { "code": null, "e": 2273, "s": 2260, "text": " 2^(n+1) - 1" }, { "code": null, "e": 2324, "s": 2273, "text": "Program to illustrate the working of our solution," }, { "code": null, "e": 2334, "s": 2324, "text": "Live Demo" }, { "code": null, "e": 2584, "s": 2334, "text": "#include <iostream>\n#include <math.h>\nusing namespace std;\nint calcSeriesSum(int n) {\n return ( (pow(2, (n+1)) - 1) );\n}\nint main() {\n int n = 11;\n cout<<\"Sum of the series 2^0 + 2^1 + 2^2 +...+ 2^\"<<n<<\" is \"<<calcSeriesSum(n);\n return 0;\n}" }, { "code": null, "e": 2637, "s": 2584, "text": "Sum of the series 2^0 + 2^1 + 2^2 +...+ 2^11 is 4095" } ]
Minimum sum of subarray | Practice | GeeksforGeeks
Given an array of integers of size N, for all, i's [1, N], the task is to find the minimum subarray sum in the subarray [i, N]. Input: 1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. 2. The first line of each test case contains a single integer N. 3. The second line contains N space-separated positive integers represents array. Output: For each test case, print N space-separated integers Constraints: 1. 1 <= T <= 10 2. 1 <= N <= 100000 3. -10000 <= arr[i] <= 10000 Example: Input: 2 3 3 -1 -2 5 5 -3 -2 9 4 Output: -3 -3 -2 -5 -5 -2 4 4 Explanation: Test case 1: 1. i = 1, subarray is [3, -1, -2], all possible subarrays are [3], [-1], [-2], [3, -1], [-1, -2], [3, -1, -2]. Minnimum sum is -3 [-1, -2]. 2. i = 2, subarray is [-1, -2], all possible subarrays are [-1], [-2], [-1, -2]. Minnimum sum is -3 [-1, -2]. 3. i = 3, subarray is [-2], all possible subarrays are [-2]. Minnimum sum is -2[-2]. +1 aloksinghbais022 months ago C++ solution having time complexity as O(N) and space complexity as O(N) is as follows :- Execution Time :- 0.0 / 2.2 sec #include <bits/stdc++.h>#define ll long long int#define ld long double#define FIO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);#define mod ((int)1e9+7)#define inf 1e18#define hell 1e15#define p_b push_backusing namespace std; vector<int> helper(int arr[],int n){ vector<int> ans(n); int min_so_far = arr[n-1]; int curr_so_far = arr[n-1]; ans[n-1] = min_so_far; for(int i = n-2; i >= 0; i--){ curr_so_far = min(arr[i],curr_so_far+arr[i]); min_so_far = min(min_so_far,curr_so_far); ans[i] = min_so_far; } return (ans);} int main(int args,char **ch){ FIO short t; cin>>t; while(t--){ int n; cin>>n; int arr[n]; for(int i = 0; i < n; i++) cin>>arr[i]; vector<int> ans = helper(arr,n); for(auto x: ans) cout<<x<<" "; cout<<endl; } return (0);} 0 imranwahid4 months ago Easy C++ solution using Kadane's algorithm 0 20je01176 months ago # include <bits/stdc++.h> # define int long long using namespace std; int find(int start,vector<int>&v){int curr_min=INT_MAX;int min_so_far=INT_MAX;for(int i=start;i<v.size();++i){if(curr_min>0){ curr_min=v[i];}else{ curr_min+=v[i];}min_so_far=min(min_so_far,curr_min);}return min_so_far;}int32_t main(){ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);//this is for finding minimum subarray sum of an arrayint t;cin>>t;while(t--){ int n;cin>>n; vector<int>v(n); for(int i=0;i<n;++i){ cin>>v[i]; }vector<int>result(n);for(int i=0;i<n;++i){ result[i]=find(i,v);}for(auto val:result){ cout<<val<<" ";}cout<<endl;} return 0;} +1 jasmeenkaursyali7 months ago #include <iostream>using namespace std; int main() {int t;cin>>t;while(t--){ int n; cin>>n; int arr[n]; for(int i=0;i<n;i++) cin>>arr[i]; for(int j=0;j<n;j++){ int mi=100000; int curr=0; for(int i=j;i<n;i++){ if(arr[i]+curr<=arr[i]) curr = arr[i]+curr; else curr = arr[i]; mi = min(curr,mi); } cout<<mi<<" "; } cout<<endl; }return 0;} 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": 366, "s": 238, "text": "Given an array of integers of size N, for all, i's [1, N], the task is to find the minimum subarray sum in the subarray [i, N]." }, { "code": null, "e": 841, "s": 366, "text": "Input: \n1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.\n2. The first line of each test case contains a single integer N.\n3. The second line contains N space-separated positive integers represents array.\n\nOutput: For each test case, print N space-separated integers\n\nConstraints:\n1. 1 <= T <= 10\n2. 1 <= N <= 100000\n3. -10000 <= arr[i] <= 10000\n\nExample:\nInput:\n2\n3\n3 -1 -2\n5\n5 -3 -2 9 4" }, { "code": null, "e": 872, "s": 841, "text": "Output:\n-3 -3 -2\n-5 -5 -2 4 4 " }, { "code": null, "e": 899, "s": 872, "text": "Explanation:\nTest case 1: " }, { "code": null, "e": 1234, "s": 899, "text": "1. i = 1, subarray is [3, -1, -2], all possible subarrays are [3], [-1], [-2], [3, -1], [-1, -2], [3, -1, -2]. Minnimum sum is -3 [-1, -2].\n2. i = 2, subarray is [-1, -2], all possible subarrays are [-1], [-2], [-1, -2]. Minnimum sum is -3 [-1, -2].\n3. i = 3, subarray is [-2], all possible subarrays are [-2]. Minnimum sum is -2[-2]." }, { "code": null, "e": 1237, "s": 1234, "text": "+1" }, { "code": null, "e": 1265, "s": 1237, "text": "aloksinghbais022 months ago" }, { "code": null, "e": 1356, "s": 1265, "text": "C++ solution having time complexity as O(N) and space complexity as O(N) is as follows :- " }, { "code": null, "e": 1390, "s": 1358, "text": "Execution Time :- 0.0 / 2.2 sec" }, { "code": null, "e": 1629, "s": 1392, "text": "#include <bits/stdc++.h>#define ll long long int#define ld long double#define FIO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);#define mod ((int)1e9+7)#define inf 1e18#define hell 1e15#define p_b push_backusing namespace std;" }, { "code": null, "e": 1953, "s": 1629, "text": "vector<int> helper(int arr[],int n){ vector<int> ans(n); int min_so_far = arr[n-1]; int curr_so_far = arr[n-1]; ans[n-1] = min_so_far; for(int i = n-2; i >= 0; i--){ curr_so_far = min(arr[i],curr_so_far+arr[i]); min_so_far = min(min_so_far,curr_so_far); ans[i] = min_so_far; } return (ans);}" }, { "code": null, "e": 2233, "s": 1953, "text": "int main(int args,char **ch){ FIO short t; cin>>t; while(t--){ int n; cin>>n; int arr[n]; for(int i = 0; i < n; i++) cin>>arr[i]; vector<int> ans = helper(arr,n); for(auto x: ans) cout<<x<<\" \"; cout<<endl; } return (0);}" }, { "code": null, "e": 2235, "s": 2233, "text": "0" }, { "code": null, "e": 2258, "s": 2235, "text": "imranwahid4 months ago" }, { "code": null, "e": 2301, "s": 2258, "text": "Easy C++ solution using Kadane's algorithm" }, { "code": null, "e": 2303, "s": 2301, "text": "0" }, { "code": null, "e": 2324, "s": 2303, "text": "20je01176 months ago" }, { "code": null, "e": 2972, "s": 2324, "text": "# include <bits/stdc++.h> # define int long long using namespace std; int find(int start,vector<int>&v){int curr_min=INT_MAX;int min_so_far=INT_MAX;for(int i=start;i<v.size();++i){if(curr_min>0){ curr_min=v[i];}else{ curr_min+=v[i];}min_so_far=min(min_so_far,curr_min);}return min_so_far;}int32_t main(){ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);//this is for finding minimum subarray sum of an arrayint t;cin>>t;while(t--){ int n;cin>>n; vector<int>v(n); for(int i=0;i<n;++i){ cin>>v[i]; }vector<int>result(n);for(int i=0;i<n;++i){ result[i]=find(i,v);}for(auto val:result){ cout<<val<<\" \";}cout<<endl;}" }, { "code": null, "e": 2983, "s": 2972, "text": "return 0;}" }, { "code": null, "e": 2986, "s": 2983, "text": "+1" }, { "code": null, "e": 3015, "s": 2986, "text": "jasmeenkaursyali7 months ago" }, { "code": null, "e": 3055, "s": 3015, "text": "#include <iostream>using namespace std;" }, { "code": null, "e": 3502, "s": 3055, "text": "int main() {int t;cin>>t;while(t--){ int n; cin>>n; int arr[n]; for(int i=0;i<n;i++) cin>>arr[i]; for(int j=0;j<n;j++){ int mi=100000; int curr=0; for(int i=j;i<n;i++){ if(arr[i]+curr<=arr[i]) curr = arr[i]+curr; else curr = arr[i]; mi = min(curr,mi); } cout<<mi<<\" \"; } cout<<endl; }return 0;}" }, { "code": null, "e": 3648, "s": 3502, "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": 3684, "s": 3648, "text": " Login to access your submissions. " }, { "code": null, "e": 3694, "s": 3684, "text": "\nProblem\n" }, { "code": null, "e": 3704, "s": 3694, "text": "\nContest\n" }, { "code": null, "e": 3767, "s": 3704, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3915, "s": 3767, "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": 4123, "s": 3915, "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": 4229, "s": 4123, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
First strictly greater element in a sorted array in Java - GeeksforGeeks
16 Jun, 2021 Given a sorted array and a target value, find the first element that is strictly greater than given element. Examples: Input : arr[] = {1, 2, 3, 5, 8, 12} Target = 5 Output : 4 (Index of 8) Input : {1, 2, 3, 5, 8, 12} Target = 8 Output : 5 (Index of 12) Input : {1, 2, 3, 5, 8, 12} Target = 15 Output : -1 A simple solution is to linearly traverse given array and find first element that is strictly greater. If no such element exists, then return -1. An efficient solution is to use Binary Search. In a general binary search, we are looking for a value which appears in the array. Sometimes, however, we need to find the first element which is either greater than a target. To see that this algorithm is correct, consider each comparison being made. If we find an element that’s no greater than the target element, then it and everything below it can’t possibly match, so there’s no need to search that region. We can thus search the right half. If we find an element that is larger than the element in question, then anything after it must also be larger, so they can’t be the first element that’s bigger and so we don’t need to search them. The middle element is thus the last possible place it could be. Note that on each iteration we drop off at least half the remaining elements from consideration. If the top branch executes, then the elements in the range [low, (low + high) / 2] are all discarded, causing us to lose floor((low + high) / 2) – low + 1 >= (low + high) / 2 – low = (high – low) / 2 elements. If the bottom branch executes, then the elements in the range [(low + high) / 2 + 1, high] are all discarded. This loses us high – floor(low + high) / 2 + 1 >= high – (low + high) / 2 = (high – low) / 2 elements. Consequently, we’ll end up finding the first element greater than the target in O(lg n) iterations of this process. C++ Java Python3 C# PHP Javascript // C++ program to find first element that// is strictly greater than given target.#include <iostream>using namespace std; int next(int arr[], int target, int end){ int start = 0; int ans = -1; while (start <= end) { int mid = (start + end) / 2; // Move to right side if target is // greater. if (arr[mid] <= target) start = mid + 1; // Move left side. else { ans = mid; end = mid - 1; } } return ans;} // Driver codeint main(){ int arr[] = {1, 2, 3, 5, 8, 12}; int n = sizeof(arr) / sizeof(arr[0]); cout << next(arr, 8, n); return 0;} // This code is contributed by sanjeev2552 // Java program to find first element that// is strictly greater than given target. class GfG { private static int next(int[] arr, int target) { int start = 0, end = arr.length - 1; int ans = -1; while (start <= end) { int mid = (start + end) / 2; // Move to right side if target is // greater. if (arr[mid] <= target) { start = mid + 1; } // Move left side. else { ans = mid; end = mid - 1; } } return ans; } // Driver code public static void main(String[] args) { int[] arr = { 1, 2, 3, 5, 8, 12 }; System.out.println(next(arr, 8)); }} # Python program to find first element that# is strictly greater than given target. def next(arr, target): start = 0; end = len(arr) - 1; ans = -1; while (start <= end): mid = (start + end) // 2; # Move to right side if target is # greater. if (arr[mid] <= target): start = mid + 1; # Move left side. else: ans = mid; end = mid - 1; return ans; # Driver codeif __name__ == '__main__': arr = [1, 2, 3, 5, 8, 12]; print(next(arr, 8)); # This code is contributed by 29AjayKumar // C# program to find first element that// is strictly greater than given target.using System; class GfG{ private static int next(int[] arr, int target) { int start = 0, end = arr.Length - 1; int ans = -1; while (start <= end) { int mid = (start + end) / 2; // Move to right side if target is // greater. if (arr[mid] <= target) { start = mid + 1; } // Move left side. else { ans = mid; end = mid - 1; } } return ans; } // Driver code public static void Main() { int[] arr = { 1, 2, 3, 5, 8, 12 }; Console.WriteLine(next(arr, 8)); }} // This code is contributed by Code_Mech <?php// PHP program to find first element that// is strictly greater than given target.function next0($arr, $target){ $start = 0; $end = sizeof($arr) - 1; $ans = -1; while ($start <= $end) { $mid = (int)(($start + $end) / 2); // Move to right side if target is // greater. if ($arr[$mid] <= $target) { $start = $mid + 1; } // Move left side. else { $ans = $mid; $end = $mid - 1; } } return $ans;} // Driver code{ $arr = array( 1, 2, 3, 5, 8, 12 ); echo(next0($arr, 8));} // This code is contributed by Code_Mech?> <script> // Javascript program to find first element that// is strictly greater than given target.function next(arr, target){ let start = 0, end = arr.length - 1; let ans = -1; while (start <= end) { let mid = parseInt((start + end) / 2, 10); // Move to right side if target is // greater. if (arr[mid] <= target) { start = mid + 1; } // Move left side. else { ans = mid; end = mid - 1; } } return ans;} // Driver codelet arr = [ 1, 2, 3, 5, 8, 12 ];document.write(next(arr, 8)); // This code is contributed by decode2207 </script> 5 Code_Mech sanjeev2552 29AjayKumar decode2207 Arrays Divide and Conquer Java Programs Searching Arrays Searching Divide and Conquer Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Multidimensional Arrays in Java Introduction to Arrays Python | Using 2D arrays/lists the right way Linked List vs Array Merge Sort QuickSort Maximum and minimum of an array using minimum number of comparisons Program for Tower of Hanoi Divide and Conquer Algorithm | Introduction
[ { "code": null, "e": 24290, "s": 24262, "text": "\n16 Jun, 2021" }, { "code": null, "e": 24399, "s": 24290, "text": "Given a sorted array and a target value, find the first element that is strictly greater than given element." }, { "code": null, "e": 24410, "s": 24399, "text": "Examples: " }, { "code": null, "e": 24626, "s": 24410, "text": "Input : arr[] = {1, 2, 3, 5, 8, 12} \n Target = 5\nOutput : 4 (Index of 8)\n\nInput : {1, 2, 3, 5, 8, 12} \n Target = 8\nOutput : 5 (Index of 12)\n\nInput : {1, 2, 3, 5, 8, 12} \n Target = 15\nOutput : -1" }, { "code": null, "e": 24772, "s": 24626, "text": "A simple solution is to linearly traverse given array and find first element that is strictly greater. If no such element exists, then return -1." }, { "code": null, "e": 24995, "s": 24772, "text": "An efficient solution is to use Binary Search. In a general binary search, we are looking for a value which appears in the array. Sometimes, however, we need to find the first element which is either greater than a target." }, { "code": null, "e": 25528, "s": 24995, "text": "To see that this algorithm is correct, consider each comparison being made. If we find an element that’s no greater than the target element, then it and everything below it can’t possibly match, so there’s no need to search that region. We can thus search the right half. If we find an element that is larger than the element in question, then anything after it must also be larger, so they can’t be the first element that’s bigger and so we don’t need to search them. The middle element is thus the last possible place it could be." }, { "code": null, "e": 25835, "s": 25528, "text": "Note that on each iteration we drop off at least half the remaining elements from consideration. If the top branch executes, then the elements in the range [low, (low + high) / 2] are all discarded, causing us to lose floor((low + high) / 2) – low + 1 >= (low + high) / 2 – low = (high – low) / 2 elements." }, { "code": null, "e": 26048, "s": 25835, "text": "If the bottom branch executes, then the elements in the range [(low + high) / 2 + 1, high] are all discarded. This loses us high – floor(low + high) / 2 + 1 >= high – (low + high) / 2 = (high – low) / 2 elements." }, { "code": null, "e": 26165, "s": 26048, "text": "Consequently, we’ll end up finding the first element greater than the target in O(lg n) iterations of this process. " }, { "code": null, "e": 26169, "s": 26165, "text": "C++" }, { "code": null, "e": 26174, "s": 26169, "text": "Java" }, { "code": null, "e": 26182, "s": 26174, "text": "Python3" }, { "code": null, "e": 26185, "s": 26182, "text": "C#" }, { "code": null, "e": 26189, "s": 26185, "text": "PHP" }, { "code": null, "e": 26200, "s": 26189, "text": "Javascript" }, { "code": "// C++ program to find first element that// is strictly greater than given target.#include <iostream>using namespace std; int next(int arr[], int target, int end){ int start = 0; int ans = -1; while (start <= end) { int mid = (start + end) / 2; // Move to right side if target is // greater. if (arr[mid] <= target) start = mid + 1; // Move left side. else { ans = mid; end = mid - 1; } } return ans;} // Driver codeint main(){ int arr[] = {1, 2, 3, 5, 8, 12}; int n = sizeof(arr) / sizeof(arr[0]); cout << next(arr, 8, n); return 0;} // This code is contributed by sanjeev2552", "e": 26901, "s": 26200, "text": null }, { "code": "// Java program to find first element that// is strictly greater than given target. class GfG { private static int next(int[] arr, int target) { int start = 0, end = arr.length - 1; int ans = -1; while (start <= end) { int mid = (start + end) / 2; // Move to right side if target is // greater. if (arr[mid] <= target) { start = mid + 1; } // Move left side. else { ans = mid; end = mid - 1; } } return ans; } // Driver code public static void main(String[] args) { int[] arr = { 1, 2, 3, 5, 8, 12 }; System.out.println(next(arr, 8)); }}", "e": 27656, "s": 26901, "text": null }, { "code": "# Python program to find first element that# is strictly greater than given target. def next(arr, target): start = 0; end = len(arr) - 1; ans = -1; while (start <= end): mid = (start + end) // 2; # Move to right side if target is # greater. if (arr[mid] <= target): start = mid + 1; # Move left side. else: ans = mid; end = mid - 1; return ans; # Driver codeif __name__ == '__main__': arr = [1, 2, 3, 5, 8, 12]; print(next(arr, 8)); # This code is contributed by 29AjayKumar", "e": 28231, "s": 27656, "text": null }, { "code": "// C# program to find first element that// is strictly greater than given target.using System; class GfG{ private static int next(int[] arr, int target) { int start = 0, end = arr.Length - 1; int ans = -1; while (start <= end) { int mid = (start + end) / 2; // Move to right side if target is // greater. if (arr[mid] <= target) { start = mid + 1; } // Move left side. else { ans = mid; end = mid - 1; } } return ans; } // Driver code public static void Main() { int[] arr = { 1, 2, 3, 5, 8, 12 }; Console.WriteLine(next(arr, 8)); }} // This code is contributed by Code_Mech", "e": 29042, "s": 28231, "text": null }, { "code": "<?php// PHP program to find first element that// is strictly greater than given target.function next0($arr, $target){ $start = 0; $end = sizeof($arr) - 1; $ans = -1; while ($start <= $end) { $mid = (int)(($start + $end) / 2); // Move to right side if target is // greater. if ($arr[$mid] <= $target) { $start = $mid + 1; } // Move left side. else { $ans = $mid; $end = $mid - 1; } } return $ans;} // Driver code{ $arr = array( 1, 2, 3, 5, 8, 12 ); echo(next0($arr, 8));} // This code is contributed by Code_Mech?>", "e": 29687, "s": 29042, "text": null }, { "code": "<script> // Javascript program to find first element that// is strictly greater than given target.function next(arr, target){ let start = 0, end = arr.length - 1; let ans = -1; while (start <= end) { let mid = parseInt((start + end) / 2, 10); // Move to right side if target is // greater. if (arr[mid] <= target) { start = mid + 1; } // Move left side. else { ans = mid; end = mid - 1; } } return ans;} // Driver codelet arr = [ 1, 2, 3, 5, 8, 12 ];document.write(next(arr, 8)); // This code is contributed by decode2207 </script>", "e": 30347, "s": 29687, "text": null }, { "code": null, "e": 30349, "s": 30347, "text": "5" }, { "code": null, "e": 30361, "s": 30351, "text": "Code_Mech" }, { "code": null, "e": 30373, "s": 30361, "text": "sanjeev2552" }, { "code": null, "e": 30385, "s": 30373, "text": "29AjayKumar" }, { "code": null, "e": 30396, "s": 30385, "text": "decode2207" }, { "code": null, "e": 30403, "s": 30396, "text": "Arrays" }, { "code": null, "e": 30422, "s": 30403, "text": "Divide and Conquer" }, { "code": null, "e": 30436, "s": 30422, "text": "Java Programs" }, { "code": null, "e": 30446, "s": 30436, "text": "Searching" }, { "code": null, "e": 30453, "s": 30446, "text": "Arrays" }, { "code": null, "e": 30463, "s": 30453, "text": "Searching" }, { "code": null, "e": 30482, "s": 30463, "text": "Divide and Conquer" }, { "code": null, "e": 30580, "s": 30482, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30648, "s": 30580, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 30680, "s": 30648, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 30703, "s": 30680, "text": "Introduction to Arrays" }, { "code": null, "e": 30748, "s": 30703, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 30769, "s": 30748, "text": "Linked List vs Array" }, { "code": null, "e": 30780, "s": 30769, "text": "Merge Sort" }, { "code": null, "e": 30790, "s": 30780, "text": "QuickSort" }, { "code": null, "e": 30858, "s": 30790, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 30885, "s": 30858, "text": "Program for Tower of Hanoi" } ]
BabylonJS - Box
In this section, we will learn how to add box to the scene we created. To create box, following is the syntax. var box = BABYLON.Mesh.CreateBox("box", 6.0, scene, false, BABYLON.Mesh.DEFAULTSIDE); The following are the different parameters to add box − Name − The Name to be given to the box; for example, “box”. Name − The Name to be given to the box; for example, “box”. Size of the box − The size of the box. Size of the box − The size of the box. Scene − The scene is where the box will be attached. Scene − The scene is where the box will be attached. Boolean value − False is the default value. Boolean value − False is the default value. BABYLON.Mesh.DEFAULTSIDE − This is used for orientation. BABYLON.Mesh.DEFAULTSIDE − This is used for orientation. The last 2 parameters are optional. <!doctype html> <html> <head> <meta charset = "utf-8"> <title>BabylonJs - Basic Element-Creating Scene</title> <script src = "babylon.js"></script> <style> canvas {width: 100%; height: 100%;} </style> </head> <body> <canvas id = "renderCanvas"></canvas> <script type = "text/javascript"> var canvas = document.getElementById("renderCanvas"); var engine = new BABYLON.Engine(canvas, true); var createScene = function() { var scene = new BABYLON.Scene(engine); scene.clearColor = new BABYLON.Color3(0, 1, 0); var camera = new BABYLON.ArcRotateCamera("Camera", 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene); camera.attachControl(canvas, true); var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene); light.intensity = 0.7; var pl = new BABYLON.PointLight("pl", BABYLON.Vector3.Zero(), scene); pl.diffuse = new BABYLON.Color3(1, 1, 1); pl.specular = new BABYLON.Color3(1, 1, 1); pl.intensity = 0.8; var box = BABYLON.Mesh.CreateBox("box", '3', scene); scene.registerBeforeRender(function() { pl.position = camera.position; }); return scene; }; var scene = createScene(); engine.runRenderLoop(function() { scene.render(); }); </script> </body> </html> Upon execution, the above code will generate the following output − Size refers to the height of the box on all sides. A size of 100 will basically be a box occupying full screen. The color given to the background scene is green. We are using the camera and light effect to move the screen onmouse cursor. This helps in the light effect too. Print Add Notes Bookmark this page
[ { "code": null, "e": 2254, "s": 2183, "text": "In this section, we will learn how to add box to the scene we created." }, { "code": null, "e": 2294, "s": 2254, "text": "To create box, following is the syntax." }, { "code": null, "e": 2381, "s": 2294, "text": "var box = BABYLON.Mesh.CreateBox(\"box\", 6.0, scene, false, BABYLON.Mesh.DEFAULTSIDE);\n" }, { "code": null, "e": 2437, "s": 2381, "text": "The following are the different parameters to add box −" }, { "code": null, "e": 2497, "s": 2437, "text": "Name − The Name to be given to the box; for example, “box”." }, { "code": null, "e": 2557, "s": 2497, "text": "Name − The Name to be given to the box; for example, “box”." }, { "code": null, "e": 2596, "s": 2557, "text": "Size of the box − The size of the box." }, { "code": null, "e": 2635, "s": 2596, "text": "Size of the box − The size of the box." }, { "code": null, "e": 2688, "s": 2635, "text": "Scene − The scene is where the box will be attached." }, { "code": null, "e": 2741, "s": 2688, "text": "Scene − The scene is where the box will be attached." }, { "code": null, "e": 2785, "s": 2741, "text": "Boolean value − False is the default value." }, { "code": null, "e": 2829, "s": 2785, "text": "Boolean value − False is the default value." }, { "code": null, "e": 2886, "s": 2829, "text": "BABYLON.Mesh.DEFAULTSIDE − This is used for orientation." }, { "code": null, "e": 2943, "s": 2886, "text": "BABYLON.Mesh.DEFAULTSIDE − This is used for orientation." }, { "code": null, "e": 2979, "s": 2943, "text": "The last 2 parameters are optional." }, { "code": null, "e": 4535, "s": 2979, "text": "<!doctype html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <title>BabylonJs - Basic Element-Creating Scene</title>\n <script src = \"babylon.js\"></script>\n <style>\n canvas {width: 100%; height: 100%;}\n </style>\n </head>\n\n <body>\n <canvas id = \"renderCanvas\"></canvas>\n <script type = \"text/javascript\">\n var canvas = document.getElementById(\"renderCanvas\");\n var engine = new BABYLON.Engine(canvas, true);\n var createScene = function() {\n var scene = new BABYLON.Scene(engine);\n scene.clearColor = new BABYLON.Color3(0, 1, 0);\n \n var camera = new BABYLON.ArcRotateCamera(\"Camera\", 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene);\n camera.attachControl(canvas, true);\n \n var light = new BABYLON.HemisphericLight(\"light1\", new BABYLON.Vector3(0, 1, 0), scene);\n light.intensity = 0.7;\t\n \n var pl = new BABYLON.PointLight(\"pl\", BABYLON.Vector3.Zero(), scene);\n pl.diffuse = new BABYLON.Color3(1, 1, 1);\n pl.specular = new BABYLON.Color3(1, 1, 1);\n pl.intensity = 0.8;\n \n var box = BABYLON.Mesh.CreateBox(\"box\", '3', scene);\t\n scene.registerBeforeRender(function() { \n pl.position = camera.position;\n });\n\n return scene;\n };\n var scene = createScene();\n engine.runRenderLoop(function() {\n scene.render();\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 4603, "s": 4535, "text": "Upon execution, the above code will generate the following output −" }, { "code": null, "e": 4877, "s": 4603, "text": "Size refers to the height of the box on all sides. A size of 100 will basically be a box occupying full screen. The color given to the background scene is green. We are using the camera and light effect to move the screen onmouse cursor. This helps in the light effect too." }, { "code": null, "e": 4884, "s": 4877, "text": " Print" }, { "code": null, "e": 4895, "s": 4884, "text": " Add Notes" } ]
How to create a left-right split pane in Java?
To create a left-right split pane, let us create two components and split them − JComponent one = new JLabel("Left Split"); one.setBorder(BorderFactory.createLineBorder(Color.MAGENTA)); JComponent two = new JLabel("Right Split"); two.setBorder(BorderFactory.createLineBorder(Color.ORANGE)); Now, we will split them. The two components will be split one to the left of the other using HORIZONTAL_PANE constant − JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, one, two); The following is an example to create a left-right split pane in Java − package my; import java.awt.Color; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JSplitPane; public class SwingDemo { public static void main(String[] a) { JFrame frame = new JFrame("SplitPane Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JComponent one = new JLabel("Left Split"); one.setBorder(BorderFactory.createLineBorder(Color.MAGENTA)); JComponent two = new JLabel("Right Split"); two.setBorder(BorderFactory.createLineBorder(Color.ORANGE)); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, one, two); frame.add(splitPane); frame.setSize(550, 250); frame.setVisible(true); } } This will produce the following output −
[ { "code": null, "e": 1143, "s": 1062, "text": "To create a left-right split pane, let us create two components and split them −" }, { "code": null, "e": 1353, "s": 1143, "text": "JComponent one = new JLabel(\"Left Split\");\none.setBorder(BorderFactory.createLineBorder(Color.MAGENTA));\nJComponent two = new JLabel(\"Right Split\");\ntwo.setBorder(BorderFactory.createLineBorder(Color.ORANGE));" }, { "code": null, "e": 1473, "s": 1353, "text": "Now, we will split them. The two components will be split one to the left of the other using HORIZONTAL_PANE constant −" }, { "code": null, "e": 1551, "s": 1473, "text": "JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, one, two);" }, { "code": null, "e": 1623, "s": 1551, "text": "The following is an example to create a left-right split pane in Java −" }, { "code": null, "e": 2399, "s": 1623, "text": "package my;\nimport java.awt.Color;\nimport javax.swing.BorderFactory;\nimport javax.swing.JComponent;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JSplitPane;\npublic class SwingDemo {\n public static void main(String[] a) {\n JFrame frame = new JFrame(\"SplitPane Demo\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n JComponent one = new JLabel(\"Left Split\");\n one.setBorder(BorderFactory.createLineBorder(Color.MAGENTA));\n JComponent two = new JLabel(\"Right Split\");\n two.setBorder(BorderFactory.createLineBorder(Color.ORANGE));\n JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, one, two);\n frame.add(splitPane);\n frame.setSize(550, 250);\n frame.setVisible(true);\n }\n}" }, { "code": null, "e": 2440, "s": 2399, "text": "This will produce the following output −" } ]
From scikit-learn to Spark ML. Taking a machine learning project from... | by Scott Johnson | Towards Data Science
In a previous post, I showed how to take a raw dataset of home sales and apply feature engineering techniques in Python with pandas. This allowed us to produce and improve predictions on home sale prices using scikit-learn machine learning models. But what happens when you want to take this sort of project to production, and instead of 10,000 data points perhaps there are tens or hundreds of gigabytes of data to train on? In this context, it is worth moving away from Python and scikit-learn toward a framework that can handle Big Data. Scala is a programming language based on the Java Virtual Machine (JVM) that uses functional programming techniques. There is an endless number of very sophisticated — and complicated — features in Scala that you can study, but getting started in basic Scala is not necessarily much harder than writing code in Java or even Python. Spark, on the other hand, is a framework based on Hadoop technologies which provides far more flexibility and usability than traditional Hadoop. It is probably the best tool for managing and analyzing large datasets, aka Big Data. The Spark ML framework allows developers to use Spark for data processing at scale while building machine learning models. Why not just do all of your data exploration and model training in Spark ML in the first place? You certainly could, but the truth is, Python is much easier for open-ended exploration especially if you are working in a Jupyter notebook. But having said that, Scala and Spark does not need to be that much more complicated than Python, as both pandas and Spark use DataFrame structures for data storage and manipulation. Our goal here is to show this simplicity rather than dwell on the difficulties. This post will not delve into the complexities of Scala, and it will assume some knowledge of the previous project. We are going to reproduce the results of the Python example, but we will not rehash all the reasons why we did them as they were explained previously. First, we will start by loading the dataset, exactly the same CSV file as before. val data_key = “housing_data_raw.csv”val df = spark.read.format(“csv”).option(“header”, “true”).option(“inferSchema”, “true”).load(s”./$data_key”) Next, we will remove the outliers that we identified in the previous post. import org.apache.spark.sql.DataFrameimport org.apache.spark.sql.functions._def drop_outliers(data: DataFrame) = { val drop = List(1618, 3405,10652, 954, 11136, 5103, 916, 10967, 7383, 1465, 8967, 8300, 4997) data.filter(not($"_c0".isin(drop:_*)))}val housing = drop_outliers(df) Now, we transform the lastsolddate field from text to a numeric value, which a regression model can train on. val housing_dateint = housing.withColumn("lastsolddateint", unix_timestamp($"lastsolddate","MM/dd/yy")) We also want to drop a number of columns that, for now anyway, we do not want to train on. def drop_geog(data: DataFrame, keep: List[String] = List()) = { val removeList = List("info","address","z_address","longitude","latitude","neighborhood", "lastsolddate","zipcode","zpid","usecode", "zestimate","zindexvalue") .filter(!keep.contains(_)) data.drop(removeList: _*)}val housing_dropgeo = drop_geog(housing_dateint) We perform this operation via a function in case we want to run the same code again later, which we will. Also note that the function has a keep parameter, in case we want to actually keep one of these values which we are removing. Which we will later. Note that most of this syntax is pretty close to Python with two major exceptions. First, Scala is a typed language. Variables actually do not have to be explicitly typed, but function parameters do. Second, you will see a line like: data.drop(removeList: _*) This means to drop everything in removeList from the data DataFrame. The _* is a wildcard type definition, just some necessary syntax to tell the Scala compiler how to get the job done. Now we want to split our data into a training and a test set. import org.apache.spark.ml.feature.VectorAssemblerdef train_test_split(data: DataFrame) = { val assembler = new VectorAssembler(). setInputCols(data.drop("lastsoldprice").columns). setOutputCol("features") val Array(train, test) = data.randomSplit(Array(0.8, 0.2), seed = 30) (assembler.transform(train), assembler.transform(test))}val (train, test) = train_test_split(housing_dropgeo) This is a bit tricky and requires some explanation. In scitkit-learn, you can take an entire pandas DataFrame and send that to the machine learning algorithm for training. Spark ML also has a DataFrame structure but model training overall is a bit pickier. You have to pack all of your features, from every column you want to train on, into a single column, by extracting each row of values and packing them into a Vector. That means that Spark ML trains off of only one column of data, which happens to be a data structure that actually contains multiple columns of data. Setting this up is not complicated once you have the code (see above) but it is an extra step you have to be conscious of. Creating one of these Vector columns is done using the VectorAssembler. We create the VectorAssembler, denoting that we want to use all of our feature columns (except our label/target column, lastsoldprice) then give the new Vector column a name, usually features. Then we use this new assembler to transform two DataFrames, the test and train datasets, and then return each of those transformed DataFrames as a tuple. Now, we can do some machine learning. Let’s start with Linear Regression. import org.apache.spark.ml.regression.LinearRegressionimport org.apache.spark.ml.evaluation.RegressionEvaluatorval lr = new LinearRegression() .setLabelCol("lastsoldprice") .setFeaturesCol("features")val lrModel = lr.fit(train)val predictions = lrModel.transform(test)val rmse = new RegressionEvaluator() .setLabelCol("lastsoldprice") .setPredictionCol("prediction") .setMetricName("rmse")val r2 = new RegressionEvaluator() .setLabelCol("lastsoldprice") .setPredictionCol("prediction") .setMetricName("r2")println("Root Mean Squared Error (RMSE) on test data = " + rmse.evaluate(predictions))println("R^2 on test data = " + r2.evaluate(predictions)) This should be pretty self-explanatory. Here is the output of the above code. Root Mean Squared Error (RMSE) on test data = 857356.2890199891R^2 on test data = 0.31933500943383086 That’s not great, but that’s not the point. The real win here is that we now have our data in a format where we can use Spark ML, so it is an easy step from here to trying out other algorithms. But first, we will recreate the above in a function that we can call using different algorithms. While we are at it, we will add an option for cross validation, so that we can test multiple different hyper-parameters and choose the best resulting model. Note that this step is not strictly necessary — the previous code can be easily refactored to use different algorithms by itself — but it is a better practice. import org.apache.spark.ml.Predictorimport org.apache.spark.ml.PredictionModelimport org.apache.spark.ml.linalg.Vectorimport org.apache.spark.ml.tuning.{CrossValidator, ParamGridBuilder}import org.apache.spark.ml.param.ParamMapdef train_eval[R <: Predictor[Vector, R, M], M <: PredictionModel[Vector, M]]( predictor: Predictor[Vector, R, M], paramMap: Array[ParamMap], train: DataFrame, test: DataFrame) = {val cv = new CrossValidator() .setEstimator( predictor .setLabelCol("lastsoldprice") .setFeaturesCol("features")) .setEvaluator(new RegressionEvaluator() .setLabelCol("lastsoldprice") .setPredictionCol("prediction") .setMetricName("rmse")) .setEstimatorParamMaps(paramMap) .setNumFolds(5) .setParallelism(2) val cvModel = cv.fit(train) val predictions = cvModel.transform(test) println("Root Mean Squared Error (RMSE) on test data = " + rmse.evaluate(predictions)) println("R^2 on test data = " + r2.evaluate(predictions)) val bestModel = cvModel.bestModel println(bestModel.extractParamMap) bestModel} Most of this should also be pretty self-explanatory — except the function definition, which is virtually impenetrable. That is this part: def train_eval[R <: Predictor[Vector, R, M], M <: PredictionModel[Vector, M]]( predictor: Predictor[Vector, R, M], paramMap: Array[ParamMap], train: DataFrame, test: DataFrame) = { Unfortunately, Spark ML does not seem to have a generic “Model” type where we could, for example, pass in an object that is a RegressionModel, and then our function could take that “Model” object and call the .fit method. That would allow us to avoid this mess. Instead, we have to come up with this complex definition just so we can create a method that accepts a generic “Model” type because the type is also dependent on the input format and an implicit evaluator type. Coming up with this sort of definition is pretty tricky — after looking around and some trial and error, I found that taking it directly from the Spark ML source code worked just fine. The good news is, once you write something like this, the callers do not need to really know about it or understand it (it is unlikely that they will, to be honest). Instead, this complex type definition allows callers to write really clean code like this: val lr = new LinearRegression()val lrParamMap = new ParamGridBuilder() .addGrid(lr.regParam, Array(10, 1, 0.1, 0.01, 0.001)) .addGrid(lr.elasticNetParam, Array(0.0, 0.5, 1.0)) .addGrid(lr.maxIter, Array(10000, 250000)) .build()train_eval(lr, lrParamMap, train, test) Now we are back to something simple: an algorithm (Linear Regression) and a grid of parameters for cross validation. The function call then becomes as simple as we saw in Python. It is literally the same code. Note that I even kept the embedded underscore syntax for train_eval and other variables. Typically in Scala and Java we would use camel case, ie trainEval, and that is what I would do when writing production code, but since this tutorial was originally written in Python it was worth maintaining some consistency for comparison. We will now look at a few other algorithms to see how they do. Note that Lasso and Ridge do not have explicit classes, as the elasticNetParam designates those two algorithms when set to 1 and 0, respectively. Decision Tree: import org.apache.spark.ml.regression.DecisionTreeRegressorval decisionTree = new DecisionTreeRegressor()val dtParamMap = new ParamGridBuilder().build()train_eval(decisionTree, dtParamMap, train, test) Results: Root Mean Squared Error (RMSE) on test data = 759685.8395738212R^2 on test data = 0.46558480196241925 Random Forest: import org.apache.spark.ml.regression.RandomForestRegressorval randomForest = new RandomForestRegressor()val rfParamMap = new ParamGridBuilder() .addGrid(randomForest.maxBins, Array(4, 16, 32, 64)) .addGrid(randomForest.numTrees, Array(1, 10, 100)) .addGrid(randomForest.maxDepth, Array(2, 5, 10)) .build()train_eval(randomForest, rfParamMap, train, test) Results: Root Mean Squared Error (RMSE) on test data = 647133.830611256R^2 on test data = 0.6122079099308858 Gradient Boost: import org.apache.spark.ml.regression.GBTRegressorval gradientBoost = new GBTRegressor()val gbParamMap = new ParamGridBuilder() .addGrid(randomForest.maxBins, Array(16, 32)) .addGrid(randomForest.numTrees, Array(5, 10, 100)) .addGrid(randomForest.maxDepth, Array(5, 10)) .addGrid(randomForest.minInfoGain, Array(0.0, 0.1, 0.5)) .build()train_eval(gradientBoost, gbParamMap, train, test) Results: Root Mean Squared Error (RMSE) on test data = 703037.6456894034R^2 on test data = 0.5423137139558296 While the exact results differ (especially for Linear Regression), we also see a similar trend of Random Forest and Gradient Boost working better than the simpler algorithms. Once again, we can improve our results by using better data. We do this by reincorporating the neighborhood data, but in a numerical format that the algorithms can use. We do this by changing categories like Mission and South Beach to columns of one and zeros using one-hot encoding. First, we rebuild or DataFrames with this data: val housing_neighborhood = drop_geog(housing_dateint, List("neighborhood")) Then we transform the data with one-hot encoding using a Pipeline: import org.apache.spark.ml.Pipelineimport org.apache.spark.ml.feature.OneHotEncoderEstimatorimport org.apache.spark.ml.feature.StringIndexerval indexer = new StringIndexer().setInputCol("neighborhood").setOutputCol("neighborhoodIndex")val encoder = new OneHotEncoderEstimator() .setInputCols(Array(indexer.getOutputCol)) .setOutputCols(Array("neighborhoodVector"))val pipeline = new Pipeline().setStages(Array(indexer, encoder))val housingEncoded = pipeline.fit(housing_neighborhood).transform(housing_neighborhood).drop("neighborhoodIndex").drop("neighborhood") First, we have to use a StringIndexer then we can get the results we want using the OneHotEncoderEstimator. Since these are two steps, we can put them together using a Pipeline of stages. Pipelines can be used for many multi-stage cleaning and modification operations, especially where you need to do these same stages over and over again, ie with evolving data sets that require retraining. It is not really necessary here, but it is worth showing because it can be so useful. Having updated our data, we can rerun our experiments exactly as before. We just pass in our new data (after creating training and testing sets): val (train_neighborhood, test_neighborhood) = train_test_split(housingEncoded) For example, for Linear Regression, we call exactly the same function with these new variables: train_eval(lr, lrParamMap, train_neighborhood, test_neighborhood) Results: Root Mean Squared Error (RMSE) on test data = 754869.9632285038R^2 on test data = 0.4723389619596349 This still is not great, but it is quite a bit better than previously. Now let’s look at the results for the other algorithms after passing in the transformed DataFrames. Decision Tree: Root Mean Squared Error (RMSE) on test data = 722171.2606321493R^2 on test data = 0.5170622654844328 Random Forest: Root Mean Squared Error (RMSE) on test data = 581188.983582857R^2 on test data = 0.6872153115815951 Gradient Boost: Root Mean Squared Error (RMSE) on test data = 636055.9695573623R^2 on test data = 0.6253709908240936 In each case, we see quite an improvement, and now we have a model and a training pipeline that we can take into production with larger data sets.
[ { "code": null, "e": 420, "s": 172, "text": "In a previous post, I showed how to take a raw dataset of home sales and apply feature engineering techniques in Python with pandas. This allowed us to produce and improve predictions on home sale prices using scikit-learn machine learning models." }, { "code": null, "e": 713, "s": 420, "text": "But what happens when you want to take this sort of project to production, and instead of 10,000 data points perhaps there are tens or hundreds of gigabytes of data to train on? In this context, it is worth moving away from Python and scikit-learn toward a framework that can handle Big Data." }, { "code": null, "e": 1045, "s": 713, "text": "Scala is a programming language based on the Java Virtual Machine (JVM) that uses functional programming techniques. There is an endless number of very sophisticated — and complicated — features in Scala that you can study, but getting started in basic Scala is not necessarily much harder than writing code in Java or even Python." }, { "code": null, "e": 1399, "s": 1045, "text": "Spark, on the other hand, is a framework based on Hadoop technologies which provides far more flexibility and usability than traditional Hadoop. It is probably the best tool for managing and analyzing large datasets, aka Big Data. The Spark ML framework allows developers to use Spark for data processing at scale while building machine learning models." }, { "code": null, "e": 1899, "s": 1399, "text": "Why not just do all of your data exploration and model training in Spark ML in the first place? You certainly could, but the truth is, Python is much easier for open-ended exploration especially if you are working in a Jupyter notebook. But having said that, Scala and Spark does not need to be that much more complicated than Python, as both pandas and Spark use DataFrame structures for data storage and manipulation. Our goal here is to show this simplicity rather than dwell on the difficulties." }, { "code": null, "e": 2166, "s": 1899, "text": "This post will not delve into the complexities of Scala, and it will assume some knowledge of the previous project. We are going to reproduce the results of the Python example, but we will not rehash all the reasons why we did them as they were explained previously." }, { "code": null, "e": 2248, "s": 2166, "text": "First, we will start by loading the dataset, exactly the same CSV file as before." }, { "code": null, "e": 2395, "s": 2248, "text": "val data_key = “housing_data_raw.csv”val df = spark.read.format(“csv”).option(“header”, “true”).option(“inferSchema”, “true”).load(s”./$data_key”)" }, { "code": null, "e": 2470, "s": 2395, "text": "Next, we will remove the outliers that we identified in the previous post." }, { "code": null, "e": 2760, "s": 2470, "text": "import org.apache.spark.sql.DataFrameimport org.apache.spark.sql.functions._def drop_outliers(data: DataFrame) = { val drop = List(1618, 3405,10652, 954, 11136, 5103, 916, 10967, 7383, 1465, 8967, 8300, 4997) data.filter(not($\"_c0\".isin(drop:_*)))}val housing = drop_outliers(df)" }, { "code": null, "e": 2870, "s": 2760, "text": "Now, we transform the lastsolddate field from text to a numeric value, which a regression model can train on." }, { "code": null, "e": 2974, "s": 2870, "text": "val housing_dateint = housing.withColumn(\"lastsolddateint\", unix_timestamp($\"lastsolddate\",\"MM/dd/yy\"))" }, { "code": null, "e": 3065, "s": 2974, "text": "We also want to drop a number of columns that, for now anyway, we do not want to train on." }, { "code": null, "e": 3429, "s": 3065, "text": "def drop_geog(data: DataFrame, keep: List[String] = List()) = { val removeList = List(\"info\",\"address\",\"z_address\",\"longitude\",\"latitude\",\"neighborhood\", \"lastsolddate\",\"zipcode\",\"zpid\",\"usecode\", \"zestimate\",\"zindexvalue\") .filter(!keep.contains(_)) data.drop(removeList: _*)}val housing_dropgeo = drop_geog(housing_dateint)" }, { "code": null, "e": 3682, "s": 3429, "text": "We perform this operation via a function in case we want to run the same code again later, which we will. Also note that the function has a keep parameter, in case we want to actually keep one of these values which we are removing. Which we will later." }, { "code": null, "e": 3916, "s": 3682, "text": "Note that most of this syntax is pretty close to Python with two major exceptions. First, Scala is a typed language. Variables actually do not have to be explicitly typed, but function parameters do. Second, you will see a line like:" }, { "code": null, "e": 3942, "s": 3916, "text": "data.drop(removeList: _*)" }, { "code": null, "e": 4128, "s": 3942, "text": "This means to drop everything in removeList from the data DataFrame. The _* is a wildcard type definition, just some necessary syntax to tell the Scala compiler how to get the job done." }, { "code": null, "e": 4190, "s": 4128, "text": "Now we want to split our data into a training and a test set." }, { "code": null, "e": 4605, "s": 4190, "text": "import org.apache.spark.ml.feature.VectorAssemblerdef train_test_split(data: DataFrame) = { val assembler = new VectorAssembler(). setInputCols(data.drop(\"lastsoldprice\").columns). setOutputCol(\"features\") val Array(train, test) = data.randomSplit(Array(0.8, 0.2), seed = 30) (assembler.transform(train), assembler.transform(test))}val (train, test) = train_test_split(housing_dropgeo)" }, { "code": null, "e": 4657, "s": 4605, "text": "This is a bit tricky and requires some explanation." }, { "code": null, "e": 5301, "s": 4657, "text": "In scitkit-learn, you can take an entire pandas DataFrame and send that to the machine learning algorithm for training. Spark ML also has a DataFrame structure but model training overall is a bit pickier. You have to pack all of your features, from every column you want to train on, into a single column, by extracting each row of values and packing them into a Vector. That means that Spark ML trains off of only one column of data, which happens to be a data structure that actually contains multiple columns of data. Setting this up is not complicated once you have the code (see above) but it is an extra step you have to be conscious of." }, { "code": null, "e": 5720, "s": 5301, "text": "Creating one of these Vector columns is done using the VectorAssembler. We create the VectorAssembler, denoting that we want to use all of our feature columns (except our label/target column, lastsoldprice) then give the new Vector column a name, usually features. Then we use this new assembler to transform two DataFrames, the test and train datasets, and then return each of those transformed DataFrames as a tuple." }, { "code": null, "e": 5794, "s": 5720, "text": "Now, we can do some machine learning. Let’s start with Linear Regression." }, { "code": null, "e": 6456, "s": 5794, "text": "import org.apache.spark.ml.regression.LinearRegressionimport org.apache.spark.ml.evaluation.RegressionEvaluatorval lr = new LinearRegression() .setLabelCol(\"lastsoldprice\") .setFeaturesCol(\"features\")val lrModel = lr.fit(train)val predictions = lrModel.transform(test)val rmse = new RegressionEvaluator() .setLabelCol(\"lastsoldprice\") .setPredictionCol(\"prediction\") .setMetricName(\"rmse\")val r2 = new RegressionEvaluator() .setLabelCol(\"lastsoldprice\") .setPredictionCol(\"prediction\") .setMetricName(\"r2\")println(\"Root Mean Squared Error (RMSE) on test data = \" + rmse.evaluate(predictions))println(\"R^2 on test data = \" + r2.evaluate(predictions))" }, { "code": null, "e": 6534, "s": 6456, "text": "This should be pretty self-explanatory. Here is the output of the above code." }, { "code": null, "e": 6636, "s": 6534, "text": "Root Mean Squared Error (RMSE) on test data = 857356.2890199891R^2 on test data = 0.31933500943383086" }, { "code": null, "e": 7244, "s": 6636, "text": "That’s not great, but that’s not the point. The real win here is that we now have our data in a format where we can use Spark ML, so it is an easy step from here to trying out other algorithms. But first, we will recreate the above in a function that we can call using different algorithms. While we are at it, we will add an option for cross validation, so that we can test multiple different hyper-parameters and choose the best resulting model. Note that this step is not strictly necessary — the previous code can be easily refactored to use different algorithms by itself — but it is a better practice." }, { "code": null, "e": 8408, "s": 7244, "text": "import org.apache.spark.ml.Predictorimport org.apache.spark.ml.PredictionModelimport org.apache.spark.ml.linalg.Vectorimport org.apache.spark.ml.tuning.{CrossValidator, ParamGridBuilder}import org.apache.spark.ml.param.ParamMapdef train_eval[R <: Predictor[Vector, R, M], M <: PredictionModel[Vector, M]]( predictor: Predictor[Vector, R, M], paramMap: Array[ParamMap], train: DataFrame, test: DataFrame) = {val cv = new CrossValidator() .setEstimator( predictor .setLabelCol(\"lastsoldprice\") .setFeaturesCol(\"features\")) .setEvaluator(new RegressionEvaluator() .setLabelCol(\"lastsoldprice\") .setPredictionCol(\"prediction\") .setMetricName(\"rmse\")) .setEstimatorParamMaps(paramMap) .setNumFolds(5) .setParallelism(2) val cvModel = cv.fit(train) val predictions = cvModel.transform(test) println(\"Root Mean Squared Error (RMSE) on test data = \" + rmse.evaluate(predictions)) println(\"R^2 on test data = \" + r2.evaluate(predictions)) val bestModel = cvModel.bestModel println(bestModel.extractParamMap) bestModel}" }, { "code": null, "e": 8546, "s": 8408, "text": "Most of this should also be pretty self-explanatory — except the function definition, which is virtually impenetrable. That is this part:" }, { "code": null, "e": 8754, "s": 8546, "text": "def train_eval[R <: Predictor[Vector, R, M], M <: PredictionModel[Vector, M]]( predictor: Predictor[Vector, R, M], paramMap: Array[ParamMap], train: DataFrame, test: DataFrame) = {" }, { "code": null, "e": 9412, "s": 8754, "text": "Unfortunately, Spark ML does not seem to have a generic “Model” type where we could, for example, pass in an object that is a RegressionModel, and then our function could take that “Model” object and call the .fit method. That would allow us to avoid this mess. Instead, we have to come up with this complex definition just so we can create a method that accepts a generic “Model” type because the type is also dependent on the input format and an implicit evaluator type. Coming up with this sort of definition is pretty tricky — after looking around and some trial and error, I found that taking it directly from the Spark ML source code worked just fine." }, { "code": null, "e": 9669, "s": 9412, "text": "The good news is, once you write something like this, the callers do not need to really know about it or understand it (it is unlikely that they will, to be honest). Instead, this complex type definition allows callers to write really clean code like this:" }, { "code": null, "e": 9948, "s": 9669, "text": "val lr = new LinearRegression()val lrParamMap = new ParamGridBuilder() .addGrid(lr.regParam, Array(10, 1, 0.1, 0.01, 0.001)) .addGrid(lr.elasticNetParam, Array(0.0, 0.5, 1.0)) .addGrid(lr.maxIter, Array(10000, 250000)) .build()train_eval(lr, lrParamMap, train, test)" }, { "code": null, "e": 10487, "s": 9948, "text": "Now we are back to something simple: an algorithm (Linear Regression) and a grid of parameters for cross validation. The function call then becomes as simple as we saw in Python. It is literally the same code. Note that I even kept the embedded underscore syntax for train_eval and other variables. Typically in Scala and Java we would use camel case, ie trainEval, and that is what I would do when writing production code, but since this tutorial was originally written in Python it was worth maintaining some consistency for comparison." }, { "code": null, "e": 10696, "s": 10487, "text": "We will now look at a few other algorithms to see how they do. Note that Lasso and Ridge do not have explicit classes, as the elasticNetParam designates those two algorithms when set to 1 and 0, respectively." }, { "code": null, "e": 10711, "s": 10696, "text": "Decision Tree:" }, { "code": null, "e": 10913, "s": 10711, "text": "import org.apache.spark.ml.regression.DecisionTreeRegressorval decisionTree = new DecisionTreeRegressor()val dtParamMap = new ParamGridBuilder().build()train_eval(decisionTree, dtParamMap, train, test)" }, { "code": null, "e": 10922, "s": 10913, "text": "Results:" }, { "code": null, "e": 11024, "s": 10922, "text": "Root Mean Squared Error (RMSE) on test data = 759685.8395738212R^2 on test data = 0.46558480196241925" }, { "code": null, "e": 11039, "s": 11024, "text": "Random Forest:" }, { "code": null, "e": 11407, "s": 11039, "text": "import org.apache.spark.ml.regression.RandomForestRegressorval randomForest = new RandomForestRegressor()val rfParamMap = new ParamGridBuilder() .addGrid(randomForest.maxBins, Array(4, 16, 32, 64)) .addGrid(randomForest.numTrees, Array(1, 10, 100)) .addGrid(randomForest.maxDepth, Array(2, 5, 10)) .build()train_eval(randomForest, rfParamMap, train, test)" }, { "code": null, "e": 11416, "s": 11407, "text": "Results:" }, { "code": null, "e": 11516, "s": 11416, "text": "Root Mean Squared Error (RMSE) on test data = 647133.830611256R^2 on test data = 0.6122079099308858" }, { "code": null, "e": 11532, "s": 11516, "text": "Gradient Boost:" }, { "code": null, "e": 11934, "s": 11532, "text": "import org.apache.spark.ml.regression.GBTRegressorval gradientBoost = new GBTRegressor()val gbParamMap = new ParamGridBuilder() .addGrid(randomForest.maxBins, Array(16, 32)) .addGrid(randomForest.numTrees, Array(5, 10, 100)) .addGrid(randomForest.maxDepth, Array(5, 10)) .addGrid(randomForest.minInfoGain, Array(0.0, 0.1, 0.5)) .build()train_eval(gradientBoost, gbParamMap, train, test)" }, { "code": null, "e": 11943, "s": 11934, "text": "Results:" }, { "code": null, "e": 12044, "s": 11943, "text": "Root Mean Squared Error (RMSE) on test data = 703037.6456894034R^2 on test data = 0.5423137139558296" }, { "code": null, "e": 12503, "s": 12044, "text": "While the exact results differ (especially for Linear Regression), we also see a similar trend of Random Forest and Gradient Boost working better than the simpler algorithms. Once again, we can improve our results by using better data. We do this by reincorporating the neighborhood data, but in a numerical format that the algorithms can use. We do this by changing categories like Mission and South Beach to columns of one and zeros using one-hot encoding." }, { "code": null, "e": 12551, "s": 12503, "text": "First, we rebuild or DataFrames with this data:" }, { "code": null, "e": 12627, "s": 12551, "text": "val housing_neighborhood = drop_geog(housing_dateint, List(\"neighborhood\"))" }, { "code": null, "e": 12694, "s": 12627, "text": "Then we transform the data with one-hot encoding using a Pipeline:" }, { "code": null, "e": 13259, "s": 12694, "text": "import org.apache.spark.ml.Pipelineimport org.apache.spark.ml.feature.OneHotEncoderEstimatorimport org.apache.spark.ml.feature.StringIndexerval indexer = new StringIndexer().setInputCol(\"neighborhood\").setOutputCol(\"neighborhoodIndex\")val encoder = new OneHotEncoderEstimator() .setInputCols(Array(indexer.getOutputCol)) .setOutputCols(Array(\"neighborhoodVector\"))val pipeline = new Pipeline().setStages(Array(indexer, encoder))val housingEncoded = pipeline.fit(housing_neighborhood).transform(housing_neighborhood).drop(\"neighborhoodIndex\").drop(\"neighborhood\")" }, { "code": null, "e": 13737, "s": 13259, "text": "First, we have to use a StringIndexer then we can get the results we want using the OneHotEncoderEstimator. Since these are two steps, we can put them together using a Pipeline of stages. Pipelines can be used for many multi-stage cleaning and modification operations, especially where you need to do these same stages over and over again, ie with evolving data sets that require retraining. It is not really necessary here, but it is worth showing because it can be so useful." }, { "code": null, "e": 13883, "s": 13737, "text": "Having updated our data, we can rerun our experiments exactly as before. We just pass in our new data (after creating training and testing sets):" }, { "code": null, "e": 13962, "s": 13883, "text": "val (train_neighborhood, test_neighborhood) = train_test_split(housingEncoded)" }, { "code": null, "e": 14058, "s": 13962, "text": "For example, for Linear Regression, we call exactly the same function with these new variables:" }, { "code": null, "e": 14124, "s": 14058, "text": "train_eval(lr, lrParamMap, train_neighborhood, test_neighborhood)" }, { "code": null, "e": 14133, "s": 14124, "text": "Results:" }, { "code": null, "e": 14234, "s": 14133, "text": "Root Mean Squared Error (RMSE) on test data = 754869.9632285038R^2 on test data = 0.4723389619596349" }, { "code": null, "e": 14405, "s": 14234, "text": "This still is not great, but it is quite a bit better than previously. Now let’s look at the results for the other algorithms after passing in the transformed DataFrames." }, { "code": null, "e": 14420, "s": 14405, "text": "Decision Tree:" }, { "code": null, "e": 14521, "s": 14420, "text": "Root Mean Squared Error (RMSE) on test data = 722171.2606321493R^2 on test data = 0.5170622654844328" }, { "code": null, "e": 14536, "s": 14521, "text": "Random Forest:" }, { "code": null, "e": 14636, "s": 14536, "text": "Root Mean Squared Error (RMSE) on test data = 581188.983582857R^2 on test data = 0.6872153115815951" }, { "code": null, "e": 14652, "s": 14636, "text": "Gradient Boost:" }, { "code": null, "e": 14753, "s": 14652, "text": "Root Mean Squared Error (RMSE) on test data = 636055.9695573623R^2 on test data = 0.6253709908240936" } ]
Instant minus() method in Java
An immutable copy of a instant where a time unit is subtracted from it can be obtained using the minus() method in the Instant class in Java. This method requires two parameters i.e. time to be subtracted from the instant and the unit in which it is to be subtracted. It also returns the immutable copy of the instant where the required time unit is subtracted. A program that demonstrates this is given as follows − Live Demo import java.time.*; import java.time.temporal.ChronoUnit; public class Demo { public static void main(String[] args) { Instant i = Instant.now(); System.out.println("The current instant is: " + i); Instant sub = i.minus(2, ChronoUnit.HOURS); System.out.println("The instant with 2 hours subtracted is: " + sub); } } The current instant is: 2019-02-13T06:40:32.595Z The instant with 2 hours subtracted is: 2019-02-13T04:40:32.595Z Now let us understand the above program. First the current instant is displayed. Then an immutable copy of the instant where 2 hours are subtracted is obtained using the minus() method and this is displayed. A code snippet that demonstrates this is as follows − Instant i = Instant.now(); System.out.println("The current instant is: " + i); Instant sub = i.minus(2, ChronoUnit.HOURS); System.out.println("The instant with 2 hours subtracted is: " + sub);
[ { "code": null, "e": 1424, "s": 1062, "text": "An immutable copy of a instant where a time unit is subtracted from it can be obtained using the minus() method in the Instant class in Java. This method requires two parameters i.e. time to be subtracted from the instant and the unit in which it is to be subtracted. It also returns the immutable copy of the instant where the required time unit is subtracted." }, { "code": null, "e": 1479, "s": 1424, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1490, "s": 1479, "text": " Live Demo" }, { "code": null, "e": 1836, "s": 1490, "text": "import java.time.*;\nimport java.time.temporal.ChronoUnit;\npublic class Demo {\n public static void main(String[] args) {\n Instant i = Instant.now();\n System.out.println(\"The current instant is: \" + i);\n Instant sub = i.minus(2, ChronoUnit.HOURS);\n System.out.println(\"The instant with 2 hours subtracted is: \" + sub);\n }\n}" }, { "code": null, "e": 1950, "s": 1836, "text": "The current instant is: 2019-02-13T06:40:32.595Z\nThe instant with 2 hours subtracted is: 2019-02-13T04:40:32.595Z" }, { "code": null, "e": 1991, "s": 1950, "text": "Now let us understand the above program." }, { "code": null, "e": 2212, "s": 1991, "text": "First the current instant is displayed. Then an immutable copy of the instant where 2 hours are subtracted is obtained using the minus() method and this is displayed. A code snippet that demonstrates this is as follows −" }, { "code": null, "e": 2405, "s": 2212, "text": "Instant i = Instant.now();\nSystem.out.println(\"The current instant is: \" + i);\nInstant sub = i.minus(2, ChronoUnit.HOURS);\nSystem.out.println(\"The instant with 2 hours subtracted is: \" + sub);" } ]
Deploying Docker containers in AWS Fargate | by Eduardo Vioque | Towards Data Science
Docker is a fantastic tool to encapsulate and deploy applications in an easy and scalable way. Indeed, something I find myself doing very often is wrapping Python libraries into Docker images that I can later use as boilerplates for my projects. In this post, I will illustrate how to register your Docker images in a container registry and how to deploy the containers in AWS using Fargate, a serverless compute engine designed to run containerized applications. Additionally, we will use Cloud Formation to deploy our stack in a programmatic way. Let’s get started! Container registries are to Docker images what code repositories are to code. In a registry, you create image repositories to push and register your local images, you can store different versions of the same image, and other users can pull and update the image if they have access to the repo. Now, let’s say you have developed locally an image that you want to deploy to the cloud. To do so, we would need to store our local image in a container registry from which it can be pulled and deployed. In this article, I will be using a fairly simple image that starts a web Python-Dash application on port 80. We will use the ECR (Elastic Container Registry) to register our images. ECR is an AWS service, quite similar to DockerHub, to store Docker images. The first thing we have to do is creating a repository in ECR, we can use the AWS CLI as follows: aws ecr create-repository \--repository-name dash-app \--image-scanning-configuration scanOnPush=true \ --region eu-central-1 You should be able to see the repository in the AWS management console To push local images to our ECR repository we are required to authenticate our local Docker CLI into AWS: aws ecr get-login-password --region region | docker login --username AWS --password-stdin acccount_id.dkr.ecr.region.amazonaws.com Just replace the aws_account_id and region appropriately. You should see the message Login Succeeded in the terminal, which means our local Docker CLI is authenticated to interact with the ECR. Let’s push now our local image to our brand new repository. To do so we must tag our image to point to the ECR repository: docker tag image_id account_id.dkr.ecr.eu-central-1.amazonaws.com/dash-app:latest Now we just have to push it to the ECR: docker push account_id.dkr.ecr.eu-central-1.amazonaws.com/dash-app:latest You should see the pushed image in the AWS Console: With that we come to the end of the section, let’s summarize: (i) we have created an image repository called dash-app in ECR, (ii) we have authorized our local Docker CLI to connect to AWS, and (iii) we have pushed an image to the repository. In the next section, we will cover how to deploy this image in AWS. Leaving Kubernetes aside, AWS provides several options to deploy containerized applications: Deploying containers on EC2, usually within an auto-scaling group of instances. In this scenario we are responsible for patching, securing, monitoring, and scaling the EC2 instances.Deploying containers on AWS Fargate. Since Fargate is serverless, there are no EC2 instances to manage or provision. Fargate manages the execution of our tasks providing the right computing power (a task in this context refers to a group of containers that work together as an application). Deploying containers on EC2, usually within an auto-scaling group of instances. In this scenario we are responsible for patching, securing, monitoring, and scaling the EC2 instances. Deploying containers on AWS Fargate. Since Fargate is serverless, there are no EC2 instances to manage or provision. Fargate manages the execution of our tasks providing the right computing power (a task in this context refers to a group of containers that work together as an application). In this section, we will focus on the second option, illustrating how to roll out our web application on AWS Fargate. In addition, we will allocate all the necessary resources with AWS Cloud Formation. Cloud Formation is an AWS service to provision and deploy resources in a programmatic way, a technique usually referred to as infrastructure as code or IaC. In IaC, instead of allocating resources manually through the management console, we define our stack in a JSON or YAML file. The file is then submitted to Cloud Formation which automatically deploys all the resources specified in it. This has two main advantages: (i) it makes it easy to automate resources provisioning and deployments, and (ii) the files help as documentation of our cloud infrastructure. Although defining our stack in a JSON/YAML file requires going through a learning curve and forgetting about AWS management console and its truly easy to use wizards, it definitely pays off in the long run. As your infrastructure grows, keeping all the stack as code will be incredibly helpful to scale productively. Now, let’s list the resources we need to run our application: Task: It describes the group of Docker containers that shape our application. In our example, we simply have one image.ECS Service: It takes care of running and maintaining the desired number of instances of a task. For example, if a task fails or stops, the ECS Service can automatically launch a new instance to keep the desired number of tasks in service.Fargate: A serverless compute engine for containers. With Fargate there is no need to book and manage servers. It automatically supplies compute power to run our tasks.Network resources: we need as well a VPC, a public subnet connected to an internet gateway through a routing table (don’t forget we are deploying a web application that should be reachable from the internet), and a security group to run our containers securely. You don’t need to set up those resources if you already have a network configuration in place, although I include them in the Cloud Formation script. Task: It describes the group of Docker containers that shape our application. In our example, we simply have one image. ECS Service: It takes care of running and maintaining the desired number of instances of a task. For example, if a task fails or stops, the ECS Service can automatically launch a new instance to keep the desired number of tasks in service. Fargate: A serverless compute engine for containers. With Fargate there is no need to book and manage servers. It automatically supplies compute power to run our tasks. Network resources: we need as well a VPC, a public subnet connected to an internet gateway through a routing table (don’t forget we are deploying a web application that should be reachable from the internet), and a security group to run our containers securely. You don’t need to set up those resources if you already have a network configuration in place, although I include them in the Cloud Formation script. Now, without further ado, let’s jump into the stack. The Gist below contains all the resources required. Let’s explain them in details: VPC-FARGATE: This is the VPC. It is important enabling DNS support and DNS Hostnames to reach the ECR and pull the images.INT-GATEWAY: This is an internet gateway, it is needed to expose the subnet to the internet.ATTACH-IG: This attaches the internet gateway to the VPC.ROUTE-TABLE : This is a routing table, to which we will add the rules to expose the subnet to the internet gateway.ROUTE : This adds a rule to the routing table previously described. It forwards traffic to the internet gateway.SUBNETFARGATE : This is the subnet to host our services. We define the availability zone and the VPC to which it belongs.SUBNETROUTE : This associates the routing table to the subnet.SGFARGATE : This is the security group to be applied to our services. It allows traffic on ports 443 and 80 over HTTPS and HTTP protocols.FARGATECLUSTER : It defines the Fargate cluster to host our services.ECSTASK : Determines the tasks to be executed. It includes the list of Docker images that make the task. For each container, it registers ports mapping, starting commands, and logging options. Images are pulled from the ECR repository set up before.SERVICE : Defines the ECS Service that will launch and maintain our tasks. If you already have a network configuration in place and don’t need to create a new subnet and security group, just reference those existing resources in the NetworkConfiguration section of the ECS Service. VPC-FARGATE: This is the VPC. It is important enabling DNS support and DNS Hostnames to reach the ECR and pull the images. INT-GATEWAY: This is an internet gateway, it is needed to expose the subnet to the internet. ATTACH-IG: This attaches the internet gateway to the VPC. ROUTE-TABLE : This is a routing table, to which we will add the rules to expose the subnet to the internet gateway. ROUTE : This adds a rule to the routing table previously described. It forwards traffic to the internet gateway. SUBNETFARGATE : This is the subnet to host our services. We define the availability zone and the VPC to which it belongs. SUBNETROUTE : This associates the routing table to the subnet. SGFARGATE : This is the security group to be applied to our services. It allows traffic on ports 443 and 80 over HTTPS and HTTP protocols. FARGATECLUSTER : It defines the Fargate cluster to host our services. ECSTASK : Determines the tasks to be executed. It includes the list of Docker images that make the task. For each container, it registers ports mapping, starting commands, and logging options. Images are pulled from the ECR repository set up before. SERVICE : Defines the ECS Service that will launch and maintain our tasks. If you already have a network configuration in place and don’t need to create a new subnet and security group, just reference those existing resources in the NetworkConfiguration section of the ECS Service. Once your file is ready, upload it to Cloud Formation to create your stack: Follow the steps in the management console to launch the stack. Once finished, Cloud Formation will automatically start provisioning the services. You can follow its progress in the events tab: And more importantly, when ready, you can access your web application at the public IP address assigned to the running task! If you are following best practices, you are not creating resources with your AWS root account. Instead, you should be using a non-root user. However, you should note that to pass a role to a service, AWS requires the user who creates the service to have “Pass Role” permissions. In our example, we need our user to pass the role ecsTaskExecutionRole to the TaskDefinition service, and therefore we must grant the user permissions to do so. This is something to be done from the root account in the IAM or any account with IAM privileges. Simply add the policy bellow, and attach it to the user who will allocate all the resources. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "iam:PassRole", "Resource": "arn:aws:iam::account_id:role/ecsTaskExecutionRole" } ]} We’ve covered a lot in this article. We’ve seen how to create an ECR repository and how to push Docker images to it. We’ve also had a brief introduction to CloudFormation and IaC. I would like to restate the importance of specifying your infrastructure and stack as code. As your infrastructure grows, having the stack defined in JSON or YAML files will make it easier to automate deployments, scale in a productive manner, and will provide certain documentation on your infrastructure. Finally, we used AWS Fargate to deploy docker containers in a serverless way, which spared us the burden of provisioning and managing servers. I hope you find this article helpful, thank you for reading. Getting started with Amazon ECR using the AWS CLI Getting started with Amazon ECR using the AWS CLI
[ { "code": null, "e": 418, "s": 172, "text": "Docker is a fantastic tool to encapsulate and deploy applications in an easy and scalable way. Indeed, something I find myself doing very often is wrapping Python libraries into Docker images that I can later use as boilerplates for my projects." }, { "code": null, "e": 740, "s": 418, "text": "In this post, I will illustrate how to register your Docker images in a container registry and how to deploy the containers in AWS using Fargate, a serverless compute engine designed to run containerized applications. Additionally, we will use Cloud Formation to deploy our stack in a programmatic way. Let’s get started!" }, { "code": null, "e": 1034, "s": 740, "text": "Container registries are to Docker images what code repositories are to code. In a registry, you create image repositories to push and register your local images, you can store different versions of the same image, and other users can pull and update the image if they have access to the repo." }, { "code": null, "e": 1347, "s": 1034, "text": "Now, let’s say you have developed locally an image that you want to deploy to the cloud. To do so, we would need to store our local image in a container registry from which it can be pulled and deployed. In this article, I will be using a fairly simple image that starts a web Python-Dash application on port 80." }, { "code": null, "e": 1593, "s": 1347, "text": "We will use the ECR (Elastic Container Registry) to register our images. ECR is an AWS service, quite similar to DockerHub, to store Docker images. The first thing we have to do is creating a repository in ECR, we can use the AWS CLI as follows:" }, { "code": null, "e": 1723, "s": 1593, "text": "aws ecr create-repository \\--repository-name dash-app \\--image-scanning-configuration scanOnPush=true \\ --region eu-central-1" }, { "code": null, "e": 1794, "s": 1723, "text": "You should be able to see the repository in the AWS management console" }, { "code": null, "e": 1900, "s": 1794, "text": "To push local images to our ECR repository we are required to authenticate our local Docker CLI into AWS:" }, { "code": null, "e": 2031, "s": 1900, "text": "aws ecr get-login-password --region region | docker login --username AWS --password-stdin acccount_id.dkr.ecr.region.amazonaws.com" }, { "code": null, "e": 2225, "s": 2031, "text": "Just replace the aws_account_id and region appropriately. You should see the message Login Succeeded in the terminal, which means our local Docker CLI is authenticated to interact with the ECR." }, { "code": null, "e": 2348, "s": 2225, "text": "Let’s push now our local image to our brand new repository. To do so we must tag our image to point to the ECR repository:" }, { "code": null, "e": 2430, "s": 2348, "text": "docker tag image_id account_id.dkr.ecr.eu-central-1.amazonaws.com/dash-app:latest" }, { "code": null, "e": 2470, "s": 2430, "text": "Now we just have to push it to the ECR:" }, { "code": null, "e": 2544, "s": 2470, "text": "docker push account_id.dkr.ecr.eu-central-1.amazonaws.com/dash-app:latest" }, { "code": null, "e": 2596, "s": 2544, "text": "You should see the pushed image in the AWS Console:" }, { "code": null, "e": 2907, "s": 2596, "text": "With that we come to the end of the section, let’s summarize: (i) we have created an image repository called dash-app in ECR, (ii) we have authorized our local Docker CLI to connect to AWS, and (iii) we have pushed an image to the repository. In the next section, we will cover how to deploy this image in AWS." }, { "code": null, "e": 3000, "s": 2907, "text": "Leaving Kubernetes aside, AWS provides several options to deploy containerized applications:" }, { "code": null, "e": 3473, "s": 3000, "text": "Deploying containers on EC2, usually within an auto-scaling group of instances. In this scenario we are responsible for patching, securing, monitoring, and scaling the EC2 instances.Deploying containers on AWS Fargate. Since Fargate is serverless, there are no EC2 instances to manage or provision. Fargate manages the execution of our tasks providing the right computing power (a task in this context refers to a group of containers that work together as an application)." }, { "code": null, "e": 3656, "s": 3473, "text": "Deploying containers on EC2, usually within an auto-scaling group of instances. In this scenario we are responsible for patching, securing, monitoring, and scaling the EC2 instances." }, { "code": null, "e": 3947, "s": 3656, "text": "Deploying containers on AWS Fargate. Since Fargate is serverless, there are no EC2 instances to manage or provision. Fargate manages the execution of our tasks providing the right computing power (a task in this context refers to a group of containers that work together as an application)." }, { "code": null, "e": 4149, "s": 3947, "text": "In this section, we will focus on the second option, illustrating how to roll out our web application on AWS Fargate. In addition, we will allocate all the necessary resources with AWS Cloud Formation." }, { "code": null, "e": 4713, "s": 4149, "text": "Cloud Formation is an AWS service to provision and deploy resources in a programmatic way, a technique usually referred to as infrastructure as code or IaC. In IaC, instead of allocating resources manually through the management console, we define our stack in a JSON or YAML file. The file is then submitted to Cloud Formation which automatically deploys all the resources specified in it. This has two main advantages: (i) it makes it easy to automate resources provisioning and deployments, and (ii) the files help as documentation of our cloud infrastructure." }, { "code": null, "e": 5030, "s": 4713, "text": "Although defining our stack in a JSON/YAML file requires going through a learning curve and forgetting about AWS management console and its truly easy to use wizards, it definitely pays off in the long run. As your infrastructure grows, keeping all the stack as code will be incredibly helpful to scale productively." }, { "code": null, "e": 5092, "s": 5030, "text": "Now, let’s list the resources we need to run our application:" }, { "code": null, "e": 6030, "s": 5092, "text": "Task: It describes the group of Docker containers that shape our application. In our example, we simply have one image.ECS Service: It takes care of running and maintaining the desired number of instances of a task. For example, if a task fails or stops, the ECS Service can automatically launch a new instance to keep the desired number of tasks in service.Fargate: A serverless compute engine for containers. With Fargate there is no need to book and manage servers. It automatically supplies compute power to run our tasks.Network resources: we need as well a VPC, a public subnet connected to an internet gateway through a routing table (don’t forget we are deploying a web application that should be reachable from the internet), and a security group to run our containers securely. You don’t need to set up those resources if you already have a network configuration in place, although I include them in the Cloud Formation script." }, { "code": null, "e": 6150, "s": 6030, "text": "Task: It describes the group of Docker containers that shape our application. In our example, we simply have one image." }, { "code": null, "e": 6390, "s": 6150, "text": "ECS Service: It takes care of running and maintaining the desired number of instances of a task. For example, if a task fails or stops, the ECS Service can automatically launch a new instance to keep the desired number of tasks in service." }, { "code": null, "e": 6559, "s": 6390, "text": "Fargate: A serverless compute engine for containers. With Fargate there is no need to book and manage servers. It automatically supplies compute power to run our tasks." }, { "code": null, "e": 6971, "s": 6559, "text": "Network resources: we need as well a VPC, a public subnet connected to an internet gateway through a routing table (don’t forget we are deploying a web application that should be reachable from the internet), and a security group to run our containers securely. You don’t need to set up those resources if you already have a network configuration in place, although I include them in the Cloud Formation script." }, { "code": null, "e": 7107, "s": 6971, "text": "Now, without further ado, let’s jump into the stack. The Gist below contains all the resources required. Let’s explain them in details:" }, { "code": null, "e": 8526, "s": 7107, "text": "VPC-FARGATE: This is the VPC. It is important enabling DNS support and DNS Hostnames to reach the ECR and pull the images.INT-GATEWAY: This is an internet gateway, it is needed to expose the subnet to the internet.ATTACH-IG: This attaches the internet gateway to the VPC.ROUTE-TABLE : This is a routing table, to which we will add the rules to expose the subnet to the internet gateway.ROUTE : This adds a rule to the routing table previously described. It forwards traffic to the internet gateway.SUBNETFARGATE : This is the subnet to host our services. We define the availability zone and the VPC to which it belongs.SUBNETROUTE : This associates the routing table to the subnet.SGFARGATE : This is the security group to be applied to our services. It allows traffic on ports 443 and 80 over HTTPS and HTTP protocols.FARGATECLUSTER : It defines the Fargate cluster to host our services.ECSTASK : Determines the tasks to be executed. It includes the list of Docker images that make the task. For each container, it registers ports mapping, starting commands, and logging options. Images are pulled from the ECR repository set up before.SERVICE : Defines the ECS Service that will launch and maintain our tasks. If you already have a network configuration in place and don’t need to create a new subnet and security group, just reference those existing resources in the NetworkConfiguration section of the ECS Service." }, { "code": null, "e": 8649, "s": 8526, "text": "VPC-FARGATE: This is the VPC. It is important enabling DNS support and DNS Hostnames to reach the ECR and pull the images." }, { "code": null, "e": 8742, "s": 8649, "text": "INT-GATEWAY: This is an internet gateway, it is needed to expose the subnet to the internet." }, { "code": null, "e": 8800, "s": 8742, "text": "ATTACH-IG: This attaches the internet gateway to the VPC." }, { "code": null, "e": 8916, "s": 8800, "text": "ROUTE-TABLE : This is a routing table, to which we will add the rules to expose the subnet to the internet gateway." }, { "code": null, "e": 9029, "s": 8916, "text": "ROUTE : This adds a rule to the routing table previously described. It forwards traffic to the internet gateway." }, { "code": null, "e": 9151, "s": 9029, "text": "SUBNETFARGATE : This is the subnet to host our services. We define the availability zone and the VPC to which it belongs." }, { "code": null, "e": 9214, "s": 9151, "text": "SUBNETROUTE : This associates the routing table to the subnet." }, { "code": null, "e": 9353, "s": 9214, "text": "SGFARGATE : This is the security group to be applied to our services. It allows traffic on ports 443 and 80 over HTTPS and HTTP protocols." }, { "code": null, "e": 9423, "s": 9353, "text": "FARGATECLUSTER : It defines the Fargate cluster to host our services." }, { "code": null, "e": 9673, "s": 9423, "text": "ECSTASK : Determines the tasks to be executed. It includes the list of Docker images that make the task. For each container, it registers ports mapping, starting commands, and logging options. Images are pulled from the ECR repository set up before." }, { "code": null, "e": 9955, "s": 9673, "text": "SERVICE : Defines the ECS Service that will launch and maintain our tasks. If you already have a network configuration in place and don’t need to create a new subnet and security group, just reference those existing resources in the NetworkConfiguration section of the ECS Service." }, { "code": null, "e": 10031, "s": 9955, "text": "Once your file is ready, upload it to Cloud Formation to create your stack:" }, { "code": null, "e": 10225, "s": 10031, "text": "Follow the steps in the management console to launch the stack. Once finished, Cloud Formation will automatically start provisioning the services. You can follow its progress in the events tab:" }, { "code": null, "e": 10350, "s": 10225, "text": "And more importantly, when ready, you can access your web application at the public IP address assigned to the running task!" }, { "code": null, "e": 10982, "s": 10350, "text": "If you are following best practices, you are not creating resources with your AWS root account. Instead, you should be using a non-root user. However, you should note that to pass a role to a service, AWS requires the user who creates the service to have “Pass Role” permissions. In our example, we need our user to pass the role ecsTaskExecutionRole to the TaskDefinition service, and therefore we must grant the user permissions to do so. This is something to be done from the root account in the IAM or any account with IAM privileges. Simply add the policy bellow, and attach it to the user who will allocate all the resources." }, { "code": null, "e": 11196, "s": 10982, "text": "{ \"Version\": \"2012-10-17\", \"Statement\": [ { \"Effect\": \"Allow\", \"Action\": \"iam:PassRole\", \"Resource\": \"arn:aws:iam::account_id:role/ecsTaskExecutionRole\" } ]}" }, { "code": null, "e": 11826, "s": 11196, "text": "We’ve covered a lot in this article. We’ve seen how to create an ECR repository and how to push Docker images to it. We’ve also had a brief introduction to CloudFormation and IaC. I would like to restate the importance of specifying your infrastructure and stack as code. As your infrastructure grows, having the stack defined in JSON or YAML files will make it easier to automate deployments, scale in a productive manner, and will provide certain documentation on your infrastructure. Finally, we used AWS Fargate to deploy docker containers in a serverless way, which spared us the burden of provisioning and managing servers." }, { "code": null, "e": 11887, "s": 11826, "text": "I hope you find this article helpful, thank you for reading." }, { "code": null, "e": 11937, "s": 11887, "text": "Getting started with Amazon ECR using the AWS CLI" } ]
Program to find sum of prime numbers between 1 to n - GeeksforGeeks
27 Jan, 2022 Write a program to find sum of all prime numbers between 1 to n.Examples: Input : 10 Output : 17 Explanation : Primes between 1 to 10 : 2, 3, 5, 7. Input : 11 Output : 28 Explanation : Primes between 1 to 11 : 2, 3, 5, 7, 11. A simple solution is to traverse all numbers from 1 to n. For every number, check if it is a prime. If yes, add it to result.An efficient solution is to use Sieve of Eratosthenes to find all prime numbers from till n and then do their sum. C++ Java Python3 C# PHP Javascript // C++ program to find sum of primes in// range from 1 to n.#include <bits/stdc++.h>using namespace std; // Returns sum of primes in range from// 1 to n.int sumOfPrimes(int n){ // Array to store prime numbers bool prime[n + 1]; // Create a boolean array "prime[0..n]" // and initialize all entries it as true. // A value in prime[i] will finally be // false if i is Not a prime, else true. memset(prime, true, n + 1); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // Return sum of primes generated through // Sieve. int sum = 0; for (int i = 2; i <= n; i++) if (prime[i]) sum += i; return sum;} // Driver codeint main(){ int n = 11; cout << sumOfPrimes(n); return 0;} // Java program to find// sum of primes in// range from 1 to n.import java.io.*;import java.util.*; class GFG { // Returns sum of primes // in range from // 1 to n. static int sumOfPrimes(int n) { // Array to store prime numbers boolean prime[]=new boolean[n + 1]; // Create a boolean array "prime[0..n]" // and initialize all entries it as true. // A value in prime[i] will finally be // false if i is Not a prime, else true. Arrays.fill(prime, true); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // Return sum of primes generated through // Sieve. int sum = 0; for (int i = 2; i <= n; i++) if (prime[i]) sum += i; return sum; } // Driver code public static void main(String args[]) { int n = 11; System.out.print(sumOfPrimes(n)); }} // This code is contributed// by Nikita Tiwari. # Python program to find sum of primes# in range from 1 to n. # Returns sum of primes in range from# 1 to n def sumOfPrimes(n): # list to store prime numbers prime = [True] * (n + 1) # Create a boolean array "prime[0..n]" # and initialize all entries it as true. # A value in prime[i] will finally be # false if i is Not a prime, else true. p = 2 while p * p <= n: # If prime[p] is not changed, then # it is a prime if prime[p] == True: # Update all multiples of p i = p * 2 while i <= n: prime[i] = False i += p p += 1 # Return sum of primes generated through # Sieve. sum = 0 for i in range (2, n + 1): if(prime[i]): sum += i return sum # Driver coden = 11print(sumOfPrimes(n)) # This code is contributed by Sachin Bisht // C# program to find// sum of primes in// range from 1 to n.using System; class GFG { // Returns sum of primes // in range from // 1 to n. static int sumOfPrimes(int n) { // Array to store prime numbers bool []prime=new bool[n + 1]; // Create a boolean array "prime[0..n]" // and initialize all entries it as true. // A value in prime[i] will finally be // false if i is Not a prime, else true. for(int i = 0; i < n + 1; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // Return sum of primes // generated through Sieve. int sum = 0; for (int i = 2; i <= n; i++) if (prime[i]) sum += i; return sum; } // Driver code public static void Main() { int n = 11; Console.Write(sumOfPrimes(n)); }} // This code is contributed by nitin mittal. <?php// PHP program to find// sum of primes in// range from 1 to n. // Returns sum of primes// in range from 1 to n.function sumOfPrimes($n){ // Array to store prime // numbers bool prime[n + 1]; // Create a boolean array // "prime[0..n]" and initialize // all entries it as true. // A value in prime[i] will // finally be false if i is Not // a prime, else true. $prime = array_fill(0, $n + 1, true); for ($p = 2; $p * $p <= $n; $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $n; $i += $p) $prime[$i] = false; } } // Return sum of primes // generated through Sieve. $sum = 0; for ($i = 2; $i <= $n; $i++) if ($prime[$i]) $sum += $i; return $sum;} // Driver code$n = 11;echo sumOfPrimes($n); // This code is contributed// by ajit?> <script> // Javascript program to find // sum of primes in // range from 1 to n. // Returns sum of primes // in range from // 1 to n. function sumOfPrimes(n) { // Array to store prime numbers let prime = new Array(n + 1); // Create a boolean array "prime[0..n]" // and initialize all entries it as true. // A value in prime[i] will finally be // false if i is Not a prime, else true. for(let i = 0; i < n + 1; i++) prime[i] = true; for (let p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= n; i += p) prime[i] = false; } } // Return sum of primes // generated through Sieve. let sum = 0; for (let i = 2; i <= n; i++) if (prime[i]) sum += i; return sum; } let n = 11; document.write(sumOfPrimes(n)); </script> Output: 28 This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal jit_t rameshtravel07 amartyaghoshgfg Prime Number Samsung sieve Mathematical Samsung Mathematical Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program for Decimal to Binary Conversion Program to find sum of elements in a given array The Knight's tour problem | Backtracking-1 Find all factors of a natural number | Set 1 Program for factorial of a number Operators in C / C++ Minimum number of jumps to reach end
[ { "code": null, "e": 24321, "s": 24293, "text": "\n27 Jan, 2022" }, { "code": null, "e": 24397, "s": 24321, "text": "Write a program to find sum of all prime numbers between 1 to n.Examples: " }, { "code": null, "e": 24550, "s": 24397, "text": "Input : 10\nOutput : 17\nExplanation : Primes between 1 to 10 : 2, 3, 5, 7.\n\nInput : 11\nOutput : 28\nExplanation : Primes between 1 to 11 : 2, 3, 5, 7, 11." }, { "code": null, "e": 24793, "s": 24552, "text": "A simple solution is to traverse all numbers from 1 to n. For every number, check if it is a prime. If yes, add it to result.An efficient solution is to use Sieve of Eratosthenes to find all prime numbers from till n and then do their sum. " }, { "code": null, "e": 24797, "s": 24793, "text": "C++" }, { "code": null, "e": 24802, "s": 24797, "text": "Java" }, { "code": null, "e": 24810, "s": 24802, "text": "Python3" }, { "code": null, "e": 24813, "s": 24810, "text": "C#" }, { "code": null, "e": 24817, "s": 24813, "text": "PHP" }, { "code": null, "e": 24828, "s": 24817, "text": "Javascript" }, { "code": "// C++ program to find sum of primes in// range from 1 to n.#include <bits/stdc++.h>using namespace std; // Returns sum of primes in range from// 1 to n.int sumOfPrimes(int n){ // Array to store prime numbers bool prime[n + 1]; // Create a boolean array \"prime[0..n]\" // and initialize all entries it as true. // A value in prime[i] will finally be // false if i is Not a prime, else true. memset(prime, true, n + 1); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // Return sum of primes generated through // Sieve. int sum = 0; for (int i = 2; i <= n; i++) if (prime[i]) sum += i; return sum;} // Driver codeint main(){ int n = 11; cout << sumOfPrimes(n); return 0;}", "e": 25788, "s": 24828, "text": null }, { "code": "// Java program to find// sum of primes in// range from 1 to n.import java.io.*;import java.util.*; class GFG { // Returns sum of primes // in range from // 1 to n. static int sumOfPrimes(int n) { // Array to store prime numbers boolean prime[]=new boolean[n + 1]; // Create a boolean array \"prime[0..n]\" // and initialize all entries it as true. // A value in prime[i] will finally be // false if i is Not a prime, else true. Arrays.fill(prime, true); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // Return sum of primes generated through // Sieve. int sum = 0; for (int i = 2; i <= n; i++) if (prime[i]) sum += i; return sum; } // Driver code public static void main(String args[]) { int n = 11; System.out.print(sumOfPrimes(n)); }} // This code is contributed// by Nikita Tiwari.", "e": 27023, "s": 25788, "text": null }, { "code": "# Python program to find sum of primes# in range from 1 to n. # Returns sum of primes in range from# 1 to n def sumOfPrimes(n): # list to store prime numbers prime = [True] * (n + 1) # Create a boolean array \"prime[0..n]\" # and initialize all entries it as true. # A value in prime[i] will finally be # false if i is Not a prime, else true. p = 2 while p * p <= n: # If prime[p] is not changed, then # it is a prime if prime[p] == True: # Update all multiples of p i = p * 2 while i <= n: prime[i] = False i += p p += 1 # Return sum of primes generated through # Sieve. sum = 0 for i in range (2, n + 1): if(prime[i]): sum += i return sum # Driver coden = 11print(sumOfPrimes(n)) # This code is contributed by Sachin Bisht", "e": 27917, "s": 27023, "text": null }, { "code": "// C# program to find// sum of primes in// range from 1 to n.using System; class GFG { // Returns sum of primes // in range from // 1 to n. static int sumOfPrimes(int n) { // Array to store prime numbers bool []prime=new bool[n + 1]; // Create a boolean array \"prime[0..n]\" // and initialize all entries it as true. // A value in prime[i] will finally be // false if i is Not a prime, else true. for(int i = 0; i < n + 1; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // Return sum of primes // generated through Sieve. int sum = 0; for (int i = 2; i <= n; i++) if (prime[i]) sum += i; return sum; } // Driver code public static void Main() { int n = 11; Console.Write(sumOfPrimes(n)); }} // This code is contributed by nitin mittal.", "e": 29167, "s": 27917, "text": null }, { "code": "<?php// PHP program to find// sum of primes in// range from 1 to n. // Returns sum of primes// in range from 1 to n.function sumOfPrimes($n){ // Array to store prime // numbers bool prime[n + 1]; // Create a boolean array // \"prime[0..n]\" and initialize // all entries it as true. // A value in prime[i] will // finally be false if i is Not // a prime, else true. $prime = array_fill(0, $n + 1, true); for ($p = 2; $p * $p <= $n; $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $n; $i += $p) $prime[$i] = false; } } // Return sum of primes // generated through Sieve. $sum = 0; for ($i = 2; $i <= $n; $i++) if ($prime[$i]) $sum += $i; return $sum;} // Driver code$n = 11;echo sumOfPrimes($n); // This code is contributed// by ajit?>", "e": 30169, "s": 29167, "text": null }, { "code": "<script> // Javascript program to find // sum of primes in // range from 1 to n. // Returns sum of primes // in range from // 1 to n. function sumOfPrimes(n) { // Array to store prime numbers let prime = new Array(n + 1); // Create a boolean array \"prime[0..n]\" // and initialize all entries it as true. // A value in prime[i] will finally be // false if i is Not a prime, else true. for(let i = 0; i < n + 1; i++) prime[i] = true; for (let p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= n; i += p) prime[i] = false; } } // Return sum of primes // generated through Sieve. let sum = 0; for (let i = 2; i <= n; i++) if (prime[i]) sum += i; return sum; } let n = 11; document.write(sumOfPrimes(n)); </script>", "e": 31346, "s": 30169, "text": null }, { "code": null, "e": 31356, "s": 31346, "text": "Output: " }, { "code": null, "e": 31359, "s": 31356, "text": "28" }, { "code": null, "e": 31788, "s": 31359, "text": "This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 31801, "s": 31788, "text": "nitin mittal" }, { "code": null, "e": 31807, "s": 31801, "text": "jit_t" }, { "code": null, "e": 31822, "s": 31807, "text": "rameshtravel07" }, { "code": null, "e": 31838, "s": 31822, "text": "amartyaghoshgfg" }, { "code": null, "e": 31851, "s": 31838, "text": "Prime Number" }, { "code": null, "e": 31859, "s": 31851, "text": "Samsung" }, { "code": null, "e": 31865, "s": 31859, "text": "sieve" }, { "code": null, "e": 31878, "s": 31865, "text": "Mathematical" }, { "code": null, "e": 31886, "s": 31878, "text": "Samsung" }, { "code": null, "e": 31899, "s": 31886, "text": "Mathematical" }, { "code": null, "e": 31912, "s": 31899, "text": "Prime Number" }, { "code": null, "e": 31918, "s": 31912, "text": "sieve" }, { "code": null, "e": 32016, "s": 31918, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32025, "s": 32016, "text": "Comments" }, { "code": null, "e": 32038, "s": 32025, "text": "Old Comments" }, { "code": null, "e": 32062, "s": 32038, "text": "Merge two sorted arrays" }, { "code": null, "e": 32105, "s": 32062, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 32119, "s": 32105, "text": "Prime Numbers" }, { "code": null, "e": 32160, "s": 32119, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 32209, "s": 32160, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 32252, "s": 32209, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 32297, "s": 32252, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 32331, "s": 32297, "text": "Program for factorial of a number" }, { "code": null, "e": 32352, "s": 32331, "text": "Operators in C / C++" } ]
Batch Script – Remove All Spaces
28 Nov, 2021 In this article, we are going to see how to remove all spaces from any string using Batch String. Example : Input: G e e k s f o r G e e k s Output: GeeksforGeeks By using ‘ set ‘ we are getting input of any string.Example: set str=input string Example: set str=input string In the next line using ‘ echo %str% ‘ we are printing our input string. In the next line of code, we are going to remove all spaces in the input string. Using ‘ := ‘ operator we are removing spaces in any string. We have to type any character between and = to remove that character from any given input string.For example: str=%str:e=% (this will remove e from the input string) For example: str=%str:e=% (this will remove e from the input string) So for removing spaces we will use ‘ : = ‘ . ‘ pause ‘ is used to hold the screen until any key is pressed. Code: @echo off set str=G e e k s f o r G e e k s echo %str% set str=%str: =% echo %str% pause Output: batch script to remove all spaces. Batch-script Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 nohup Command in Linux with Examples mv command in Linux with examples chmod command in Linux with examples Array Basics in Shell Scripting | Set 1 Introduction to Linux Operating System Basic Operators in Shell Scripting
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Nov, 2021" }, { "code": null, "e": 152, "s": 54, "text": "In this article, we are going to see how to remove all spaces from any string using Batch String." }, { "code": null, "e": 162, "s": 152, "text": "Example :" }, { "code": null, "e": 224, "s": 162, "text": "Input: G e e k s f o r G e e k s\nOutput: GeeksforGeeks" }, { "code": null, "e": 306, "s": 224, "text": "By using ‘ set ‘ we are getting input of any string.Example: set str=input string" }, { "code": null, "e": 336, "s": 306, "text": "Example: set str=input string" }, { "code": null, "e": 408, "s": 336, "text": "In the next line using ‘ echo %str% ‘ we are printing our input string." }, { "code": null, "e": 489, "s": 408, "text": "In the next line of code, we are going to remove all spaces in the input string." }, { "code": null, "e": 549, "s": 489, "text": "Using ‘ := ‘ operator we are removing spaces in any string." }, { "code": null, "e": 715, "s": 549, "text": "We have to type any character between and = to remove that character from any given input string.For example: str=%str:e=% (this will remove e from the input string)" }, { "code": null, "e": 784, "s": 715, "text": "For example: str=%str:e=% (this will remove e from the input string)" }, { "code": null, "e": 829, "s": 784, "text": "So for removing spaces we will use ‘ : = ‘ ." }, { "code": null, "e": 892, "s": 829, "text": "‘ pause ‘ is used to hold the screen until any key is pressed." }, { "code": null, "e": 898, "s": 892, "text": "Code:" }, { "code": null, "e": 994, "s": 898, "text": "@echo off\nset str=G e e k s f o r G e e k s\necho %str%\nset str=%str: =%\necho %str%\npause" }, { "code": null, "e": 1002, "s": 994, "text": "Output:" }, { "code": null, "e": 1037, "s": 1002, "text": "batch script to remove all spaces." }, { "code": null, "e": 1050, "s": 1037, "text": "Batch-script" }, { "code": null, "e": 1057, "s": 1050, "text": "Picked" }, { "code": null, "e": 1068, "s": 1057, "text": "Linux-Unix" }, { "code": null, "e": 1166, "s": 1068, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1192, "s": 1166, "text": "Docker - COPY Instruction" }, { "code": null, "e": 1227, "s": 1192, "text": "scp command in Linux with Examples" }, { "code": null, "e": 1264, "s": 1227, "text": "chown command in Linux with Examples" }, { "code": null, "e": 1293, "s": 1264, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 1330, "s": 1293, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 1364, "s": 1330, "text": "mv command in Linux with examples" }, { "code": null, "e": 1401, "s": 1364, "text": "chmod command in Linux with examples" }, { "code": null, "e": 1441, "s": 1401, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 1480, "s": 1441, "text": "Introduction to Linux Operating System" } ]
Java Program to Find the Area of a Triangle
02 Dec, 2020 A triangle is a polygon. It has three edges and three vertices and each vertex from an angle. It is a closed 2-dimensional shape. In this article, we will learn how to find the area of the triangle. There can be two possibilities while calculating the area of the triangle as per cases Using the height and base of the triangle Using the 3 sides of the triangle Case 1: When the height and base of the triangle are given, then the area of the triangle is half the product of its base and height. Formula: Area of triangle: Area = (height×base)/2 Example 1: Evaluation of area using base and height Java // Java program to find the// area of the triangle // Importing java librariesimport java.io.*; class GFG { // Function to calculate the // area of the triangle static double area(double h, double b) { // Function returning the value that is // area of a triangle return (h * b) / 2; } // Main driver code public static void main(String[] args) { // Custom inputs- height and base values // Height of the triangle double h = 10; // Base of the triangle double b = 5; // Calling area function and // printing value corresponding area System.out.println("Area of the triangle: " + area(h, b)); }} Output: Area of the triangle: 25.0 Case 2: When the three sides of the triangle are given Now suppose if only sides are known to us then the above formula can not be applied. The area will be calculated using the dimensions of a triangle. This formula is popularly known as Heron’s formula. Algorithm: The Semiperimeter of the triangle is calculated.Product of semi meter with 3 values where these rest of values are the difference of sides from above semi perimeter calculated.Square rooting the above value obtained from the computations gives the area of a triangle. The Semiperimeter of the triangle is calculated. Product of semi meter with 3 values where these rest of values are the difference of sides from above semi perimeter calculated. Square rooting the above value obtained from the computations gives the area of a triangle. Example 2: Java // Java program to find the area of// the triangle using Heron’s formula // Importing java librariesimport java.io.*; class GFG { // Function to calculate the area where parameters // passed are three sides of a triangle static float area(float r, float s, float t) { // Condition check over sides of triangle if (r < 0 || s < 0 || t < 0 || (r + s <= t) || r + t <= s || s + t <= r) // Length of sides must be positive and sum of // any two sides must be smaller than third side { // print message if condition fails System.out.println("Not a valid input"); System.exit(0); } /*else*/ // Finding Semi perimeter of the triangle // using formula float S = (r + s + t) / 2; // Finding the area of the triangle float A = (float)Math.sqrt(S * (S - r) * (S - s) * (S - t)); // return area value return A; } // Main driver code public static void main(String[] args) { // custom inputs of sides of values // Sides of the triangle float r = 5.0f; float s = 6.0f; float t = 7.0f; // Calling area function and // printing the area of triangle System.out.println("Area of the triangle: " + area(r, s, t)); }} Output: Area of the triangle: 14.6969385 Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Dec, 2020" }, { "code": null, "e": 227, "s": 28, "text": "A triangle is a polygon. It has three edges and three vertices and each vertex from an angle. It is a closed 2-dimensional shape. In this article, we will learn how to find the area of the triangle." }, { "code": null, "e": 314, "s": 227, "text": "There can be two possibilities while calculating the area of the triangle as per cases" }, { "code": null, "e": 356, "s": 314, "text": "Using the height and base of the triangle" }, { "code": null, "e": 390, "s": 356, "text": "Using the 3 sides of the triangle" }, { "code": null, "e": 524, "s": 390, "text": "Case 1: When the height and base of the triangle are given, then the area of the triangle is half the product of its base and height." }, { "code": null, "e": 533, "s": 524, "text": "Formula:" }, { "code": null, "e": 574, "s": 533, "text": "Area of triangle: Area = (height×base)/2" }, { "code": null, "e": 627, "s": 574, "text": "Example 1: Evaluation of area using base and height " }, { "code": null, "e": 632, "s": 627, "text": "Java" }, { "code": "// Java program to find the// area of the triangle // Importing java librariesimport java.io.*; class GFG { // Function to calculate the // area of the triangle static double area(double h, double b) { // Function returning the value that is // area of a triangle return (h * b) / 2; } // Main driver code public static void main(String[] args) { // Custom inputs- height and base values // Height of the triangle double h = 10; // Base of the triangle double b = 5; // Calling area function and // printing value corresponding area System.out.println(\"Area of the triangle: \" + area(h, b)); }}", "e": 1369, "s": 632, "text": null }, { "code": null, "e": 1377, "s": 1369, "text": "Output:" }, { "code": null, "e": 1404, "s": 1377, "text": "Area of the triangle: 25.0" }, { "code": null, "e": 1459, "s": 1404, "text": "Case 2: When the three sides of the triangle are given" }, { "code": null, "e": 1660, "s": 1459, "text": "Now suppose if only sides are known to us then the above formula can not be applied. The area will be calculated using the dimensions of a triangle. This formula is popularly known as Heron’s formula." }, { "code": null, "e": 1671, "s": 1660, "text": "Algorithm:" }, { "code": null, "e": 1939, "s": 1671, "text": "The Semiperimeter of the triangle is calculated.Product of semi meter with 3 values where these rest of values are the difference of sides from above semi perimeter calculated.Square rooting the above value obtained from the computations gives the area of a triangle." }, { "code": null, "e": 1988, "s": 1939, "text": "The Semiperimeter of the triangle is calculated." }, { "code": null, "e": 2117, "s": 1988, "text": "Product of semi meter with 3 values where these rest of values are the difference of sides from above semi perimeter calculated." }, { "code": null, "e": 2209, "s": 2117, "text": "Square rooting the above value obtained from the computations gives the area of a triangle." }, { "code": null, "e": 2221, "s": 2209, "text": "Example 2: " }, { "code": null, "e": 2226, "s": 2221, "text": "Java" }, { "code": "// Java program to find the area of// the triangle using Heron’s formula // Importing java librariesimport java.io.*; class GFG { // Function to calculate the area where parameters // passed are three sides of a triangle static float area(float r, float s, float t) { // Condition check over sides of triangle if (r < 0 || s < 0 || t < 0 || (r + s <= t) || r + t <= s || s + t <= r) // Length of sides must be positive and sum of // any two sides must be smaller than third side { // print message if condition fails System.out.println(\"Not a valid input\"); System.exit(0); } /*else*/ // Finding Semi perimeter of the triangle // using formula float S = (r + s + t) / 2; // Finding the area of the triangle float A = (float)Math.sqrt(S * (S - r) * (S - s) * (S - t)); // return area value return A; } // Main driver code public static void main(String[] args) { // custom inputs of sides of values // Sides of the triangle float r = 5.0f; float s = 6.0f; float t = 7.0f; // Calling area function and // printing the area of triangle System.out.println(\"Area of the triangle: \" + area(r, s, t)); }}", "e": 3631, "s": 2226, "text": null }, { "code": null, "e": 3639, "s": 3631, "text": "Output:" }, { "code": null, "e": 3672, "s": 3639, "text": "Area of the triangle: 14.6969385" }, { "code": null, "e": 3679, "s": 3672, "text": "Picked" }, { "code": null, "e": 3684, "s": 3679, "text": "Java" }, { "code": null, "e": 3698, "s": 3684, "text": "Java Programs" }, { "code": null, "e": 3703, "s": 3698, "text": "Java" }, { "code": null, "e": 3801, "s": 3703, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3816, "s": 3801, "text": "Stream In Java" }, { "code": null, "e": 3837, "s": 3816, "text": "Introduction to Java" }, { "code": null, "e": 3858, "s": 3837, "text": "Constructors in Java" }, { "code": null, "e": 3877, "s": 3858, "text": "Exceptions in Java" }, { "code": null, "e": 3894, "s": 3877, "text": "Generics in Java" }, { "code": null, "e": 3920, "s": 3894, "text": "Java Programming Examples" }, { "code": null, "e": 3954, "s": 3920, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 4001, "s": 3954, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 4039, "s": 4001, "text": "Factory method design pattern in Java" } ]
Rabin-Karp algorithm for Pattern Searching in Matrix
06 Aug, 2021 Given matrices txt[][] of dimensions m1 x m2 and pattern pat[][] of dimensions n1 x n2, the task is to check whether a pattern exists in the matrix or not, and if yes then print the top most indices of the pat[][] in txt[][]. It is assumed that m1, m2 ≥ n1, n2 Examples: Input: txt[][] = {{G, H, I, P} {J, K, L, Q} {R, G, H, I} {S, J, K, L} } pat[][] = {{G, H, I}, {J, K, L} } Output: Pattern found at ( 0, 0 ) Pattern found at ( 2, 1 ) Explanation: Input: txt[][] = { {A, B, C}, {D, E, F}, {G, H, I} } pat[][] = { {E, F}, {H, I} } Output: Pattern found at (1, 1) Approach: In order to find a pattern in a 2-D array using Rabin-Karp algorithm, consider an input matrix txt[m1][m2] and a pattern pat[n1][n2]. The idea is to find the hash of each columns of mat[][] and pat[][] and compare the hash values. For any column if hash values are equals than check for the corresponding rows values. Below are the steps: Find the hash values of each column for the first N1 rows in both txt[][] and pat[][] matrix.Apply Rabin-Karp Algorithm by finding hash values for the column hashes found in step 1.If a match is found compare txt[][] and pat[][] matrices for the specific rows and columns.Else slide down the column hashes by 1 row in the txt matrix using a rolling hash.Repeat steps 2 to 4 for all the hash values and if we found any pat[][] match in txt[][] then print the indices of top most cell in the txt[][]. Find the hash values of each column for the first N1 rows in both txt[][] and pat[][] matrix. Apply Rabin-Karp Algorithm by finding hash values for the column hashes found in step 1. If a match is found compare txt[][] and pat[][] matrices for the specific rows and columns. Else slide down the column hashes by 1 row in the txt matrix using a rolling hash. Repeat steps 2 to 4 for all the hash values and if we found any pat[][] match in txt[][] then print the indices of top most cell in the txt[][]. To find the hash value: In order to find the hash value of a substring of size N in a text using rolling hash follow below steps: Remove the first character from the string: hash(txt[s:s+n-1])-(radix**(n-1)*txt[s])%prime_numberAdd the next character to the string: hash(txt[s:s+n-1])*radix + txt[n] Remove the first character from the string: hash(txt[s:s+n-1])-(radix**(n-1)*txt[s])%prime_number Add the next character to the string: hash(txt[s:s+n-1])*radix + txt[n] Below is the implementation of the above approach: C++ Python3 #include <bits/stdc++.h>using namespace std;long long mod = 257; //The modular valuelong long r = 256; //radixlong long dr = 1; //Highest power for row hashinglong long dc = 1; //Highest power for col hashing //func that return a power n under mod m in LogNlong long power(int a,int n,long long m){ if(n == 0){ return 1; } if(n == 1){ return a%m; } long long pow = power(a,n/2,m); if(n&1){ return ((a%m)*(pow)%m * (pow)%m)%m; } else{ return ((pow)%m * (pow)%m)%m; }}//Checks if all values of pattern matches with the textbool check(vector<vector<char>> &txt,vector<vector<char>> &pat, long long r,long long c){ for(long long i=0;i<pat.size();i++){ for(long long j=0;j<pat[0].size();j++){ if(pat[i][j] != txt[i+r][j+c]) return false; } } return true;}//Finds the first hash of first n rows where n is no. of rows in patternvector<long long> findHash(vector<vector<char>> &mat,long long row){ vector<long long> hash; long long col = mat[0].size(); for(long long i=0;i<col;i++){ long long h = 0; for(long long j=0;j<row;j++){ h = ((h*r)%mod + mat[j][i]%mod)%mod; } hash.push_back(h); } return hash;}//rolling hash function for columnsvoid colRollingHash(vector<vector<char>> &txt, vector<long long> &t_hash, long long row, long long p_row){ for(long long i=0;i<t_hash.size();i++){ t_hash[i] = (t_hash[i]%mod - ((txt[row][i])%mod*(dr)%mod)%mod)%mod; t_hash[i] = ((t_hash[i]%mod) * (r%mod))%mod; t_hash[i] = (t_hash[i]%mod + txt[row+p_row][i]%mod)%mod; }}void rabinKarp(vector<vector<char>> &txt, vector<vector<char>> &pat){ long long t_row = txt.size(); long long t_col = txt[0].size(); long long p_row = pat.size(); long long p_col = pat[0].size(); dr = power(r,p_row-1,mod); dc = power(r,p_col-1,mod); vector<long long> t_hash = findHash(txt,p_row); //column hash of p_row rows vector<long long> p_hash = findHash(pat,p_row); //column hash of p_row rows long long p_val = 0; //hash of entire pattern matrix for(long long i=0;i<p_col;i++){ p_val = (p_val*r + p_hash[i])%mod; } for(long long i=0;i<=(t_row-p_row);i++){ long long t_val = 0; for(long long i=0;i<p_col;i++){ t_val = ((t_val*r) + t_hash[i])%mod; } for(long long j=0;j<=(t_col-p_col);j++){ if(p_val == t_val){ if(check(txt,pat,i,j)){ cout<<i<<" "<<j<<endl; } } //calculating t_val for next set of columns t_val = (t_val%mod - ((t_hash[j]%mod)*(dc%mod))%mod + mod)%mod; t_val = (t_val%mod * r%mod)%mod; t_val = (t_val%mod + t_hash[j+p_col]%mod)%mod; } if(i < t_row-p_row){ //call this function for hashing form next row colRollingHash(txt,t_hash,i,p_row); } }}int main(){ vector<vector<char>> txt{{'A','B','C','D','E'},{'A','B','C','D','E'},{'A','B','C','D','E'},{'A','B','C','D','E'},{'A','B','C','D','E'}}; vector<vector<char>> pat{{'A','B','C','D','E'},{'A','B','C','D','E'},{'A','B','C','D','E'},{'A','B','C','D','E'}}; //function prints the indices of row and col where its a match in txt rabinKarp(txt,pat); return 0;} # Python implementation for the# pattern matching in 2-D matrix # Function to find the hash-value# of the given columns of textdef findHash(arr, col, row): hashCol = [] add = 0 radix = 256 # For each column for i in range(0, col): for j in reversed(range(0, row)): add = add + (radix**(row-j-1) * ord(arr[j][i]))% 101 hashCol.append(add % 101); add = 0 return hashCol # Function to check equality of the# two stringsdef checkEquality(txt, row, col, flag): txt = [txt[i][col:patCol + col] for i in range(row, patRow + row)] # If pattern found if txt == pat: flag = 1 print("Pattern found at", \ "(", row, ", ", col, ")") return flag # Function to find the hash value of# of the next column using rolling-hash# of the Rabin-karpdef colRollingHash(txtHash, nxtRow): radix = 256 # Find the hash of the matrix for j in range(len(txtHash)): txtHash[j] = (txtHash[j]*radix \ + ord(txt[nxtRow][j]))% 101 txtHash[j] = txtHash[j] - (radix**(patRow) * ord(txt[nxtRow-patRow][j]))% 101 txtHash[j] = txtHash[j]% 101 return txtHash # Function to match a pattern in# the given 2D Matrixdef search(txt, pat): # List of the hashed value for # the text and pattern columns patHash = [] txtHash = [] # Hash value of the # pat_hash and txt_hash patVal = 0 txtVal = 0 # Radix value for the input characters radix = 256 # Variable to determine if # pattern was found or not flag = 0 # Function call to find the # hash value of columns txtHash = findHash(txt, txtCol, patRow) patHash = findHash(pat, patCol, patRow) # Calculate hash value for patHash for i in range(len(patHash)): patVal = patVal \ + (radix**(len(patHash)-i-1) * patHash[i]% 101) patVal = patVal % 101 # Applying Rabin-Karp to compare # txtHash and patHash for i in range(patRow-1, txtRow): col = 0 txtVal = 0 # Find the hash value txtHash for j in range(len(patHash)): txtVal = txtVal\ + (radix**(len(patHash)-j-1) * txtHash[j])% 101 txtVal = txtVal % 101 if txtVal == patVal: flag = checkEquality(\ txt, i + 1-patRow, col, flag) else: # Roll the txt window by one character for k in range(len(patHash), len(txtHash)): txtVal = txtVal \ * radix + (txtHash[k])% 101 txtVal = txtVal \ - (radix**(len(patHash)) * (txtHash[k-len(patHash)]))% 101 txtVal = txtVal % 101 col = col + 1 # Check if txtVal and patVal are equal if patVal == txtVal: flag = checkEquality(\ txt, i + 1-patRow, col, flag) else: continue # To make sure i does not exceed txtRow if i + 1<txtRow: txtHash = colRollingHash(txtHash, i + 1) if flag == 0: print("Pattern not found") # Driver Codeif __name__ == "__main__": # Given Text txt = [['A', 'B', 'C'], \ ['D', 'E', 'F'], \ ['G', 'H', 'I']] # Given Pattern pat = [['E', 'F'], ['H', 'I']] # Dimensions of the text txtRow = 3 txtCol = 3 # Dimensions for the pattern patRow = 2 patCol = 2 # Function Call search(txt, pat) Pattern found at ( 1 , 1 ) pramodtarpe adnanirshad158 Hash Greedy Hash Mathematical Matrix Searching Searching Hash Greedy Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Shortest Job First (or SJF) CPU Scheduling Non-preemptive algorithm using Segment Tree Greedy Algorithm for Egyptian Fraction Huffman Decoding Bin Packing Problem (Minimize number of used Bins) Boruvka's algorithm | Greedy Algo-9 Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) What is Hashing | A Complete Tutorial Hashing | Set 1 (Introduction) Internal Working of HashMap in Java Count pairs with given sum
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Aug, 2021" }, { "code": null, "e": 313, "s": 52, "text": "Given matrices txt[][] of dimensions m1 x m2 and pattern pat[][] of dimensions n1 x n2, the task is to check whether a pattern exists in the matrix or not, and if yes then print the top most indices of the pat[][] in txt[][]. It is assumed that m1, m2 ≥ n1, n2" }, { "code": null, "e": 324, "s": 313, "text": "Examples: " }, { "code": null, "e": 741, "s": 324, "text": "Input:\ntxt[][] = {{G, H, I, P}\n {J, K, L, Q}\n {R, G, H, I} \n {S, J, K, L}\n }\npat[][] = {{G, H, I},\n {J, K, L}\n }\nOutput:\nPattern found at ( 0, 0 )\nPattern found at ( 2, 1 )\nExplanation:\n\n\nInput:\ntxt[][] = { {A, B, C},\n {D, E, F},\n {G, H, I}\n }\npat[][] = { {E, F},\n {H, I}\n }\nOutput:\nPattern found at (1, 1)" }, { "code": null, "e": 1090, "s": 741, "text": "Approach: In order to find a pattern in a 2-D array using Rabin-Karp algorithm, consider an input matrix txt[m1][m2] and a pattern pat[n1][n2]. The idea is to find the hash of each columns of mat[][] and pat[][] and compare the hash values. For any column if hash values are equals than check for the corresponding rows values. Below are the steps:" }, { "code": null, "e": 1589, "s": 1090, "text": "Find the hash values of each column for the first N1 rows in both txt[][] and pat[][] matrix.Apply Rabin-Karp Algorithm by finding hash values for the column hashes found in step 1.If a match is found compare txt[][] and pat[][] matrices for the specific rows and columns.Else slide down the column hashes by 1 row in the txt matrix using a rolling hash.Repeat steps 2 to 4 for all the hash values and if we found any pat[][] match in txt[][] then print the indices of top most cell in the txt[][]." }, { "code": null, "e": 1683, "s": 1589, "text": "Find the hash values of each column for the first N1 rows in both txt[][] and pat[][] matrix." }, { "code": null, "e": 1772, "s": 1683, "text": "Apply Rabin-Karp Algorithm by finding hash values for the column hashes found in step 1." }, { "code": null, "e": 1864, "s": 1772, "text": "If a match is found compare txt[][] and pat[][] matrices for the specific rows and columns." }, { "code": null, "e": 1947, "s": 1864, "text": "Else slide down the column hashes by 1 row in the txt matrix using a rolling hash." }, { "code": null, "e": 2092, "s": 1947, "text": "Repeat steps 2 to 4 for all the hash values and if we found any pat[][] match in txt[][] then print the indices of top most cell in the txt[][]." }, { "code": null, "e": 2224, "s": 2092, "text": "To find the hash value: In order to find the hash value of a substring of size N in a text using rolling hash follow below steps: " }, { "code": null, "e": 2393, "s": 2224, "text": "Remove the first character from the string: hash(txt[s:s+n-1])-(radix**(n-1)*txt[s])%prime_numberAdd the next character to the string: hash(txt[s:s+n-1])*radix + txt[n]" }, { "code": null, "e": 2491, "s": 2393, "text": "Remove the first character from the string: hash(txt[s:s+n-1])-(radix**(n-1)*txt[s])%prime_number" }, { "code": null, "e": 2563, "s": 2491, "text": "Add the next character to the string: hash(txt[s:s+n-1])*radix + txt[n]" }, { "code": null, "e": 2615, "s": 2563, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 2619, "s": 2615, "text": "C++" }, { "code": null, "e": 2627, "s": 2619, "text": "Python3" }, { "code": "#include <bits/stdc++.h>using namespace std;long long mod = 257; //The modular valuelong long r = 256; //radixlong long dr = 1; //Highest power for row hashinglong long dc = 1; //Highest power for col hashing //func that return a power n under mod m in LogNlong long power(int a,int n,long long m){ if(n == 0){ return 1; } if(n == 1){ return a%m; } long long pow = power(a,n/2,m); if(n&1){ return ((a%m)*(pow)%m * (pow)%m)%m; } else{ return ((pow)%m * (pow)%m)%m; }}//Checks if all values of pattern matches with the textbool check(vector<vector<char>> &txt,vector<vector<char>> &pat, long long r,long long c){ for(long long i=0;i<pat.size();i++){ for(long long j=0;j<pat[0].size();j++){ if(pat[i][j] != txt[i+r][j+c]) return false; } } return true;}//Finds the first hash of first n rows where n is no. of rows in patternvector<long long> findHash(vector<vector<char>> &mat,long long row){ vector<long long> hash; long long col = mat[0].size(); for(long long i=0;i<col;i++){ long long h = 0; for(long long j=0;j<row;j++){ h = ((h*r)%mod + mat[j][i]%mod)%mod; } hash.push_back(h); } return hash;}//rolling hash function for columnsvoid colRollingHash(vector<vector<char>> &txt, vector<long long> &t_hash, long long row, long long p_row){ for(long long i=0;i<t_hash.size();i++){ t_hash[i] = (t_hash[i]%mod - ((txt[row][i])%mod*(dr)%mod)%mod)%mod; t_hash[i] = ((t_hash[i]%mod) * (r%mod))%mod; t_hash[i] = (t_hash[i]%mod + txt[row+p_row][i]%mod)%mod; }}void rabinKarp(vector<vector<char>> &txt, vector<vector<char>> &pat){ long long t_row = txt.size(); long long t_col = txt[0].size(); long long p_row = pat.size(); long long p_col = pat[0].size(); dr = power(r,p_row-1,mod); dc = power(r,p_col-1,mod); vector<long long> t_hash = findHash(txt,p_row); //column hash of p_row rows vector<long long> p_hash = findHash(pat,p_row); //column hash of p_row rows long long p_val = 0; //hash of entire pattern matrix for(long long i=0;i<p_col;i++){ p_val = (p_val*r + p_hash[i])%mod; } for(long long i=0;i<=(t_row-p_row);i++){ long long t_val = 0; for(long long i=0;i<p_col;i++){ t_val = ((t_val*r) + t_hash[i])%mod; } for(long long j=0;j<=(t_col-p_col);j++){ if(p_val == t_val){ if(check(txt,pat,i,j)){ cout<<i<<\" \"<<j<<endl; } } //calculating t_val for next set of columns t_val = (t_val%mod - ((t_hash[j]%mod)*(dc%mod))%mod + mod)%mod; t_val = (t_val%mod * r%mod)%mod; t_val = (t_val%mod + t_hash[j+p_col]%mod)%mod; } if(i < t_row-p_row){ //call this function for hashing form next row colRollingHash(txt,t_hash,i,p_row); } }}int main(){ vector<vector<char>> txt{{'A','B','C','D','E'},{'A','B','C','D','E'},{'A','B','C','D','E'},{'A','B','C','D','E'},{'A','B','C','D','E'}}; vector<vector<char>> pat{{'A','B','C','D','E'},{'A','B','C','D','E'},{'A','B','C','D','E'},{'A','B','C','D','E'}}; //function prints the indices of row and col where its a match in txt rabinKarp(txt,pat); return 0;}", "e": 5700, "s": 2627, "text": null }, { "code": "# Python implementation for the# pattern matching in 2-D matrix # Function to find the hash-value# of the given columns of textdef findHash(arr, col, row): hashCol = [] add = 0 radix = 256 # For each column for i in range(0, col): for j in reversed(range(0, row)): add = add + (radix**(row-j-1) * ord(arr[j][i]))% 101 hashCol.append(add % 101); add = 0 return hashCol # Function to check equality of the# two stringsdef checkEquality(txt, row, col, flag): txt = [txt[i][col:patCol + col] for i in range(row, patRow + row)] # If pattern found if txt == pat: flag = 1 print(\"Pattern found at\", \\ \"(\", row, \", \", col, \")\") return flag # Function to find the hash value of# of the next column using rolling-hash# of the Rabin-karpdef colRollingHash(txtHash, nxtRow): radix = 256 # Find the hash of the matrix for j in range(len(txtHash)): txtHash[j] = (txtHash[j]*radix \\ + ord(txt[nxtRow][j]))% 101 txtHash[j] = txtHash[j] - (radix**(patRow) * ord(txt[nxtRow-patRow][j]))% 101 txtHash[j] = txtHash[j]% 101 return txtHash # Function to match a pattern in# the given 2D Matrixdef search(txt, pat): # List of the hashed value for # the text and pattern columns patHash = [] txtHash = [] # Hash value of the # pat_hash and txt_hash patVal = 0 txtVal = 0 # Radix value for the input characters radix = 256 # Variable to determine if # pattern was found or not flag = 0 # Function call to find the # hash value of columns txtHash = findHash(txt, txtCol, patRow) patHash = findHash(pat, patCol, patRow) # Calculate hash value for patHash for i in range(len(patHash)): patVal = patVal \\ + (radix**(len(patHash)-i-1) * patHash[i]% 101) patVal = patVal % 101 # Applying Rabin-Karp to compare # txtHash and patHash for i in range(patRow-1, txtRow): col = 0 txtVal = 0 # Find the hash value txtHash for j in range(len(patHash)): txtVal = txtVal\\ + (radix**(len(patHash)-j-1) * txtHash[j])% 101 txtVal = txtVal % 101 if txtVal == patVal: flag = checkEquality(\\ txt, i + 1-patRow, col, flag) else: # Roll the txt window by one character for k in range(len(patHash), len(txtHash)): txtVal = txtVal \\ * radix + (txtHash[k])% 101 txtVal = txtVal \\ - (radix**(len(patHash)) * (txtHash[k-len(patHash)]))% 101 txtVal = txtVal % 101 col = col + 1 # Check if txtVal and patVal are equal if patVal == txtVal: flag = checkEquality(\\ txt, i + 1-patRow, col, flag) else: continue # To make sure i does not exceed txtRow if i + 1<txtRow: txtHash = colRollingHash(txtHash, i + 1) if flag == 0: print(\"Pattern not found\") # Driver Codeif __name__ == \"__main__\": # Given Text txt = [['A', 'B', 'C'], \\ ['D', 'E', 'F'], \\ ['G', 'H', 'I']] # Given Pattern pat = [['E', 'F'], ['H', 'I']] # Dimensions of the text txtRow = 3 txtCol = 3 # Dimensions for the pattern patRow = 2 patCol = 2 # Function Call search(txt, pat)", "e": 9360, "s": 5700, "text": null }, { "code": null, "e": 9388, "s": 9360, "text": "Pattern found at ( 1 , 1 )" }, { "code": null, "e": 9400, "s": 9388, "text": "pramodtarpe" }, { "code": null, "e": 9415, "s": 9400, "text": "adnanirshad158" }, { "code": null, "e": 9420, "s": 9415, "text": "Hash" }, { "code": null, "e": 9427, "s": 9420, "text": "Greedy" }, { "code": null, "e": 9432, "s": 9427, "text": "Hash" }, { "code": null, "e": 9445, "s": 9432, "text": "Mathematical" }, { "code": null, "e": 9452, "s": 9445, "text": "Matrix" }, { "code": null, "e": 9462, "s": 9452, "text": "Searching" }, { "code": null, "e": 9472, "s": 9462, "text": "Searching" }, { "code": null, "e": 9477, "s": 9472, "text": "Hash" }, { "code": null, "e": 9484, "s": 9477, "text": "Greedy" }, { "code": null, "e": 9497, "s": 9484, "text": "Mathematical" }, { "code": null, "e": 9504, "s": 9497, "text": "Matrix" }, { "code": null, "e": 9602, "s": 9504, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9689, "s": 9602, "text": "Shortest Job First (or SJF) CPU Scheduling Non-preemptive algorithm using Segment Tree" }, { "code": null, "e": 9728, "s": 9689, "text": "Greedy Algorithm for Egyptian Fraction" }, { "code": null, "e": 9745, "s": 9728, "text": "Huffman Decoding" }, { "code": null, "e": 9796, "s": 9745, "text": "Bin Packing Problem (Minimize number of used Bins)" }, { "code": null, "e": 9832, "s": 9796, "text": "Boruvka's algorithm | Greedy Algo-9" }, { "code": null, "e": 9917, "s": 9832, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 9955, "s": 9917, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 9986, "s": 9955, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 10022, "s": 9986, "text": "Internal Working of HashMap in Java" } ]
Perl | index() Function
25 Jun, 2019 This function returns the position of the first occurrence of given substring (or pattern) in a string (or text). We can specify start position. By default, it searches from the beginning(i.e. from index zero). Syntax:# Searches pat in text from given indexindex(text, pat, index) # Searches pat in textindex(text, pat) Parameters: text: String in which substring is to be searched. pat: Substring to be searched. index: Starting index(set by the user or it takes zero by default). Returns:-1 on failure otherwise Position of the matching string. Example 1: #!/usr/bin/perl # String from which Substring # is to be searched $string = "Geeks are the best"; # Using index() to search for substring$index = index ($string, 'the'); # Printing the position of the substringprint "Position of 'the' in the string: $index\n"; Position of 'the' in the string: 10 Example 2: #!/usr/bin/perl # String from which Substring # is to be searched $string = "Geeks are the best"; # Defining the starting Index$pos = 3; # Using index() to search for substring$index = index ($string, 'Geeks', $pos); # Printing the position of the substringprint "Position of 'Geeks' in the string: $index\n"; Position of 'Geeks' in the string: -1 Here, in the second example the position is set to ‘3’, i.e. the starting index from where searching is to begin is from 3rd position. Hence, the substring is not found in the String. Perl-function Perl-String Perl-String-Functions Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | Arrays (push, pop, shift, unshift) Perl | Arrays Perl Tutorial - Learn Perl With Examples Perl | Polymorphism in OOPs Perl | Boolean Values Perl | Subroutines or Functions Use of print() and say() in Perl Perl | Basic Syntax of a Perl Program Hello World Program in Perl Introduction to Perl
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jun, 2019" }, { "code": null, "e": 239, "s": 28, "text": "This function returns the position of the first occurrence of given substring (or pattern) in a string (or text). We can specify start position. By default, it searches from the beginning(i.e. from index zero)." }, { "code": null, "e": 309, "s": 239, "text": "Syntax:# Searches pat in text from given indexindex(text, pat, index)" }, { "code": null, "e": 348, "s": 309, "text": "# Searches pat in textindex(text, pat)" }, { "code": null, "e": 360, "s": 348, "text": "Parameters:" }, { "code": null, "e": 411, "s": 360, "text": "text: String in which substring is to be searched." }, { "code": null, "e": 442, "s": 411, "text": "pat: Substring to be searched." }, { "code": null, "e": 510, "s": 442, "text": "index: Starting index(set by the user or it takes zero by default)." }, { "code": null, "e": 575, "s": 510, "text": "Returns:-1 on failure otherwise Position of the matching string." }, { "code": null, "e": 586, "s": 575, "text": "Example 1:" }, { "code": "#!/usr/bin/perl # String from which Substring # is to be searched $string = \"Geeks are the best\"; # Using index() to search for substring$index = index ($string, 'the'); # Printing the position of the substringprint \"Position of 'the' in the string: $index\\n\";", "e": 850, "s": 586, "text": null }, { "code": null, "e": 887, "s": 850, "text": "Position of 'the' in the string: 10\n" }, { "code": null, "e": 898, "s": 887, "text": "Example 2:" }, { "code": "#!/usr/bin/perl # String from which Substring # is to be searched $string = \"Geeks are the best\"; # Defining the starting Index$pos = 3; # Using index() to search for substring$index = index ($string, 'Geeks', $pos); # Printing the position of the substringprint \"Position of 'Geeks' in the string: $index\\n\";", "e": 1212, "s": 898, "text": null }, { "code": null, "e": 1251, "s": 1212, "text": "Position of 'Geeks' in the string: -1\n" }, { "code": null, "e": 1435, "s": 1251, "text": "Here, in the second example the position is set to ‘3’, i.e. the starting index from where searching is to begin is from 3rd position. Hence, the substring is not found in the String." }, { "code": null, "e": 1449, "s": 1435, "text": "Perl-function" }, { "code": null, "e": 1461, "s": 1449, "text": "Perl-String" }, { "code": null, "e": 1483, "s": 1461, "text": "Perl-String-Functions" }, { "code": null, "e": 1488, "s": 1483, "text": "Perl" }, { "code": null, "e": 1493, "s": 1488, "text": "Perl" }, { "code": null, "e": 1591, "s": 1493, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1633, "s": 1591, "text": "Perl | Arrays (push, pop, shift, unshift)" }, { "code": null, "e": 1647, "s": 1633, "text": "Perl | Arrays" }, { "code": null, "e": 1688, "s": 1647, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 1716, "s": 1688, "text": "Perl | Polymorphism in OOPs" }, { "code": null, "e": 1738, "s": 1716, "text": "Perl | Boolean Values" }, { "code": null, "e": 1770, "s": 1738, "text": "Perl | Subroutines or Functions" }, { "code": null, "e": 1803, "s": 1770, "text": "Use of print() and say() in Perl" }, { "code": null, "e": 1841, "s": 1803, "text": "Perl | Basic Syntax of a Perl Program" }, { "code": null, "e": 1869, "s": 1841, "text": "Hello World Program in Perl" } ]
Interesting facts about null in Java
09 Jun, 2022 Almost all the programming languages are bonded with null. There is hardly a programmer, who is not troubled by null. In Java, null is associated java.lang.NullPointerException. As it is a class in java.lang package, it is called when we try to perform some operations with or without null, and sometimes we don’t even know where it has happened. Below are some important points about null in java that every Java programmer should know: 1. null is Case sensitive: null is literal in Java and because keywords are case-sensitive in java, we can’t write NULL or 0 as in C language. Java public class Test{ public static void main (String[] args) throws java.lang.Exception { // compile-time error : can't find symbol 'NULL' Object obj = NULL; //runs successfully Object obj1 = null; }} Output: 5: error: cannot find symbol can't find symbol 'NULL' ^ variable NULL class Test 1 error 2. Reference Variable value: Any reference variable in Java has a default value null. Java public class Test{ private static Object obj; public static void main(String args[]) { // it will print null; System.out.println("Value of object obj is : " + obj); }} Output: Value of object obj is : null 3. Type of null: Unlike the common misconception, null is not Object or neither a type. It’s just a special value, which can be assigned to any reference type and you can type cast null to any type Examples: // null can be assigned to String String str = null; // you can assign null to Integer also Integer itr = null; // null can also be assigned to Double Double dbl = null; // null can be type cast to String String myStr = (String) null; // it can also be type casted to Integer Integer myItr = (Integer) null; // yes it's possible, no error Double myDbl = (Double) null; 4. Autoboxing and unboxing : During auto-boxing and unboxing operations, compiler simply throws Nullpointer exception error if a null value is assigned to primitive boxed data type. Java public class Test { public static void main(String[] args) throws java.lang.Exception { // An integer can be null, so this is fine Integer i = null; // Unboxing null to integer throws // NullpointerException int a = i; }} Output: Exception in thread "main" java.lang.NullPointerException at Test.main(Test.java:6) 5. instanceof operator: The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface). At run time, the result of the instanceof operator is true if the value of the Expression is not null. This is an important property of instanceof operation which makes it useful for type casting checks. Java public class Test { public static void main(String[] args) throws java.lang.Exception { Integer i = null; Integer j = 10; // prints false System.out.println(i instanceof Integer); // Compiles successfully System.out.println(j instanceof Integer); }} Output: false true 6. Static vs Non static Methods: We cannot call a non-static method on a reference variable with null value, it will throw NullPointerException, but we can call static method with reference variables with null values. Since static methods are bonded using static binding, they won’t throw Null pointer Exception. Java public class Test { public static void main(String args[]) { Test obj = null; obj.staticMethod(); obj.nonStaticMethod(); } private static void staticMethod() { // Can be called by null reference System.out.println( " static method, can be called by null reference & quot;); } private void nonStaticMethod() { // Can not be called by null reference System.out.print(" Non - static method - "); System.out.println( " cannot be called by null reference & quot;); }} Output: static method, can be called by null referenceException in thread "main" java.lang.NullPointerException at Test.main(Test.java:5) 7. == and != The comparison and not equal to operators are allowed with null in Java. This can made useful in checking of null with objects in java. Java public class Test { public static void main(String args[]) { // return true; System.out.println(null == null); // return false; System.out.println(null != null); }} Output: true false 8. “null” can be passed as an argument in the method : We can pass the null as an argument in java and we can print the same. The data type of argument should be Reference Type. But the return type of method could be any type as void, int, double or any other reference type depending upon the logic of program. Here, the method “print_null” will simply print the argument which is passed from the main method. Java import java.io.*; class GFG { public static void print_null(String str) { System.out.println("Hey, I am : " + str); } public static void main(String[] args) { GFG.print_null(null); }} Output : Hey, I am : null 9. ‘+’ operator on null : We can concatenate the null value with String variables in java. It is considered a concatenation in java. Here, the null will only be concatenated with the String variable. If we use “+” operator with null and any other type(Integer, Double, etc.,) other than String, it will throw an error message. Integer a=null+7 will throw an error message as “bad operand types for binary operator ‘+’ “ Java import java.io.*; class GFG { public static void main(String[] args) { String str1 = null; String str2 = "_value"; String output = str1 + str2; System.out.println("Concatenated value : " + output); }} Concatenated value : null_value This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. Akanksha_Rai keerthikarathan123 interesting-facts Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Jun, 2022" }, { "code": null, "e": 491, "s": 52, "text": "Almost all the programming languages are bonded with null. There is hardly a programmer, who is not troubled by null. In Java, null is associated java.lang.NullPointerException. As it is a class in java.lang package, it is called when we try to perform some operations with or without null, and sometimes we don’t even know where it has happened. Below are some important points about null in java that every Java programmer should know: " }, { "code": null, "e": 635, "s": 491, "text": "1. null is Case sensitive: null is literal in Java and because keywords are case-sensitive in java, we can’t write NULL or 0 as in C language. " }, { "code": null, "e": 640, "s": 635, "text": "Java" }, { "code": "public class Test{ public static void main (String[] args) throws java.lang.Exception { // compile-time error : can't find symbol 'NULL' Object obj = NULL; //runs successfully Object obj1 = null; }}", "e": 885, "s": 640, "text": null }, { "code": null, "e": 893, "s": 885, "text": "Output:" }, { "code": null, "e": 1005, "s": 893, "text": "5: error: cannot find symbol\n can't find symbol 'NULL'\n ^\n variable NULL\n class Test\n1 error " }, { "code": null, "e": 1092, "s": 1005, "text": "2. Reference Variable value: Any reference variable in Java has a default value null. " }, { "code": null, "e": 1097, "s": 1092, "text": "Java" }, { "code": "public class Test{ private static Object obj; public static void main(String args[]) { // it will print null; System.out.println(\"Value of object obj is : \" + obj); }}", "e": 1291, "s": 1097, "text": null }, { "code": null, "e": 1299, "s": 1291, "text": "Output:" }, { "code": null, "e": 1330, "s": 1299, "text": "Value of object obj is : null " }, { "code": null, "e": 1538, "s": 1330, "text": "3. Type of null: Unlike the common misconception, null is not Object or neither a type. It’s just a special value, which can be assigned to any reference type and you can type cast null to any type Examples:" }, { "code": null, "e": 1990, "s": 1538, "text": " // null can be assigned to String\n String str = null; \n \n // you can assign null to Integer also\n Integer itr = null; \n \n // null can also be assigned to Double\n Double dbl = null; \n \n // null can be type cast to String\n String myStr = (String) null; \n \n // it can also be type casted to Integer\n Integer myItr = (Integer) null; \n \n // yes it's possible, no error\n Double myDbl = (Double) null; " }, { "code": null, "e": 2173, "s": 1990, "text": "4. Autoboxing and unboxing : During auto-boxing and unboxing operations, compiler simply throws Nullpointer exception error if a null value is assigned to primitive boxed data type. " }, { "code": null, "e": 2178, "s": 2173, "text": "Java" }, { "code": "public class Test { public static void main(String[] args) throws java.lang.Exception { // An integer can be null, so this is fine Integer i = null; // Unboxing null to integer throws // NullpointerException int a = i; }}", "e": 2452, "s": 2178, "text": null }, { "code": null, "e": 2460, "s": 2452, "text": "Output:" }, { "code": null, "e": 2550, "s": 2460, "text": " Exception in thread \"main\" java.lang.NullPointerException\n at Test.main(Test.java:6) " }, { "code": null, "e": 2914, "s": 2550, "text": "5. instanceof operator: The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface). At run time, the result of the instanceof operator is true if the value of the Expression is not null. This is an important property of instanceof operation which makes it useful for type casting checks. " }, { "code": null, "e": 2919, "s": 2914, "text": "Java" }, { "code": "public class Test { public static void main(String[] args) throws java.lang.Exception { Integer i = null; Integer j = 10; // prints false System.out.println(i instanceof Integer); // Compiles successfully System.out.println(j instanceof Integer); }}", "e": 3229, "s": 2919, "text": null }, { "code": null, "e": 3237, "s": 3229, "text": "Output:" }, { "code": null, "e": 3249, "s": 3237, "text": "false \ntrue" }, { "code": null, "e": 3563, "s": 3249, "text": "6. Static vs Non static Methods: We cannot call a non-static method on a reference variable with null value, it will throw NullPointerException, but we can call static method with reference variables with null values. Since static methods are bonded using static binding, they won’t throw Null pointer Exception. " }, { "code": null, "e": 3568, "s": 3563, "text": "Java" }, { "code": "public class Test { public static void main(String args[]) { Test obj = null; obj.staticMethod(); obj.nonStaticMethod(); } private static void staticMethod() { // Can be called by null reference System.out.println( \" static method, can be called by null reference & quot;); } private void nonStaticMethod() { // Can not be called by null reference System.out.print(\" Non - static method - \"); System.out.println( \" cannot be called by null reference & quot;); }}", "e": 4191, "s": 3568, "text": null }, { "code": null, "e": 4199, "s": 4191, "text": "Output:" }, { "code": null, "e": 4335, "s": 4199, "text": "static method, can be called by null referenceException in thread \"main\" \njava.lang.NullPointerException\n at Test.main(Test.java:5) " }, { "code": null, "e": 4485, "s": 4335, "text": "7. == and != The comparison and not equal to operators are allowed with null in Java. This can made useful in checking of null with objects in java. " }, { "code": null, "e": 4490, "s": 4485, "text": "Java" }, { "code": "public class Test { public static void main(String args[]) { // return true; System.out.println(null == null); // return false; System.out.println(null != null); }}", "e": 4694, "s": 4490, "text": null }, { "code": null, "e": 4702, "s": 4694, "text": "Output:" }, { "code": null, "e": 4713, "s": 4702, "text": "true\nfalse" }, { "code": null, "e": 4768, "s": 4713, "text": "8. “null” can be passed as an argument in the method :" }, { "code": null, "e": 5025, "s": 4768, "text": "We can pass the null as an argument in java and we can print the same. The data type of argument should be Reference Type. But the return type of method could be any type as void, int, double or any other reference type depending upon the logic of program." }, { "code": null, "e": 5124, "s": 5025, "text": "Here, the method “print_null” will simply print the argument which is passed from the main method." }, { "code": null, "e": 5129, "s": 5124, "text": "Java" }, { "code": "import java.io.*; class GFG { public static void print_null(String str) { System.out.println(\"Hey, I am : \" + str); } public static void main(String[] args) { GFG.print_null(null); }}", "e": 5345, "s": 5129, "text": null }, { "code": null, "e": 5354, "s": 5345, "text": "Output :" }, { "code": null, "e": 5371, "s": 5354, "text": "Hey, I am : null" }, { "code": null, "e": 5397, "s": 5371, "text": "9. ‘+’ operator on null :" }, { "code": null, "e": 5504, "s": 5397, "text": "We can concatenate the null value with String variables in java. It is considered a concatenation in java." }, { "code": null, "e": 5699, "s": 5504, "text": "Here, the null will only be concatenated with the String variable. If we use “+” operator with null and any other type(Integer, Double, etc.,) other than String, it will throw an error message. " }, { "code": null, "e": 5792, "s": 5699, "text": "Integer a=null+7 will throw an error message as “bad operand types for binary operator ‘+’ “" }, { "code": null, "e": 5797, "s": 5792, "text": "Java" }, { "code": "import java.io.*; class GFG { public static void main(String[] args) { String str1 = null; String str2 = \"_value\"; String output = str1 + str2; System.out.println(\"Concatenated value : \" + output); }}", "e": 6061, "s": 5797, "text": null }, { "code": null, "e": 6094, "s": 6061, "text": "Concatenated value : null_value\n" }, { "code": null, "e": 6393, "s": 6094, "text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 6521, "s": 6393, "text": "Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above." }, { "code": null, "e": 6534, "s": 6521, "text": "Akanksha_Rai" }, { "code": null, "e": 6553, "s": 6534, "text": "keerthikarathan123" }, { "code": null, "e": 6571, "s": 6553, "text": "interesting-facts" }, { "code": null, "e": 6576, "s": 6571, "text": "Java" }, { "code": null, "e": 6581, "s": 6576, "text": "Java" } ]
Literals in Python
01 Sep, 2021 Generally, literals are a notation for representing a fixed value in source code. They can also be defined as raw value or data given in variables or constants. Example: Python3 # Numeric literalsx = 24y = 24.3z = 2+3jprint(x, y, z) 24 24.3 (2+3j) Here 24, 24.3, 2+3j are considered as literals. Python has different types of literals. String literalsNumeric literalsBoolean literalsLiteral CollectionsSpecial literals String literals Numeric literals Boolean literals Literal Collections Special literals A string literal can be created by writing a text(a group of Characters ) surrounded by the single(”), double(“”), or triple quotes. By using triple quotes we can write multi-line strings or display in the desired way. Example: Python3 # string literals # in single quotes = 'geekforgeeks' # in double quotest = "geekforgeeks" # multi-line Stringm = '''geek for geeks''' print(s)print(t)print(m) geekforgeeks geekforgeeks geek for geeks Here geekforgeeks is string literal which is assigned to variable(s). It is also a type of string literals where a single character surrounded by single or double-quotes. Example: Python3 # character literal in single quotev = 'n' # character literal in double quotesw = "a" print(v)print(w) n a They are immutable and there are three types of numeric literal : IntegerFloatComplex. Integer Float Complex. Both positive and negative numbers including 0. There should not be any fractional part. Example: Python3 # integer literal # Binary Literalsa = 0b10100 # Decimal Literalb = 50 # Octal Literalc = 0o320 # Hexadecimal Literald = 0x12b print(a, b, c, d) 20 50 208 299 In the program above we assigned integer literals (0b10100, 50, 0o320, 0x12b) into different variables. Here, ‘a‘ is binary literal, ‘b’ is a decimal literal, ‘c‘ is an octal literal and ‘d‘ is a hexadecimal literal. But on using print function to display value or to get output they were converted into decimal. These are real numbers having both integer and fractional parts. Example: Python3 # Float Literale = 24.8f = 45.0 print(e, f) 24.8 45.0 24.8 and 45.0 are floating-point literals because both 24.8 and 45.0 are floating-point numbers. The numerals will be in the form of a + bj, where ‘a‘ is the real part and ‘b‘ is the complex part. Example: Python3 z = 7 + 5j # real part is 0 here.k = 7j print(z, k) (7+5j) 7j There are only two Boolean literals in Python. They are true and false. Example: Python3 a = (1 == True)b = (1 == False)c = True + 3d = False + 7 print("a is", a)print("b is", b)print("c:", c)print("d:", d) a is True b is False c: 4 d: 7 In python, True represents the value as 1 and False represents the value as 0. In the above example ‘a‘ is True and ‘b‘ is False because 1 equal to True. Example: Python3 x = (1 == True)y = (2 == False)z = (3 == True)r = (1 == True)a = True + 10b = False + 10 print("x is", x)print("y is", y)print("z is", r)print("a:", a)print("b:", b) x is True y is False z is True a: 11 b: 10 There are four different types of literal collections List literalsTuple literalsDict literalsSet literals List literals Tuple literals Dict literals Set literals List contains items of different data types. The values stored in List are separated by comma (,) and enclosed within square brackets([]). We can store different types of data in a List. Lists are mutable. Example : Python3 # List literalsnumber = [1, 2, 3, 4, 5]name = ['Amit', 'kabir', 'bhaskar', 2]print(number)print(name) [1, 2, 3, 4, 5] ['Amit', 'kabir', 'bhaskar', 2] A tuple is a collection of different data-type. It is enclosed by the parentheses ‘()‘ and each element is separated by the comma(,). It is immutable. Example: Python3 # Tuple literalseven_number = (2, 4, 6, 8)odd_number = (1, 3, 5, 7) print(even_number)print(odd_number) (2, 4, 6, 8) (1, 3, 5, 7) Dictionary stores the data in the key-value pair. It is enclosed by curly-braces ‘{}‘ and each pair is separated by the commas(,). We can store different types of data in a dictionary. Dictionaries are mutable. Example: Python3 # Dict literalsalphabets = {'a': 'apple', 'b': 'ball', 'c': 'cat'}information = {'name': 'amit', 'age': 20, 'ID': 20} print(alphabets)print(information) {'a': 'apple', 'b': 'ball', 'c': 'cat'} {'name': 'amit', 'age': 20, 'ID': 20} Set is the collection of the unordered data set. It is enclosed by the {} and each element is separated by the comma(,). Example: we can create a set of vowels and fruits. Python3 # Set literalsvowels = {'a', 'e', 'i', 'o', 'u'}fruits = {"apple", "banana", "cherry"} print(vowels)print(fruits) {'o', 'e', 'a', 'u', 'i'} {'apple', 'banana', 'cherry'} Python contains one special literal (None). ‘None’ is used to define a null variable. If ‘None’ is compared with anything else other than a ‘None’, it will return false. Example: Python3 # Special literalswater_remain = Noneprint(water_remain) None chhabradhanvi python-basics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Sep, 2021" }, { "code": null, "e": 216, "s": 54, "text": "Generally, literals are a notation for representing a fixed value in source code. They can also be defined as raw value or data given in variables or constants. " }, { "code": null, "e": 225, "s": 216, "text": "Example:" }, { "code": null, "e": 233, "s": 225, "text": "Python3" }, { "code": "# Numeric literalsx = 24y = 24.3z = 2+3jprint(x, y, z)", "e": 288, "s": 233, "text": null }, { "code": null, "e": 303, "s": 288, "text": "24 24.3 (2+3j)" }, { "code": null, "e": 352, "s": 303, "text": "Here 24, 24.3, 2+3j are considered as literals. " }, { "code": null, "e": 392, "s": 352, "text": "Python has different types of literals." }, { "code": null, "e": 475, "s": 392, "text": "String literalsNumeric literalsBoolean literalsLiteral CollectionsSpecial literals" }, { "code": null, "e": 491, "s": 475, "text": "String literals" }, { "code": null, "e": 508, "s": 491, "text": "Numeric literals" }, { "code": null, "e": 525, "s": 508, "text": "Boolean literals" }, { "code": null, "e": 545, "s": 525, "text": "Literal Collections" }, { "code": null, "e": 562, "s": 545, "text": "Special literals" }, { "code": null, "e": 783, "s": 562, "text": "A string literal can be created by writing a text(a group of Characters ) surrounded by the single(”), double(“”), or triple quotes. By using triple quotes we can write multi-line strings or display in the desired way. " }, { "code": null, "e": 792, "s": 783, "text": "Example:" }, { "code": null, "e": 800, "s": 792, "text": "Python3" }, { "code": "# string literals # in single quotes = 'geekforgeeks' # in double quotest = \"geekforgeeks\" # multi-line Stringm = '''geek for geeks''' print(s)print(t)print(m)", "e": 984, "s": 800, "text": null }, { "code": null, "e": 1053, "s": 984, "text": "geekforgeeks\ngeekforgeeks\ngeek \n for \n geeks" }, { "code": null, "e": 1124, "s": 1053, "text": "Here geekforgeeks is string literal which is assigned to variable(s). " }, { "code": null, "e": 1225, "s": 1124, "text": "It is also a type of string literals where a single character surrounded by single or double-quotes." }, { "code": null, "e": 1234, "s": 1225, "text": "Example:" }, { "code": null, "e": 1242, "s": 1234, "text": "Python3" }, { "code": "# character literal in single quotev = 'n' # character literal in double quotesw = \"a\" print(v)print(w)", "e": 1346, "s": 1242, "text": null }, { "code": null, "e": 1350, "s": 1346, "text": "n\na" }, { "code": null, "e": 1418, "s": 1350, "text": "They are immutable and there are three types of numeric literal : " }, { "code": null, "e": 1439, "s": 1418, "text": "IntegerFloatComplex." }, { "code": null, "e": 1447, "s": 1439, "text": "Integer" }, { "code": null, "e": 1453, "s": 1447, "text": "Float" }, { "code": null, "e": 1462, "s": 1453, "text": "Complex." }, { "code": null, "e": 1552, "s": 1462, "text": " Both positive and negative numbers including 0. There should not be any fractional part." }, { "code": null, "e": 1561, "s": 1552, "text": "Example:" }, { "code": null, "e": 1569, "s": 1561, "text": "Python3" }, { "code": "# integer literal # Binary Literalsa = 0b10100 # Decimal Literalb = 50 # Octal Literalc = 0o320 # Hexadecimal Literald = 0x12b print(a, b, c, d)", "e": 1714, "s": 1569, "text": null }, { "code": null, "e": 1728, "s": 1714, "text": "20 50 208 299" }, { "code": null, "e": 2041, "s": 1728, "text": "In the program above we assigned integer literals (0b10100, 50, 0o320, 0x12b) into different variables. Here, ‘a‘ is binary literal, ‘b’ is a decimal literal, ‘c‘ is an octal literal and ‘d‘ is a hexadecimal literal. But on using print function to display value or to get output they were converted into decimal." }, { "code": null, "e": 2107, "s": 2041, "text": " These are real numbers having both integer and fractional parts." }, { "code": null, "e": 2116, "s": 2107, "text": "Example:" }, { "code": null, "e": 2124, "s": 2116, "text": "Python3" }, { "code": "# Float Literale = 24.8f = 45.0 print(e, f)", "e": 2168, "s": 2124, "text": null }, { "code": null, "e": 2178, "s": 2168, "text": "24.8 45.0" }, { "code": null, "e": 2275, "s": 2178, "text": "24.8 and 45.0 are floating-point literals because both 24.8 and 45.0 are floating-point numbers." }, { "code": null, "e": 2375, "s": 2275, "text": "The numerals will be in the form of a + bj, where ‘a‘ is the real part and ‘b‘ is the complex part." }, { "code": null, "e": 2384, "s": 2375, "text": "Example:" }, { "code": null, "e": 2392, "s": 2384, "text": "Python3" }, { "code": "z = 7 + 5j # real part is 0 here.k = 7j print(z, k)", "e": 2444, "s": 2392, "text": null }, { "code": null, "e": 2454, "s": 2444, "text": "(7+5j) 7j" }, { "code": null, "e": 2526, "s": 2454, "text": "There are only two Boolean literals in Python. They are true and false." }, { "code": null, "e": 2535, "s": 2526, "text": "Example:" }, { "code": null, "e": 2543, "s": 2535, "text": "Python3" }, { "code": "a = (1 == True)b = (1 == False)c = True + 3d = False + 7 print(\"a is\", a)print(\"b is\", b)print(\"c:\", c)print(\"d:\", d)", "e": 2661, "s": 2543, "text": null }, { "code": null, "e": 2692, "s": 2661, "text": "a is True\nb is False\nc: 4\nd: 7" }, { "code": null, "e": 2846, "s": 2692, "text": "In python, True represents the value as 1 and False represents the value as 0. In the above example ‘a‘ is True and ‘b‘ is False because 1 equal to True." }, { "code": null, "e": 2855, "s": 2846, "text": "Example:" }, { "code": null, "e": 2863, "s": 2855, "text": "Python3" }, { "code": "x = (1 == True)y = (2 == False)z = (3 == True)r = (1 == True)a = True + 10b = False + 10 print(\"x is\", x)print(\"y is\", y)print(\"z is\", r)print(\"a:\", a)print(\"b:\", b)", "e": 3029, "s": 2863, "text": null }, { "code": null, "e": 3072, "s": 3029, "text": "x is True\ny is False\nz is True\na: 11\nb: 10" }, { "code": null, "e": 3126, "s": 3072, "text": "There are four different types of literal collections" }, { "code": null, "e": 3179, "s": 3126, "text": "List literalsTuple literalsDict literalsSet literals" }, { "code": null, "e": 3193, "s": 3179, "text": "List literals" }, { "code": null, "e": 3208, "s": 3193, "text": "Tuple literals" }, { "code": null, "e": 3222, "s": 3208, "text": "Dict literals" }, { "code": null, "e": 3235, "s": 3222, "text": "Set literals" }, { "code": null, "e": 3441, "s": 3235, "text": "List contains items of different data types. The values stored in List are separated by comma (,) and enclosed within square brackets([]). We can store different types of data in a List. Lists are mutable." }, { "code": null, "e": 3452, "s": 3441, "text": "Example : " }, { "code": null, "e": 3460, "s": 3452, "text": "Python3" }, { "code": "# List literalsnumber = [1, 2, 3, 4, 5]name = ['Amit', 'kabir', 'bhaskar', 2]print(number)print(name)", "e": 3562, "s": 3460, "text": null }, { "code": null, "e": 3610, "s": 3562, "text": "[1, 2, 3, 4, 5]\n['Amit', 'kabir', 'bhaskar', 2]" }, { "code": null, "e": 3762, "s": 3610, "text": "A tuple is a collection of different data-type. It is enclosed by the parentheses ‘()‘ and each element is separated by the comma(,). It is immutable." }, { "code": null, "e": 3772, "s": 3762, "text": "Example: " }, { "code": null, "e": 3780, "s": 3772, "text": "Python3" }, { "code": "# Tuple literalseven_number = (2, 4, 6, 8)odd_number = (1, 3, 5, 7) print(even_number)print(odd_number)", "e": 3884, "s": 3780, "text": null }, { "code": null, "e": 3910, "s": 3884, "text": "(2, 4, 6, 8)\n(1, 3, 5, 7)" }, { "code": null, "e": 4122, "s": 3910, "text": "Dictionary stores the data in the key-value pair. It is enclosed by curly-braces ‘{}‘ and each pair is separated by the commas(,). We can store different types of data in a dictionary. Dictionaries are mutable." }, { "code": null, "e": 4132, "s": 4122, "text": "Example: " }, { "code": null, "e": 4140, "s": 4132, "text": "Python3" }, { "code": "# Dict literalsalphabets = {'a': 'apple', 'b': 'ball', 'c': 'cat'}information = {'name': 'amit', 'age': 20, 'ID': 20} print(alphabets)print(information)", "e": 4293, "s": 4140, "text": null }, { "code": null, "e": 4371, "s": 4293, "text": "{'a': 'apple', 'b': 'ball', 'c': 'cat'}\n{'name': 'amit', 'age': 20, 'ID': 20}" }, { "code": null, "e": 4493, "s": 4371, "text": " Set is the collection of the unordered data set. It is enclosed by the {} and each element is separated by the comma(,)." }, { "code": null, "e": 4545, "s": 4493, "text": "Example: we can create a set of vowels and fruits. " }, { "code": null, "e": 4553, "s": 4545, "text": "Python3" }, { "code": "# Set literalsvowels = {'a', 'e', 'i', 'o', 'u'}fruits = {\"apple\", \"banana\", \"cherry\"} print(vowels)print(fruits)", "e": 4667, "s": 4553, "text": null }, { "code": null, "e": 4723, "s": 4667, "text": "{'o', 'e', 'a', 'u', 'i'}\n{'apple', 'banana', 'cherry'}" }, { "code": null, "e": 4893, "s": 4723, "text": "Python contains one special literal (None). ‘None’ is used to define a null variable. If ‘None’ is compared with anything else other than a ‘None’, it will return false." }, { "code": null, "e": 4902, "s": 4893, "text": "Example:" }, { "code": null, "e": 4910, "s": 4902, "text": "Python3" }, { "code": "# Special literalswater_remain = Noneprint(water_remain)", "e": 4967, "s": 4910, "text": null }, { "code": null, "e": 4972, "s": 4967, "text": "None" }, { "code": null, "e": 4986, "s": 4972, "text": "chhabradhanvi" }, { "code": null, "e": 5000, "s": 4986, "text": "python-basics" }, { "code": null, "e": 5007, "s": 5000, "text": "Python" }, { "code": null, "e": 5105, "s": 5007, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5137, "s": 5105, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5164, "s": 5137, "text": "Python Classes and Objects" }, { "code": null, "e": 5185, "s": 5164, "text": "Python OOPs Concepts" }, { "code": null, "e": 5208, "s": 5185, "text": "Introduction To PYTHON" }, { "code": null, "e": 5264, "s": 5208, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 5295, "s": 5264, "text": "Python | os.path.join() method" }, { "code": null, "e": 5337, "s": 5295, "text": "Check if element exists in list in Python" }, { "code": null, "e": 5379, "s": 5337, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 5418, "s": 5379, "text": "Python | Get unique values from a list" } ]
Python | os.makedirs() method
08 Dec, 2020 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by the operating system. os.makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os.makedirs() method will create them all.For example consider the following path: /home/User/Documents/GeeksForGeeks/Authors/ihritik Suppose we want to create directory ‘ihritik’ but Directory ‘GeeksForGeeks’ and ‘Authors’ are unavailable in the path. Then os.makedirs() method will create all unavailable/missing directory in the specified path. ‘GeeksForGeeks’ and ‘Authors’ will be created first then ‘ihritik’ directory will be created. Syntax: os.makedirs(path, mode = 0o777, exist_ok = False) Parameter: path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.mode (optional) : A Integer value representing mode of the newly created directory..If this parameter is omitted then the default value Oo777 is used.exist_ok (optional) : A default value False is used for this parameter. If the target directory already exists an OSError is raised if its value is False otherwise not. For value True leaves directory unaltered. Return Type: This method does not return any value. Code #1: Use of os.makedirs() method to create directory Python3 # Python program to explain os.makedirs() method # importing os moduleimport os # Leaf directorydirectory = "ihritik" # Parent Directoriesparent_dir = "/home/User/Documents/GeeksForGeeks/Authors" # Pathpath = os.path.join(parent_dir, directory) # Create the directory# 'ihritik'os.makedirs(path)print("Directory '%s' created" %directory) # Directory 'GeeksForGeeks' and 'Authors' will# be created too# if it does not exists # Leaf directorydirectory = "c" # Parent Directoriesparent_dir = "/home/User/Documents/GeeksforGeeks/a/b" # modemode = 0o666 path = os.path.join(parent_dir, directory) # Create the directory# 'c' os.makedirs(path, mode)print("Directory '%s' created" %directory) # 'GeeksForGeeks', 'a', and 'b'# will also be created if# it does not exists # If any of the intermediate level# directory is missing# os.makedirs() method will# create them # os.makedirs() method can be# used to create a directory tree Output: Directory 'ihritik' created Directory 'c' created Code #2: Errors while using os.makedirs() method Python3 # Python program to explain os.makedirs() method # importing os moduleimport os # os.makedirs() method will raise# an OSError if the directory# to be created already exists # Directorydirectory = "ihritik" # Parent Directory pathparent_dir = "/home/User/Documents/GeeksForGeeks" # Pathpath = os.path.join(parent_dir, directory) # Create the directory# 'ihritik'os.makedirs(path)print("Directory '%s' created" %directory) Output: Traceback (most recent call last): File "makedirs.py", line 21, in os.makedirs(path) File "/usr/lib/python3.6/os.py", line 220, in makedirs mkdir(name, mode) FileExistsError: [Errno 17] File exists: '/home/User/Documents/GeeksForGeeks/ihritik' Code #3: Handling errors while using os.makedirs() method Python3 # Python program to explain os.makedirs() method # importing os moduleimport os # os.makedirs() method will raise# an OSError if the directory# to be created already exists# But It can be suppressed by# setting the value of a parameter# exist_ok as True # Directorydirectory = "ihritik" # Parent Directory pathparent_dir = "/home/ihritik/Desktop/GeeksForGeeks" # Pathpath = os.path.join(parent_dir, directory) # Create the directory# 'ihritik'try: os.makedirs(path, exist_ok = True) print("Directory '%s' created successfully" %directory)except OSError as error: print("Directory '%s' can not be created") # By setting exist_ok as True# error caused due already# existing directory can be suppressed# but other OSError may be raised# due to other error like# invalid path name Output: Directory 'ihritik' created successfully Reference: https://docs.python.org/3/library/os.html mayank5326 abrameshba Python OS-path-module python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Dec, 2020" }, { "code": null, "e": 685, "s": 28, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by the operating system. os.makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os.makedirs() method will create them all.For example consider the following path: " }, { "code": null, "e": 736, "s": 685, "text": "/home/User/Documents/GeeksForGeeks/Authors/ihritik" }, { "code": null, "e": 1046, "s": 736, "text": "Suppose we want to create directory ‘ihritik’ but Directory ‘GeeksForGeeks’ and ‘Authors’ are unavailable in the path. Then os.makedirs() method will create all unavailable/missing directory in the specified path. ‘GeeksForGeeks’ and ‘Authors’ will be created first then ‘ihritik’ directory will be created. " }, { "code": null, "e": 1662, "s": 1046, "text": "Syntax: os.makedirs(path, mode = 0o777, exist_ok = False) Parameter: path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.mode (optional) : A Integer value representing mode of the newly created directory..If this parameter is omitted then the default value Oo777 is used.exist_ok (optional) : A default value False is used for this parameter. If the target directory already exists an OSError is raised if its value is False otherwise not. For value True leaves directory unaltered. Return Type: This method does not return any value. " }, { "code": null, "e": 1720, "s": 1662, "text": "Code #1: Use of os.makedirs() method to create directory " }, { "code": null, "e": 1728, "s": 1720, "text": "Python3" }, { "code": "# Python program to explain os.makedirs() method # importing os moduleimport os # Leaf directorydirectory = \"ihritik\" # Parent Directoriesparent_dir = \"/home/User/Documents/GeeksForGeeks/Authors\" # Pathpath = os.path.join(parent_dir, directory) # Create the directory# 'ihritik'os.makedirs(path)print(\"Directory '%s' created\" %directory) # Directory 'GeeksForGeeks' and 'Authors' will# be created too# if it does not exists # Leaf directorydirectory = \"c\" # Parent Directoriesparent_dir = \"/home/User/Documents/GeeksforGeeks/a/b\" # modemode = 0o666 path = os.path.join(parent_dir, directory) # Create the directory# 'c' os.makedirs(path, mode)print(\"Directory '%s' created\" %directory) # 'GeeksForGeeks', 'a', and 'b'# will also be created if# it does not exists # If any of the intermediate level# directory is missing# os.makedirs() method will# create them # os.makedirs() method can be# used to create a directory tree ", "e": 2658, "s": 1728, "text": null }, { "code": null, "e": 2667, "s": 2658, "text": "Output: " }, { "code": null, "e": 2717, "s": 2667, "text": "Directory 'ihritik' created\nDirectory 'c' created" }, { "code": null, "e": 2767, "s": 2717, "text": "Code #2: Errors while using os.makedirs() method " }, { "code": null, "e": 2775, "s": 2767, "text": "Python3" }, { "code": "# Python program to explain os.makedirs() method # importing os moduleimport os # os.makedirs() method will raise# an OSError if the directory# to be created already exists # Directorydirectory = \"ihritik\" # Parent Directory pathparent_dir = \"/home/User/Documents/GeeksForGeeks\" # Pathpath = os.path.join(parent_dir, directory) # Create the directory# 'ihritik'os.makedirs(path)print(\"Directory '%s' created\" %directory)", "e": 3202, "s": 2775, "text": null }, { "code": null, "e": 3211, "s": 3202, "text": "Output: " }, { "code": null, "e": 3468, "s": 3211, "text": "Traceback (most recent call last):\n File \"makedirs.py\", line 21, in \n os.makedirs(path)\n File \"/usr/lib/python3.6/os.py\", line 220, in makedirs\n mkdir(name, mode)\nFileExistsError: [Errno 17] File exists: '/home/User/Documents/GeeksForGeeks/ihritik'" }, { "code": null, "e": 3527, "s": 3468, "text": "Code #3: Handling errors while using os.makedirs() method " }, { "code": null, "e": 3535, "s": 3527, "text": "Python3" }, { "code": "# Python program to explain os.makedirs() method # importing os moduleimport os # os.makedirs() method will raise# an OSError if the directory# to be created already exists# But It can be suppressed by# setting the value of a parameter# exist_ok as True # Directorydirectory = \"ihritik\" # Parent Directory pathparent_dir = \"/home/ihritik/Desktop/GeeksForGeeks\" # Pathpath = os.path.join(parent_dir, directory) # Create the directory# 'ihritik'try: os.makedirs(path, exist_ok = True) print(\"Directory '%s' created successfully\" %directory)except OSError as error: print(\"Directory '%s' can not be created\") # By setting exist_ok as True# error caused due already# existing directory can be suppressed# but other OSError may be raised# due to other error like# invalid path name", "e": 4327, "s": 3535, "text": null }, { "code": null, "e": 4336, "s": 4327, "text": "Output: " }, { "code": null, "e": 4377, "s": 4336, "text": "Directory 'ihritik' created successfully" }, { "code": null, "e": 4431, "s": 4377, "text": "Reference: https://docs.python.org/3/library/os.html " }, { "code": null, "e": 4442, "s": 4431, "text": "mayank5326" }, { "code": null, "e": 4453, "s": 4442, "text": "abrameshba" }, { "code": null, "e": 4475, "s": 4453, "text": "Python OS-path-module" }, { "code": null, "e": 4492, "s": 4475, "text": "python-os-module" }, { "code": null, "e": 4499, "s": 4492, "text": "Python" }, { "code": null, "e": 4597, "s": 4499, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4615, "s": 4597, "text": "Python Dictionary" }, { "code": null, "e": 4657, "s": 4615, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4679, "s": 4657, "text": "Enumerate() in Python" }, { "code": null, "e": 4714, "s": 4679, "text": "Read a file line by line in Python" }, { "code": null, "e": 4740, "s": 4714, "text": "Python String | replace()" }, { "code": null, "e": 4772, "s": 4740, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4801, "s": 4772, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4828, "s": 4801, "text": "Python Classes and Objects" }, { "code": null, "e": 4858, "s": 4828, "text": "Iterate over a list in Python" } ]
Routing Path for ExpressJS
23 Aug, 2019 What and Why ?Routing in ExpressJS is used to subdivide and organize the web application into multiple mini-applications each having its own functionality. It provides more functionality by subdividing the web application rather than including all of the functionality on a single page. These mini-applications combine together to form a web application. Each route in Express responds to a client request to a particular route/endpoint and an HTTP request method (GET, POST, PUT, DELETE, UPDATE and so on). Each route basically refers to the different URLs in the website. So when a URL (Eg: www.geeksforgeeks.org/login) matches a route then the function associated with that specific route is executed (In this case, the function redirects the user to the login page of GeeksforGeeks). How it is done in Express ?Express Router is used to define mini-applications in Express so that each endpoint/route can be dealt in more detail. So, first, we will need to include express into our application. Then we have 2 methods for defining routes in the ExpressJS. Method 1: Without using Router: Instead of using express.router, we make use of app.method (route, function) Example: const express = require("express");const app = express(); app.get("/", function(req, res) { res.send("This is a get request!!\n");});app.post("/", function(req, res) { res.send("This is a post request!!\n");}); app.put("/", function(req, res) { res.send("This is a put request!!\n");}); app.get("/hey", function(req, res) { res.send("This is a get request to '/hey'!!\n");}); app.listen(3000); Output: Method 2: Using the Router: We can make use of express.router to simplify our code. Instead of specifying the path every time for a specific request, we just have to specify the path once and then we can chain the request methods to that path using the express router. The .all will be applied to all types of request methods. While the rest of them will be applied based on the request method. Example: const express = require('express');const Router = express.Router(); Router.route('/').all((req, res, next) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); next();}).get((req, res, next) => { res.end('When a GET request is made, then this ' + 'is the response sent to the client!');}).post((req, res, next) => { res.end('When a POST request is made, then this ' + 'is the response sent to the client!');}).put((req, res, next) => { res.end('When a PUT request is made, then this ' + 'is the response sent to the client!');}).delete((req, res, next) => { res.end('When a DELETE request is made, then this ' + 'is the response sent to the client!');}); module.exports = Router; Let’s save this file as test.js Now we make use of the express router in index.js file as follows: const express = require('Express');const app = express(); const test = require('./test.js'); app.use('/test', test); app.listen(3000); Note: index.js and test.js should be in the same directory. Output: The outputs obtained via the Postman software for different request methods. Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Node.js | fs.writeFileSync() Method Remove elements from a JavaScript Array Form validation using HTML and JavaScript How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills Node.js fs.readFileSync() Method How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Aug, 2019" }, { "code": null, "e": 840, "s": 52, "text": "What and Why ?Routing in ExpressJS is used to subdivide and organize the web application into multiple mini-applications each having its own functionality. It provides more functionality by subdividing the web application rather than including all of the functionality on a single page. These mini-applications combine together to form a web application. Each route in Express responds to a client request to a particular route/endpoint and an HTTP request method (GET, POST, PUT, DELETE, UPDATE and so on). Each route basically refers to the different URLs in the website. So when a URL (Eg: www.geeksforgeeks.org/login) matches a route then the function associated with that specific route is executed (In this case, the function redirects the user to the login page of GeeksforGeeks)." }, { "code": null, "e": 1112, "s": 840, "text": "How it is done in Express ?Express Router is used to define mini-applications in Express so that each endpoint/route can be dealt in more detail. So, first, we will need to include express into our application. Then we have 2 methods for defining routes in the ExpressJS." }, { "code": null, "e": 1221, "s": 1112, "text": "Method 1: Without using Router: Instead of using express.router, we make use of app.method (route, function)" }, { "code": null, "e": 1230, "s": 1221, "text": "Example:" }, { "code": "const express = require(\"express\");const app = express(); app.get(\"/\", function(req, res) { res.send(\"This is a get request!!\\n\");});app.post(\"/\", function(req, res) { res.send(\"This is a post request!!\\n\");}); app.put(\"/\", function(req, res) { res.send(\"This is a put request!!\\n\");}); app.get(\"/hey\", function(req, res) { res.send(\"This is a get request to '/hey'!!\\n\");}); app.listen(3000);", "e": 1632, "s": 1230, "text": null }, { "code": null, "e": 1640, "s": 1632, "text": "Output:" }, { "code": null, "e": 2035, "s": 1640, "text": "Method 2: Using the Router: We can make use of express.router to simplify our code. Instead of specifying the path every time for a specific request, we just have to specify the path once and then we can chain the request methods to that path using the express router. The .all will be applied to all types of request methods. While the rest of them will be applied based on the request method." }, { "code": null, "e": 2044, "s": 2035, "text": "Example:" }, { "code": "const express = require('express');const Router = express.Router(); Router.route('/').all((req, res, next) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); next();}).get((req, res, next) => { res.end('When a GET request is made, then this ' + 'is the response sent to the client!');}).post((req, res, next) => { res.end('When a POST request is made, then this ' + 'is the response sent to the client!');}).put((req, res, next) => { res.end('When a PUT request is made, then this ' + 'is the response sent to the client!');}).delete((req, res, next) => { res.end('When a DELETE request is made, then this ' + 'is the response sent to the client!');}); module.exports = Router;", "e": 2813, "s": 2044, "text": null }, { "code": null, "e": 2845, "s": 2813, "text": "Let’s save this file as test.js" }, { "code": null, "e": 2912, "s": 2845, "text": "Now we make use of the express router in index.js file as follows:" }, { "code": "const express = require('Express');const app = express(); const test = require('./test.js'); app.use('/test', test); app.listen(3000);", "e": 3050, "s": 2912, "text": null }, { "code": null, "e": 3110, "s": 3050, "text": "Note: index.js and test.js should be in the same directory." }, { "code": null, "e": 3195, "s": 3110, "text": "Output: The outputs obtained via the Postman software for different request methods." }, { "code": null, "e": 3202, "s": 3195, "text": "Picked" }, { "code": null, "e": 3213, "s": 3202, "text": "JavaScript" }, { "code": null, "e": 3230, "s": 3213, "text": "Web Technologies" }, { "code": null, "e": 3328, "s": 3230, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3389, "s": 3328, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3461, "s": 3389, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3497, "s": 3461, "text": "Node.js | fs.writeFileSync() Method" }, { "code": null, "e": 3537, "s": 3497, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3579, "s": 3537, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 3629, "s": 3579, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3691, "s": 3629, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3724, "s": 3691, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 3784, "s": 3724, "text": "How to set the default value for an HTML <select> element ?" } ]
map::operator[] in C++ STL
06 Oct, 2021 Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values. This operator is used to reference the element present at position given inside the operator. It is similar to the at() function, the only difference is that the at() function throws an out-of-range exception when the position is not in the bounds of the size of map, while this operator causes undefined behavior.Syntax : mapname[key] Parameters : Key value mapped to the element to be fetched. Returns : Direct reference to the element at the given key value. Examples: Input : map mymap; mymap['a'] = 1; mymap['a']; Output : 1 Input : map mymap; mymap["abcd"] = 7; mymap["abcd"]; Output : 7 Errors and Exceptions1. If the key is not present in the map, it shows undefined behavior. 2. It has a no exception throw guarantee otherwise. CPP // CPP program to illustrate// Implementation of [] operator#include <map>#include <iostream>#include<string>using namespace std; int main(){ // map declaration map<int,string> mymap; // mapping integers to strings mymap[1] = "Hi"; mymap[2] = "This"; mymap[3] = "is"; mymap[4] = "GeeksForGeeks"; // using operator[] to print string // mapped to integer 4 cout << mymap[4]; return 0;} Output: GeeksForGeeks Time Complexity: O(logn) hritikbhatnagar2182 cpp-map STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL) Unordered Sets in C++ Standard Template Library List in C++ Standard Template Library (STL) std::find in C++ Inline Functions in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Oct, 2021" }, { "code": null, "e": 222, "s": 52, "text": "Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values. " }, { "code": null, "e": 547, "s": 222, "text": "This operator is used to reference the element present at position given inside the operator. It is similar to the at() function, the only difference is that the at() function throws an out-of-range exception when the position is not in the bounds of the size of map, while this operator causes undefined behavior.Syntax : " }, { "code": null, "e": 686, "s": 547, "text": "mapname[key]\nParameters :\nKey value mapped to the element to be fetched.\nReturns :\nDirect reference to the element at the given key value." }, { "code": null, "e": 698, "s": 686, "text": "Examples: " }, { "code": null, "e": 867, "s": 698, "text": "Input : map mymap;\n mymap['a'] = 1;\n mymap['a'];\nOutput : 1\n\nInput : map mymap;\n mymap[\"abcd\"] = 7;\n mymap[\"abcd\"];\nOutput : 7" }, { "code": null, "e": 1011, "s": 867, "text": "Errors and Exceptions1. If the key is not present in the map, it shows undefined behavior. 2. It has a no exception throw guarantee otherwise. " }, { "code": null, "e": 1015, "s": 1011, "text": "CPP" }, { "code": "// CPP program to illustrate// Implementation of [] operator#include <map>#include <iostream>#include<string>using namespace std; int main(){ // map declaration map<int,string> mymap; // mapping integers to strings mymap[1] = \"Hi\"; mymap[2] = \"This\"; mymap[3] = \"is\"; mymap[4] = \"GeeksForGeeks\"; // using operator[] to print string // mapped to integer 4 cout << mymap[4]; return 0;}", "e": 1442, "s": 1015, "text": null }, { "code": null, "e": 1451, "s": 1442, "text": "Output: " }, { "code": null, "e": 1465, "s": 1451, "text": "GeeksForGeeks" }, { "code": null, "e": 1491, "s": 1465, "text": "Time Complexity: O(logn) " }, { "code": null, "e": 1511, "s": 1491, "text": "hritikbhatnagar2182" }, { "code": null, "e": 1519, "s": 1511, "text": "cpp-map" }, { "code": null, "e": 1523, "s": 1519, "text": "STL" }, { "code": null, "e": 1527, "s": 1523, "text": "C++" }, { "code": null, "e": 1531, "s": 1527, "text": "STL" }, { "code": null, "e": 1535, "s": 1531, "text": "CPP" }, { "code": null, "e": 1633, "s": 1535, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1657, "s": 1633, "text": "Sorting a vector in C++" }, { "code": null, "e": 1677, "s": 1657, "text": "Polymorphism in C++" }, { "code": null, "e": 1710, "s": 1677, "text": "Friend class and function in C++" }, { "code": null, "e": 1735, "s": 1710, "text": "std::string class in C++" }, { "code": null, "e": 1779, "s": 1735, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 1824, "s": 1779, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 1872, "s": 1824, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 1916, "s": 1872, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 1933, "s": 1916, "text": "std::find in C++" } ]
NumPy Array Shape
19 Feb, 2022 The shape of an array can be defined as the number of elements in each dimension. Dimension is the number of indices or subscripts, that we require in order to specify an individual element of an array. In NumPy we will use an attribute called shape which returns a tuple, the elements of the tuple give the lengths of the corresponding array dimensions. Syntax: numpy.shape(array_name) Parameters: Array is passed as a Parameter. Return: A tuple whose elements give the lengths of the corresponding array dimensions. Example 1: (Printing the shape of the multidimensional array) Python3 import numpy as npy # creating a 2-d arrayarr1 = npy.array([[1, 3, 5, 7], [2, 4, 6, 8]]) # creating a 3-d arrayarr2 = npy.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) # printing the shape of arrays# first element of tuple gives# dimension of arrays second# element of tuple gives number# of element of each dimensionprint(arr1.shape)print(arr2.shape) Output: (2, 4) (2, 2,2) The example above returns (2, 4) and (2,2,2) which means that the arr1 has 2 dimensions and each dimension has 4 elements. Similarly, arr2 has 3 dimensions and each dimension has 2 rows and 2 columns. Example 2: (Creating an array using ndmin using a vector with values 2,4,6,8,10 and verifying the value of last dimension) python3 import numpy as npy # creating an array of 6 dimension# using ndimarr = npy.array([2, 4, 6, 8, 10], ndmin=6) # printing arrayprint(arr) # verifying the value of last dimension# as 5print('shape of an array :', arr.shape) Output: [[[[[[ 2 4 6 8 10]]]]]] shape of an array : (1, 1, 1, 1, 1, 5) In the above example, we verified the last value of dimension as 5. ashupadhyay99 Python numpy-arrayCreation 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 OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Feb, 2022" }, { "code": null, "e": 255, "s": 52, "text": "The shape of an array can be defined as the number of elements in each dimension. Dimension is the number of indices or subscripts, that we require in order to specify an individual element of an array." }, { "code": null, "e": 407, "s": 255, "text": "In NumPy we will use an attribute called shape which returns a tuple, the elements of the tuple give the lengths of the corresponding array dimensions." }, { "code": null, "e": 572, "s": 407, "text": "Syntax: numpy.shape(array_name) Parameters: Array is passed as a Parameter. Return: A tuple whose elements give the lengths of the corresponding array dimensions. " }, { "code": null, "e": 634, "s": 572, "text": "Example 1: (Printing the shape of the multidimensional array)" }, { "code": null, "e": 642, "s": 634, "text": "Python3" }, { "code": "import numpy as npy # creating a 2-d arrayarr1 = npy.array([[1, 3, 5, 7], [2, 4, 6, 8]]) # creating a 3-d arrayarr2 = npy.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) # printing the shape of arrays# first element of tuple gives# dimension of arrays second# element of tuple gives number# of element of each dimensionprint(arr1.shape)print(arr2.shape)", "e": 992, "s": 642, "text": null }, { "code": null, "e": 1001, "s": 992, "text": "Output: " }, { "code": null, "e": 1017, "s": 1001, "text": "(2, 4)\n(2, 2,2)" }, { "code": null, "e": 1218, "s": 1017, "text": "The example above returns (2, 4) and (2,2,2) which means that the arr1 has 2 dimensions and each dimension has 4 elements. Similarly, arr2 has 3 dimensions and each dimension has 2 rows and 2 columns." }, { "code": null, "e": 1342, "s": 1218, "text": "Example 2: (Creating an array using ndmin using a vector with values 2,4,6,8,10 and verifying the value of last dimension) " }, { "code": null, "e": 1350, "s": 1342, "text": "python3" }, { "code": "import numpy as npy # creating an array of 6 dimension# using ndimarr = npy.array([2, 4, 6, 8, 10], ndmin=6) # printing arrayprint(arr) # verifying the value of last dimension# as 5print('shape of an array :', arr.shape)", "e": 1571, "s": 1350, "text": null }, { "code": null, "e": 1580, "s": 1571, "text": "Output: " }, { "code": null, "e": 1646, "s": 1580, "text": "[[[[[[ 2 4 6 8 10]]]]]]\nshape of an array : (1, 1, 1, 1, 1, 5)" }, { "code": null, "e": 1714, "s": 1646, "text": "In the above example, we verified the last value of dimension as 5." }, { "code": null, "e": 1728, "s": 1714, "text": "ashupadhyay99" }, { "code": null, "e": 1755, "s": 1728, "text": "Python numpy-arrayCreation" }, { "code": null, "e": 1768, "s": 1755, "text": "Python-numpy" }, { "code": null, "e": 1775, "s": 1768, "text": "Python" }, { "code": null, "e": 1873, "s": 1775, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1905, "s": 1873, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1932, "s": 1905, "text": "Python Classes and Objects" }, { "code": null, "e": 1953, "s": 1932, "text": "Python OOPs Concepts" }, { "code": null, "e": 1976, "s": 1953, "text": "Introduction To PYTHON" }, { "code": null, "e": 2032, "s": 1976, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2063, "s": 2032, "text": "Python | os.path.join() method" }, { "code": null, "e": 2105, "s": 2063, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2147, "s": 2105, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2186, "s": 2147, "text": "Python | Get unique values from a list" } ]
Java Program For Chocolate Distribution Problem
06 Jan, 2022 Given an array of n integers where each value represents the number of chocolates in a packet. Each packet can have a variable number of chocolates. There are m students, the task is to distribute chocolate packets such that: Each student gets one packet.The difference between the number of chocolates in the packet with maximum chocolates and packet with minimum chocolates given to the students is minimum. Each student gets one packet. The difference between the number of chocolates in the packet with maximum chocolates and packet with minimum chocolates given to the students is minimum. Examples: Input : arr[] = {7, 3, 2, 4, 9, 12, 56} , m = 3 Output: Minimum Difference is 2 Explanation:We have seven packets of chocolates and we need to pick three packets for 3 students If we pick 2, 3 and 4, we get the minimum difference between maximum and minimum packet sizes. Input : arr[] = {3, 4, 1, 9, 56, 7, 9, 12} , m = 5 Output: Minimum Difference is 6 Explanation:The set goes like 3,4,7,9,9 and the output is 9-3 = 6 Input : arr[] = {12, 4, 7, 9, 2, 23, 25, 41, 30, 40, 28, 42, 30, 44, 48, 43, 50} , m = 7 Output: Minimum Difference is 10 Explanation:We need to pick 7 packets. We pick 40, 41, 42, 44, 48, 43 and 50 to minimize difference between maximum and minimum. Source: Flipkart Interview Experience A simple solution is to generate all subsets of size m of arr[0..n-1]. For every subset, find the difference between the maximum and minimum elements in it. Finally, return the minimum difference.An efficient solution is based on the observation that to minimize the difference, we must choose consecutive elements from a sorted packet. We first sort the array arr[0..n-1], then find the subarray of size m with the minimum difference between the last and first elements. Below image is a dry run of the above approach: Below is the implementation of the above approach: Java // Java program for Chocolate Distribution // problemimport java.util.*; class GFG { // arr[0..n-1] represents sizes of // packets. m is number of students. // Returns minimum difference between // maximum and minimum values of // distribution. static int findMinDiff(int arr[], int n, int m) { // If there are no chocolates or // number of students is 0 if (m == 0 || n == 0) return 0; // Sort the given packets Arrays.sort(arr); // Number of students cannot be // more than number of packets if (n < m) return -1; // Largest number of chocolates int min_diff = Integer.MAX_VALUE; // Find the subarray of size m // such that difference between // last (maximum in case of // sorted) and first (minimum in // case of sorted) elements of // subarray is minimum. for (int i = 0; i + m - 1 < n; i++) { int diff = arr[i+m-1] - arr[i]; if (diff < min_diff) min_diff = diff; } return min_diff; } // Driver code public static void main(String[] args) { int arr[] = {12, 4, 7, 9, 2, 23, 25, 41, 30, 40, 28, 42, 30, 44, 48, 43, 50}; // Number of students int m = 7; int n = arr.length; System.out.println( "Minimum difference is " + findMinDiff(arr, n, m)); }}// This code is contributed by Arnav Kr. Mandal. Output: Minimum difference is 10 Time Complexity: O(n Log n) as we apply sorting before subarray search. Please refer complete article on Chocolate Distribution Problem for more details! Flipkart subset Arrays Java Programs Sorting Flipkart Arrays Sorting subset Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array Chocolate Distribution Problem Find duplicates in O(n) time and O(1) extra space | Set 1 Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jan, 2022" }, { "code": null, "e": 255, "s": 28, "text": "Given an array of n integers where each value represents the number of chocolates in a packet. Each packet can have a variable number of chocolates. There are m students, the task is to distribute chocolate packets such that: " }, { "code": null, "e": 439, "s": 255, "text": "Each student gets one packet.The difference between the number of chocolates in the packet with maximum chocolates and packet with minimum chocolates given to the students is minimum." }, { "code": null, "e": 469, "s": 439, "text": "Each student gets one packet." }, { "code": null, "e": 624, "s": 469, "text": "The difference between the number of chocolates in the packet with maximum chocolates and packet with minimum chocolates given to the students is minimum." }, { "code": null, "e": 634, "s": 624, "text": "Examples:" }, { "code": null, "e": 906, "s": 634, "text": "Input : arr[] = {7, 3, 2, 4, 9, 12, 56} , m = 3 Output: Minimum Difference is 2 Explanation:We have seven packets of chocolates and we need to pick three packets for 3 students If we pick 2, 3 and 4, we get the minimum difference between maximum and minimum packet sizes." }, { "code": null, "e": 1055, "s": 906, "text": "Input : arr[] = {3, 4, 1, 9, 56, 7, 9, 12} , m = 5 Output: Minimum Difference is 6 Explanation:The set goes like 3,4,7,9,9 and the output is 9-3 = 6" }, { "code": null, "e": 1307, "s": 1055, "text": "Input : arr[] = {12, 4, 7, 9, 2, 23, 25, 41, 30, 40, 28, 42, 30, 44, 48, 43, 50} , m = 7 Output: Minimum Difference is 10 Explanation:We need to pick 7 packets. We pick 40, 41, 42, 44, 48, 43 and 50 to minimize difference between maximum and minimum. " }, { "code": null, "e": 1345, "s": 1307, "text": "Source: Flipkart Interview Experience" }, { "code": null, "e": 1817, "s": 1345, "text": "A simple solution is to generate all subsets of size m of arr[0..n-1]. For every subset, find the difference between the maximum and minimum elements in it. Finally, return the minimum difference.An efficient solution is based on the observation that to minimize the difference, we must choose consecutive elements from a sorted packet. We first sort the array arr[0..n-1], then find the subarray of size m with the minimum difference between the last and first elements." }, { "code": null, "e": 1865, "s": 1817, "text": "Below image is a dry run of the above approach:" }, { "code": null, "e": 1917, "s": 1865, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1922, "s": 1917, "text": "Java" }, { "code": "// Java program for Chocolate Distribution // problemimport java.util.*; class GFG { // arr[0..n-1] represents sizes of // packets. m is number of students. // Returns minimum difference between // maximum and minimum values of // distribution. static int findMinDiff(int arr[], int n, int m) { // If there are no chocolates or // number of students is 0 if (m == 0 || n == 0) return 0; // Sort the given packets Arrays.sort(arr); // Number of students cannot be // more than number of packets if (n < m) return -1; // Largest number of chocolates int min_diff = Integer.MAX_VALUE; // Find the subarray of size m // such that difference between // last (maximum in case of // sorted) and first (minimum in // case of sorted) elements of // subarray is minimum. for (int i = 0; i + m - 1 < n; i++) { int diff = arr[i+m-1] - arr[i]; if (diff < min_diff) min_diff = diff; } return min_diff; } // Driver code public static void main(String[] args) { int arr[] = {12, 4, 7, 9, 2, 23, 25, 41, 30, 40, 28, 42, 30, 44, 48, 43, 50}; // Number of students int m = 7; int n = arr.length; System.out.println( \"Minimum difference is \" + findMinDiff(arr, n, m)); }}// This code is contributed by Arnav Kr. Mandal.", "e": 3596, "s": 1922, "text": null }, { "code": null, "e": 3604, "s": 3596, "text": "Output:" }, { "code": null, "e": 3629, "s": 3604, "text": "Minimum difference is 10" }, { "code": null, "e": 3701, "s": 3629, "text": "Time Complexity: O(n Log n) as we apply sorting before subarray search." }, { "code": null, "e": 3783, "s": 3701, "text": "Please refer complete article on Chocolate Distribution Problem for more details!" }, { "code": null, "e": 3792, "s": 3783, "text": "Flipkart" }, { "code": null, "e": 3799, "s": 3792, "text": "subset" }, { "code": null, "e": 3806, "s": 3799, "text": "Arrays" }, { "code": null, "e": 3820, "s": 3806, "text": "Java Programs" }, { "code": null, "e": 3828, "s": 3820, "text": "Sorting" }, { "code": null, "e": 3837, "s": 3828, "text": "Flipkart" }, { "code": null, "e": 3844, "s": 3837, "text": "Arrays" }, { "code": null, "e": 3852, "s": 3844, "text": "Sorting" }, { "code": null, "e": 3859, "s": 3852, "text": "subset" }, { "code": null, "e": 3957, "s": 3859, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3989, "s": 3957, "text": "Introduction to Data Structures" }, { "code": null, "e": 4014, "s": 3989, "text": "Window Sliding Technique" }, { "code": null, "e": 4061, "s": 4014, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 4092, "s": 4061, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 4150, "s": 4092, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 4178, "s": 4150, "text": "Initializing a List in Java" }, { "code": null, "e": 4204, "s": 4178, "text": "Java Programming Examples" }, { "code": null, "e": 4248, "s": 4204, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 4282, "s": 4248, "text": "Convert Double to Integer in Java" } ]
How to bind events on dynamically created elements using jQuery?
To bind events on dynamically created elements, you need to load dynamically. You can try to run the following code to learn how to bind events on dynamically created elements. Here, we will generate a new list item on button click. Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("ul").append("<li>new item <a href='javascript:void(0);' class='del'>&times;</a></li>"); }); $(document).on("click", "a.del" , function() { $(this).parent().remove(); }); }); </script> </head> <body> <button>Add</button> <p>Click the above button to dynamically add new list items. You can remove it later.</p> <ul> <li>item</li> </ul> </body> </html>
[ { "code": null, "e": 1295, "s": 1062, "text": "To bind events on dynamically created elements, you need to load dynamically. You can try to run the following code to learn how to bind events on dynamically created elements. Here, we will generate a new list item on button click." }, { "code": null, "e": 1305, "s": 1295, "text": "Live Demo" }, { "code": null, "e": 1905, "s": 1305, "text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n $(\"button\").click(function(){\n $(\"ul\").append(\"<li>new item <a href='javascript:void(0);' class='del'>&times;</a></li>\");\n });\n \n $(document).on(\"click\", \"a.del\" , function() {\n $(this).parent().remove();\n });\n});\n</script>\n</head>\n<body>\n <button>Add</button>\n <p>Click the above button to dynamically add new list items. You can remove it later.</p>\n <ul>\n <li>item</li>\n </ul>\n</body>\n</html>" } ]
Dimensionality-Reduction with Latent Dirichlet Allocation | by Xiao Ma | Towards Data Science
Dimensionality-reduction is an unsupervised machine learning technique that is often used in conjunction with supervised models. While reducing the dimensionality often makes a feature-based model less interpretable, it’s always very effective in preventing over-fitting and shortening the training time by reducing the number of features. The most popular dimensionality-reduction techniques are no doubt the Principle Component Analysis (PCA) and its variants. However, when it comes to text data, I find Latent Dirichlet Allocation (LDA) excitingly effective. The idea of Latent Dirichlet Allocation was first introduced in the research paper authored by David Blei, Andrew Ng, and Michael Jordan in 2003. It is described by the authors as a “generative probabilistic model of a corpus.” LDA is widely used in performing Topic Modeling — a statistical technique that can extract underlying themes/topics from a corpus. In a traditional Bag-of-words approach for text feature extraction, we map each document directly to all the word tokens through a Document-Term matrix. This approach often results in a huge, sparse matrix with the majority of entries equal 0 — we have lots of parameters to estimate when we use such a matrix as model inputs, but many of them provide limited and sometimes “noisy” information. In the LDA approach, instead of modeling the relationships between each text document and each word token directly, the “Latent variables” are introduced as “bridges.” Each document within the corpus is characterized by a Dirichlet distribution over the latent variables (topics) and each topic is characterized by another Dirichlet Distribution over all the word tokens. Assuming the number of documents to be N, and we choose the number of topics to be K. The idea of reducing dimension with LDA is to focus on the first Dirichlet Distribution mentioned above. For each document, we can obtain a vector of length K which represents the probability distribution of the document over K topics. Appending such vectors for all the documents, we can get an N-by-K feature matrix that can be input into our supervised model with certain labels. Recently, inspired by the original research paper cited above, I did a small experiment in exploring the performance of LDA in dimensionality reduction. In the experiment, I was able to reduce the dimension of training data by over 99% with less than 3% drop in raw accuracy. Next, let me illustrate this experiment in greater details. The data I used comes from the training data of the Toxic Comments Classification Kaggle challenge. Since my goal was to explore LDA in dimensionality reduction, I subset and filtered the data in the following ways to simplify the process: The original data has 6 different labels for each comment. I only focused on the “toxic” label. In this way, I turned the problem from multi-label classification to single-label classification.Under-sampling: the original data is extremely imbalanced with more than 90% of the comments labeled as “non-toxic.” By under-sampling, I obtained a balanced dataset with 15294 comments labeled as “toxic” and another 15294 that are not labeled as “toxic.” The original data has 6 different labels for each comment. I only focused on the “toxic” label. In this way, I turned the problem from multi-label classification to single-label classification. Under-sampling: the original data is extremely imbalanced with more than 90% of the comments labeled as “non-toxic.” By under-sampling, I obtained a balanced dataset with 15294 comments labeled as “toxic” and another 15294 that are not labeled as “toxic.” As the first step, I built an XG-boost classification model using the standard uni-gram approach with a TF-IDF vectorizer: Training and testing split: Training and testing split: from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(data.comment_text, data.toxic, test_size = 0.25,random_state = 23)X_train.reset_index(drop = True,inplace = True)X_test.reset_index(drop = True,inplace = True)y_train.reset_index(drop = True,inplace = True)y_test.reset_index(drop = True,inplace = True) 2. Fit the TF-IDF vectorizer for n_gram models. Notice that I filter the tokens so that tokens appear in less than 15 documents more than 90% of the documents are removed. tokenizer_xm is a customized tokenizer with tokenization, lemmatization and stemming included from sklearn.feature_extraction.text import TfidfVectorizervec_tfidf = TfidfVectorizer(ngram_range =(1,1),tokenizer=tokenizer_xm,min_df = 15, max_df = 0.9)vec_tfidf_f = vec_tfidf.fit(X_training) 3. Get the document-term matrix for n-gram model and fit with training data. train_dtm_ngram = vec_tfidf_f.transform(X_training)from xgboost import XGBClassifierxgbc = XGBClassifier(n_estimators=200)xgbc_ngram = xgbc.fit(train_dtm_ngram,y_training) Next, I start building the model with LDA. To use LDA, we need to obtain the Document-Term-Matrix first. Since LDA is based on raw counts, it is better to use a Count-Vectorizer instead of TF-IDF. from sklearn.feature_extraction.text import CountVectorizervec_count = CountVectorizer(ngram_range = (1,1),tokenizer=tokenizer_xm,min_df = 15, max_df = 0.9)vec_count_f = vec_count.fit(X_train) Create the training document-term matrix for LDA weights vec_f = vec_count_ftrain_dtm = vec_f.transform(X_train)topic_num = 5from sklearn.decomposition import LatentDirichletAllocationlda = LatentDirichletAllocation(n_components = topic_num)lda_f = lda.fit(train_dtm)lda_weights = lda_f.transform(train_dtm)# The lda_weights is a n by k matrix where n is the number of documents and k is the number of topics# Fit the xgb-model with lda weightsfrom xgboost import XGBClassifierxgbc = XGBClassifier(n_estimators=200)xgbc_lda = xgbc.fit(lda_weights,y_train) As in the code above, LDA requires a “n_components” parameter, which is essentially the number of topics. However, we usually don’t know how many “topics” are there in the corpus. Therefore, I repeated the process above 9 times with topic number equals to 1, 2, 3, 4, 5, 6, 12, 24, 50 and score the model against the test data, attempting to find a relatively optimal value. Below are the results. It seems that the best topic number is 5 with an accuracy of around 84%. Below are the top 10 “salient” tokens for each of the five topics based on the Dirichlet distribution. We are not digging deep into the performance of topic modeling with LDA in this post. But it is interesting to note the differences among topics. Topic 1 appears to be the most neutral one based while topic 5 is extremely toxic. The Dirichlet Distribution actually helps separate the non-toxic comments out from the corpus. Next, I ran the entire process above, with 1%, 25%, 50%, 75% and 100% of the training data, recorded the performance of the N-gram based (xgbc_ngram) as well as the LDA-based (xgbc_lda) Extreme Gradient Boosting Classifier (notice that the two models are both initialized with 200 estimators and have all other hyperparameters left as defaults) and compared their precision, recall, and accuracy scores. Below is the raw table for the plots above: As in the figures shown above, although the accuracy for the N-gram-based model is always slightly higher than the LDA-based one, it eventually reaches 3367 distinct features with 100% of the training data while the feature number for LDA-based model still remains 5 — a significant difference! Interestingly, the LDA-based model actually out-performs the n-gram model in terms of Recall while it is not doing so well in terms of Precision. That is, the LDA-based model is better at finding all toxic examples, but not very good at preventing non-toxic comments from getting labeled as toxic. In general, the LDA-based model seems to have a better balance between precision and recall. Using LDA for dimensionality reduction, we cannot bypass the n-gram feature extraction process. Therefore we didn’t get too much of a boost in shortening the end-to-end model building time. However, while LDA seems to be at least as efficient as PCA at dimensionality reduction, it is very interpretable. It’s a promising technique in feature-based text classification/regression models as we can compress all the information in text into a low-dimension and dense matrix so that we have the ability to add many other features to help improve the model performance without worrying about over-fitting.
[ { "code": null, "e": 734, "s": 171, "text": "Dimensionality-reduction is an unsupervised machine learning technique that is often used in conjunction with supervised models. While reducing the dimensionality often makes a feature-based model less interpretable, it’s always very effective in preventing over-fitting and shortening the training time by reducing the number of features. The most popular dimensionality-reduction techniques are no doubt the Principle Component Analysis (PCA) and its variants. However, when it comes to text data, I find Latent Dirichlet Allocation (LDA) excitingly effective." }, { "code": null, "e": 1093, "s": 734, "text": "The idea of Latent Dirichlet Allocation was first introduced in the research paper authored by David Blei, Andrew Ng, and Michael Jordan in 2003. It is described by the authors as a “generative probabilistic model of a corpus.” LDA is widely used in performing Topic Modeling — a statistical technique that can extract underlying themes/topics from a corpus." }, { "code": null, "e": 1860, "s": 1093, "text": "In a traditional Bag-of-words approach for text feature extraction, we map each document directly to all the word tokens through a Document-Term matrix. This approach often results in a huge, sparse matrix with the majority of entries equal 0 — we have lots of parameters to estimate when we use such a matrix as model inputs, but many of them provide limited and sometimes “noisy” information. In the LDA approach, instead of modeling the relationships between each text document and each word token directly, the “Latent variables” are introduced as “bridges.” Each document within the corpus is characterized by a Dirichlet distribution over the latent variables (topics) and each topic is characterized by another Dirichlet Distribution over all the word tokens." }, { "code": null, "e": 2329, "s": 1860, "text": "Assuming the number of documents to be N, and we choose the number of topics to be K. The idea of reducing dimension with LDA is to focus on the first Dirichlet Distribution mentioned above. For each document, we can obtain a vector of length K which represents the probability distribution of the document over K topics. Appending such vectors for all the documents, we can get an N-by-K feature matrix that can be input into our supervised model with certain labels." }, { "code": null, "e": 2665, "s": 2329, "text": "Recently, inspired by the original research paper cited above, I did a small experiment in exploring the performance of LDA in dimensionality reduction. In the experiment, I was able to reduce the dimension of training data by over 99% with less than 3% drop in raw accuracy. Next, let me illustrate this experiment in greater details." }, { "code": null, "e": 2905, "s": 2665, "text": "The data I used comes from the training data of the Toxic Comments Classification Kaggle challenge. Since my goal was to explore LDA in dimensionality reduction, I subset and filtered the data in the following ways to simplify the process:" }, { "code": null, "e": 3354, "s": 2905, "text": "The original data has 6 different labels for each comment. I only focused on the “toxic” label. In this way, I turned the problem from multi-label classification to single-label classification.Under-sampling: the original data is extremely imbalanced with more than 90% of the comments labeled as “non-toxic.” By under-sampling, I obtained a balanced dataset with 15294 comments labeled as “toxic” and another 15294 that are not labeled as “toxic.”" }, { "code": null, "e": 3548, "s": 3354, "text": "The original data has 6 different labels for each comment. I only focused on the “toxic” label. In this way, I turned the problem from multi-label classification to single-label classification." }, { "code": null, "e": 3804, "s": 3548, "text": "Under-sampling: the original data is extremely imbalanced with more than 90% of the comments labeled as “non-toxic.” By under-sampling, I obtained a balanced dataset with 15294 comments labeled as “toxic” and another 15294 that are not labeled as “toxic.”" }, { "code": null, "e": 3927, "s": 3804, "text": "As the first step, I built an XG-boost classification model using the standard uni-gram approach with a TF-IDF vectorizer:" }, { "code": null, "e": 3955, "s": 3927, "text": "Training and testing split:" }, { "code": null, "e": 3983, "s": 3955, "text": "Training and testing split:" }, { "code": null, "e": 4340, "s": 3983, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(data.comment_text, data.toxic, test_size = 0.25,random_state = 23)X_train.reset_index(drop = True,inplace = True)X_test.reset_index(drop = True,inplace = True)y_train.reset_index(drop = True,inplace = True)y_test.reset_index(drop = True,inplace = True)" }, { "code": null, "e": 4606, "s": 4340, "text": "2. Fit the TF-IDF vectorizer for n_gram models. Notice that I filter the tokens so that tokens appear in less than 15 documents more than 90% of the documents are removed. tokenizer_xm is a customized tokenizer with tokenization, lemmatization and stemming included" }, { "code": null, "e": 4801, "s": 4606, "text": "from sklearn.feature_extraction.text import TfidfVectorizervec_tfidf = TfidfVectorizer(ngram_range =(1,1),tokenizer=tokenizer_xm,min_df = 15, max_df = 0.9)vec_tfidf_f = vec_tfidf.fit(X_training)" }, { "code": null, "e": 4878, "s": 4801, "text": "3. Get the document-term matrix for n-gram model and fit with training data." }, { "code": null, "e": 5050, "s": 4878, "text": "train_dtm_ngram = vec_tfidf_f.transform(X_training)from xgboost import XGBClassifierxgbc = XGBClassifier(n_estimators=200)xgbc_ngram = xgbc.fit(train_dtm_ngram,y_training)" }, { "code": null, "e": 5247, "s": 5050, "text": "Next, I start building the model with LDA. To use LDA, we need to obtain the Document-Term-Matrix first. Since LDA is based on raw counts, it is better to use a Count-Vectorizer instead of TF-IDF." }, { "code": null, "e": 5440, "s": 5247, "text": "from sklearn.feature_extraction.text import CountVectorizervec_count = CountVectorizer(ngram_range = (1,1),tokenizer=tokenizer_xm,min_df = 15, max_df = 0.9)vec_count_f = vec_count.fit(X_train)" }, { "code": null, "e": 5497, "s": 5440, "text": "Create the training document-term matrix for LDA weights" }, { "code": null, "e": 5996, "s": 5497, "text": "vec_f = vec_count_ftrain_dtm = vec_f.transform(X_train)topic_num = 5from sklearn.decomposition import LatentDirichletAllocationlda = LatentDirichletAllocation(n_components = topic_num)lda_f = lda.fit(train_dtm)lda_weights = lda_f.transform(train_dtm)# The lda_weights is a n by k matrix where n is the number of documents and k is the number of topics# Fit the xgb-model with lda weightsfrom xgboost import XGBClassifierxgbc = XGBClassifier(n_estimators=200)xgbc_lda = xgbc.fit(lda_weights,y_train)" }, { "code": null, "e": 6394, "s": 5996, "text": "As in the code above, LDA requires a “n_components” parameter, which is essentially the number of topics. However, we usually don’t know how many “topics” are there in the corpus. Therefore, I repeated the process above 9 times with topic number equals to 1, 2, 3, 4, 5, 6, 12, 24, 50 and score the model against the test data, attempting to find a relatively optimal value. Below are the results." }, { "code": null, "e": 6570, "s": 6394, "text": "It seems that the best topic number is 5 with an accuracy of around 84%. Below are the top 10 “salient” tokens for each of the five topics based on the Dirichlet distribution." }, { "code": null, "e": 6894, "s": 6570, "text": "We are not digging deep into the performance of topic modeling with LDA in this post. But it is interesting to note the differences among topics. Topic 1 appears to be the most neutral one based while topic 5 is extremely toxic. The Dirichlet Distribution actually helps separate the non-toxic comments out from the corpus." }, { "code": null, "e": 7298, "s": 6894, "text": "Next, I ran the entire process above, with 1%, 25%, 50%, 75% and 100% of the training data, recorded the performance of the N-gram based (xgbc_ngram) as well as the LDA-based (xgbc_lda) Extreme Gradient Boosting Classifier (notice that the two models are both initialized with 200 estimators and have all other hyperparameters left as defaults) and compared their precision, recall, and accuracy scores." }, { "code": null, "e": 7342, "s": 7298, "text": "Below is the raw table for the plots above:" }, { "code": null, "e": 8028, "s": 7342, "text": "As in the figures shown above, although the accuracy for the N-gram-based model is always slightly higher than the LDA-based one, it eventually reaches 3367 distinct features with 100% of the training data while the feature number for LDA-based model still remains 5 — a significant difference! Interestingly, the LDA-based model actually out-performs the n-gram model in terms of Recall while it is not doing so well in terms of Precision. That is, the LDA-based model is better at finding all toxic examples, but not very good at preventing non-toxic comments from getting labeled as toxic. In general, the LDA-based model seems to have a better balance between precision and recall." } ]
Check whether the given number is Wagstaff prime or not - GeeksforGeeks
26 Apr, 2021 Given a positive integer n, the task is to check if it is a Wagstaff prime or not. Print ‘YES’ if the given number is Wagstaff prime otherwise print ‘NO’.Wagstaff prime: In mathematics, Wagstaff prime is a prime number ‘n’ of the form where ‘q’ is an odd prime.First, few Wagstaff prime numbers are: 3, 11, 43, 683, 2731, 43691, 174763, 2796203.......... Examples: Input: 43 Output: Yes 43 can be expressed as - (27 + 1 )/ 3 Input: 31 Output: No 31 can not be expressed in above mentioned form. Approach: Check first if the given number is a prime number or not. To check for a number to be prime, refer this.Then check if it can be expressed in the form of (n * 3 – 1) and should be a power of 2. To check for a number to be a power of 2, refer this.If both conditions are true, then the number is a Wagstaff prime number. Hence, print “YES”. Otherwise, print “NO” Check first if the given number is a prime number or not. To check for a number to be prime, refer this. Then check if it can be expressed in the form of (n * 3 – 1) and should be a power of 2. To check for a number to be a power of 2, refer this. If both conditions are true, then the number is a Wagstaff prime number. Hence, print “YES”. Otherwise, print “NO” Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // CPP program to check if a number is// Wagstaff prime or not #include <bits/stdc++.h>using namespace std; // Function to check if a number is prime or notbool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true;} // Utility function to check power of twobool isPowerOfTwo(int n){ return (n && !(n & (n - 1)));} // Driver Programint main(){ int n = 43; // Check if number is prime // and of the form (2^q +1 )/ 3 if (isPrime(n) && (isPowerOfTwo(n * 3 - 1))) { cout << "YES\n"; } else { cout << "NO\n"; } return 0;} // JAVA program to check if a number is// Wagstaff prime or not class GFG { // Function to check if a number is prime or not static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true; } // Utility function to check power of two static boolean isPowerOfTwo(int n) { return n != 0 && ((n & (n - 1)) == 0); } // Driver Program public static void main(String[] args) { int n = 43; // Check if number is prime // and of the form ( 2^q +1 )/3 if (isPrime(n) && (isPowerOfTwo(n * 3 - 1))) { System.out.println("YES"); } else { System.out.println("NO"); } }} # Python 3 program to check if a number is # Wagstaff prime or not # Utility function to check# if a number is prime or notdef isPrime(n) : # Corner cases if (n <= 1) : return False if (n <= 3) : return True # This is checked so that we can skip # middle five numbers in below loop if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True # Utility function to Check# power of two def isPowerOfTwo(n): return (n and (not(n & (n - 1)))) # Driver Code n = 43 # Check if number is prime # and of the form ( 2 ^ q + 1 ) / 3 if(isPrime(n) and isPowerOfTwo(n * 3-1)): print("YES") else: print("NO") // C# program to check if a number// is Wagstaff prime or notusing System; class GFG{ // Function to check if a// number is prime or notstatic bool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we // can skip middle five numbers // in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true;} // Utility function to// check power of twostatic bool isPowerOfTwo(int n){ return n != 0 && ((n & (n - 1)) == 0);} // Driver Codepublic static void Main(){ int n = 43; // Check if number is prime // and of the form ( 2^q +1 )/3 if (isPrime(n) && (isPowerOfTwo(n * 3 - 1))) { Console.WriteLine("YES"); } else { Console.WriteLine("NO"); }}} // This code is contributed// by inder_verma <?php// PHP program to check if a number// is Wagstaff prime or not // Function to check if a// number is prime or notfunction isPrime($n){ // Corner cases if ($n <= 1) return false; if ($n <= 3) return true; // This is checked so that we // can skip middle five numbers // in below loop if ($n % 2 == 0 or $n % 3 == 0) return false; for ($i = 5; $i * $i <= $n; $i = $i + 6) { if ($n % $i == 0 or $n % ($i + 2) == 0) { return false; } } return true;} // Utility function to// check power of twofunction isPowerOfTwo($n){ return ($n && !($n & ($n - 1)));} // Driver Code$n = 43; // Check if number is prime// and of the form (2^q +1 )/ 3 if (isPrime($n) && (isPowerOfTwo($n * 3 - 1))){ echo "YES";}else{ echo"NO";} // This code is contributed// by Shashank?> <script> // JavaScript program to check if a number is// Wagstaff prime or not // Function to check if a number is prime or not function isPrime( n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (var i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true; } // Utility function to check power of two function isPowerOfTwo(n) { return (n != 0 )&& ((n & (n - 1)) == 0); } // Driver Program var n = 43; // Check if number is prime // and of the form ( 2^q +1 )/3 if (isPrime(n) && (isPowerOfTwo(n * 3 - 1))) { document.write("YES"); } else { document.write("NO"); } </script> YES Time Complexity: O(n1/2) Auxiliary Space: O(1) inderDuMCA Shashank12 shubham_singh subhammahato348 akshitsaxenaa09 Prime Number Bit Magic Competitive Programming Mathematical Mathematical Bit Magic Prime Number Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Set, Clear and Toggle a given bit of a number in C Check whether K-th bit is set or not Write an Efficient Method to Check if a Number is Multiple of 3 Reverse actual bits of the given number Program to find parity Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Modulo 10^9+7 (1000000007) Competitive Programming - A Complete Guide Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 24621, "s": 24593, "text": "\n26 Apr, 2021" }, { "code": null, "e": 24922, "s": 24621, "text": "Given a positive integer n, the task is to check if it is a Wagstaff prime or not. Print ‘YES’ if the given number is Wagstaff prime otherwise print ‘NO’.Wagstaff prime: In mathematics, Wagstaff prime is a prime number ‘n’ of the form where ‘q’ is an odd prime.First, few Wagstaff prime numbers are: " }, { "code": null, "e": 24977, "s": 24922, "text": "3, 11, 43, 683, 2731, 43691, 174763, 2796203.........." }, { "code": null, "e": 24989, "s": 24977, "text": "Examples: " }, { "code": null, "e": 25120, "s": 24989, "text": "Input: 43\nOutput: Yes\n43 can be expressed as - (27 + 1 )/ 3\n\nInput: 31\nOutput: No\n31 can not be expressed in above mentioned form." }, { "code": null, "e": 25132, "s": 25120, "text": "Approach: " }, { "code": null, "e": 25493, "s": 25132, "text": "Check first if the given number is a prime number or not. To check for a number to be prime, refer this.Then check if it can be expressed in the form of (n * 3 – 1) and should be a power of 2. To check for a number to be a power of 2, refer this.If both conditions are true, then the number is a Wagstaff prime number. Hence, print “YES”. Otherwise, print “NO”" }, { "code": null, "e": 25598, "s": 25493, "text": "Check first if the given number is a prime number or not. To check for a number to be prime, refer this." }, { "code": null, "e": 25741, "s": 25598, "text": "Then check if it can be expressed in the form of (n * 3 – 1) and should be a power of 2. To check for a number to be a power of 2, refer this." }, { "code": null, "e": 25856, "s": 25741, "text": "If both conditions are true, then the number is a Wagstaff prime number. Hence, print “YES”. Otherwise, print “NO”" }, { "code": null, "e": 25909, "s": 25856, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25913, "s": 25909, "text": "C++" }, { "code": null, "e": 25918, "s": 25913, "text": "Java" }, { "code": null, "e": 25926, "s": 25918, "text": "Python3" }, { "code": null, "e": 25929, "s": 25926, "text": "C#" }, { "code": null, "e": 25933, "s": 25929, "text": "PHP" }, { "code": null, "e": 25944, "s": 25933, "text": "Javascript" }, { "code": "// CPP program to check if a number is// Wagstaff prime or not #include <bits/stdc++.h>using namespace std; // Function to check if a number is prime or notbool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true;} // Utility function to check power of twobool isPowerOfTwo(int n){ return (n && !(n & (n - 1)));} // Driver Programint main(){ int n = 43; // Check if number is prime // and of the form (2^q +1 )/ 3 if (isPrime(n) && (isPowerOfTwo(n * 3 - 1))) { cout << \"YES\\n\"; } else { cout << \"NO\\n\"; } return 0;}", "e": 26840, "s": 25944, "text": null }, { "code": "// JAVA program to check if a number is// Wagstaff prime or not class GFG { // Function to check if a number is prime or not static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true; } // Utility function to check power of two static boolean isPowerOfTwo(int n) { return n != 0 && ((n & (n - 1)) == 0); } // Driver Program public static void main(String[] args) { int n = 43; // Check if number is prime // and of the form ( 2^q +1 )/3 if (isPrime(n) && (isPowerOfTwo(n * 3 - 1))) { System.out.println(\"YES\"); } else { System.out.println(\"NO\"); } }}", "e": 27914, "s": 26840, "text": null }, { "code": "# Python 3 program to check if a number is # Wagstaff prime or not # Utility function to check# if a number is prime or notdef isPrime(n) : # Corner cases if (n <= 1) : return False if (n <= 3) : return True # This is checked so that we can skip # middle five numbers in below loop if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True # Utility function to Check# power of two def isPowerOfTwo(n): return (n and (not(n & (n - 1)))) # Driver Code n = 43 # Check if number is prime # and of the form ( 2 ^ q + 1 ) / 3 if(isPrime(n) and isPowerOfTwo(n * 3-1)): print(\"YES\") else: print(\"NO\")", "e": 28727, "s": 27914, "text": null }, { "code": "// C# program to check if a number// is Wagstaff prime or notusing System; class GFG{ // Function to check if a// number is prime or notstatic bool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we // can skip middle five numbers // in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true;} // Utility function to// check power of twostatic bool isPowerOfTwo(int n){ return n != 0 && ((n & (n - 1)) == 0);} // Driver Codepublic static void Main(){ int n = 43; // Check if number is prime // and of the form ( 2^q +1 )/3 if (isPrime(n) && (isPowerOfTwo(n * 3 - 1))) { Console.WriteLine(\"YES\"); } else { Console.WriteLine(\"NO\"); }}} // This code is contributed// by inder_verma", "e": 29739, "s": 28727, "text": null }, { "code": "<?php// PHP program to check if a number// is Wagstaff prime or not // Function to check if a// number is prime or notfunction isPrime($n){ // Corner cases if ($n <= 1) return false; if ($n <= 3) return true; // This is checked so that we // can skip middle five numbers // in below loop if ($n % 2 == 0 or $n % 3 == 0) return false; for ($i = 5; $i * $i <= $n; $i = $i + 6) { if ($n % $i == 0 or $n % ($i + 2) == 0) { return false; } } return true;} // Utility function to// check power of twofunction isPowerOfTwo($n){ return ($n && !($n & ($n - 1)));} // Driver Code$n = 43; // Check if number is prime// and of the form (2^q +1 )/ 3 if (isPrime($n) && (isPowerOfTwo($n * 3 - 1))){ echo \"YES\";}else{ echo\"NO\";} // This code is contributed// by Shashank?>", "e": 30616, "s": 29739, "text": null }, { "code": "<script> // JavaScript program to check if a number is// Wagstaff prime or not // Function to check if a number is prime or not function isPrime( n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (var i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true; } // Utility function to check power of two function isPowerOfTwo(n) { return (n != 0 )&& ((n & (n - 1)) == 0); } // Driver Program var n = 43; // Check if number is prime // and of the form ( 2^q +1 )/3 if (isPrime(n) && (isPowerOfTwo(n * 3 - 1))) { document.write(\"YES\"); } else { document.write(\"NO\"); } </script>", "e": 31627, "s": 30616, "text": null }, { "code": null, "e": 31631, "s": 31627, "text": "YES" }, { "code": null, "e": 31658, "s": 31633, "text": "Time Complexity: O(n1/2)" }, { "code": null, "e": 31680, "s": 31658, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 31691, "s": 31680, "text": "inderDuMCA" }, { "code": null, "e": 31702, "s": 31691, "text": "Shashank12" }, { "code": null, "e": 31716, "s": 31702, "text": "shubham_singh" }, { "code": null, "e": 31732, "s": 31716, "text": "subhammahato348" }, { "code": null, "e": 31748, "s": 31732, "text": "akshitsaxenaa09" }, { "code": null, "e": 31761, "s": 31748, "text": "Prime Number" }, { "code": null, "e": 31771, "s": 31761, "text": "Bit Magic" }, { "code": null, "e": 31795, "s": 31771, "text": "Competitive Programming" }, { "code": null, "e": 31808, "s": 31795, "text": "Mathematical" }, { "code": null, "e": 31821, "s": 31808, "text": "Mathematical" }, { "code": null, "e": 31831, "s": 31821, "text": "Bit Magic" }, { "code": null, "e": 31844, "s": 31831, "text": "Prime Number" }, { "code": null, "e": 31942, "s": 31844, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31951, "s": 31942, "text": "Comments" }, { "code": null, "e": 31964, "s": 31951, "text": "Old Comments" }, { "code": null, "e": 32015, "s": 31964, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 32052, "s": 32015, "text": "Check whether K-th bit is set or not" }, { "code": null, "e": 32116, "s": 32052, "text": "Write an Efficient Method to Check if a Number is Multiple of 3" }, { "code": null, "e": 32156, "s": 32116, "text": "Reverse actual bits of the given number" }, { "code": null, "e": 32179, "s": 32156, "text": "Program to find parity" }, { "code": null, "e": 32222, "s": 32179, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 32263, "s": 32222, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 32290, "s": 32263, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 32333, "s": 32290, "text": "Competitive Programming - A Complete Guide" } ]
How to link jQuery from Google CDN?
jQuery is a JavaScript library primarily designed with the purpose to make it easier to use JavaScript on our website. jQuery wraps many lines of JavaScript code into methods that we can call with a single line of code. Google provides CDN support for jQuery via the googleapis.com domain. The latest version of Google CDN provides four different types of jQuery versions- normal (uncompressed), minified, slim, and slim & minified. Google CDN provides the jQuery via ajax.googleapis.com domain. jQuery is provided with different versions having different sizes or functionality. The four versions are discussed below. jquery.js is the normal jQuery file that is uncompressed. This version is bigger than the others with all functions included. jquery.js is the normal jQuery file that is uncompressed. This version is bigger than the others with all functions included. query.min.js is the minified version of the jQuery where spaces and unnecessary characters are removed to make the size less. query.min.js is the minified version of the jQuery where spaces and unnecessary characters are removed to make the size less. jquery.slim.js is the less functional version where some less used functions are removed. It includes the most popular and core functions. jquery.slim.js is the less functional version where some less used functions are removed. It includes the most popular and core functions. jquery.slim.min.js is the smallest version where spaces and unnecessary characters and some functions are removed. It's a minified version of jquery.slim.js. jquery.slim.min.js is the smallest version where spaces and unnecessary characters and some functions are removed. It's a minified version of jquery.slim.js. To link normal jQuery from Google CDN, add the Google CDN address in the src attribute of the script tag. The jquery.js can be added like below. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.js"></script> Let’s understand how to link minified jQuery from Google CDN with the help of a complete example. Here, we are using the Google CDN version of the library. You can try to run the following code to learn how to use Google CDN to link jQuery. <html> <head> <title>jQuery Google CDN</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.js"></script> <script> $(document).ready(function() { document.write("Hello, World! We are using Uncompressed jQuery."); }); </script> </head> <body> <h1>Hello</h1> </body> </html> This will produce the following result - Hello, World! We are using Uncompressed jQuery. We can link a minified jQuery from Google CDN by using script tag and providing the Google CDN address as the src attribute. The jquery.min.js can be added like below. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> Let’s understand how to link minified jQuery from Google CDN with the help of a complete example. Here, in the example below we include the minified jQuery library in your HTML page as follows – <html> <head> <title>jQuery Google CDN</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script> <script> $(document).ready(function() { document.write("Hello, World! We are using Minified jQuery."); }); </script> </head> <body> <h1>Hello</h1> </body> </html> On successful execution of the above code, It will produce following result - Hello, World! We are using Minified jQuery. We add the Google CDN address in the src attribute of the script tag, to link slim jQuery from Google CDN. The jquery.slim.js can be added like below. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.slim.js"></script> Let’s understand how to link minified jQuery from Google CDN with the help of a complete example. Here, in the example below we link the slim jQuery library in your HTML page as follows – <html> <head> <title>jQuery Google CDN</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.slim.js"> </script> <script> $(document).ready(function() { document.write("Hello, World! We are using Slim jQuery."); }); </script> </head> <body> <h1>Hello</h1> </body> </html> This will produce the following result - Hello, World! We are using Slim jQuery. To link slim and minified jQuery from Google CDN, add the Google CDN address in the src attribute of the script tag. The jquery.slim.min.js can be added like below. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.slim.min.js"></script> Let’s understand how to link slim and minified jQuery from Google CDN with the help of a complete example. Here, we are using the Google CDN version of the library. You can try to run the following code to learn how to use Google CDN to link slim and minified jQuery. <html> <head> <title>jQuery Google CDN</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.slim.min.js"> </script> <script> $(document).ready(function() { document.write("Hello, World! We are using Slim andMinified jQuery."); }); </script> </head> <body> <h1>Hello</h1> </body> </html> The browser will display the following result - Hello, World! We are using Slim and Minified jQuery. Since the jQuery file is loaded from Google CDN and not from your website, it decreases the load on your website. It improves the overall performance of the website. Since the jQuery file is loaded from Google CDN and not from your website, it decreases the load on your website. It improves the overall performance of the website. Google has servers all over the world decreasing the latency. It ensures that the user will get geographically close responses. Google has servers all over the world decreasing the latency. It ensures that the user will get geographically close responses. The users already have the file ready as more websites use jQuery from Google CDN. It increases the chance of a cache-hit. The users already have the file ready as more websites use jQuery from Google CDN. It increases the chance of a cache-hit.
[ { "code": null, "e": 1558, "s": 1062, "text": "jQuery is a JavaScript library primarily designed with the purpose to make it easier to use JavaScript on our website. jQuery wraps many lines of JavaScript code into methods that we can call with a single line of code. Google provides CDN support for jQuery via the googleapis.com domain. The latest version of Google CDN provides four different types of jQuery versions- normal (uncompressed), minified, slim, and slim & minified. Google CDN provides the jQuery via ajax.googleapis.com domain." }, { "code": null, "e": 1681, "s": 1558, "text": "jQuery is provided with different versions having different sizes or functionality. The four versions are discussed below." }, { "code": null, "e": 1807, "s": 1681, "text": "jquery.js is the normal jQuery file that is uncompressed. This version is bigger than the others with all functions included." }, { "code": null, "e": 1933, "s": 1807, "text": "jquery.js is the normal jQuery file that is uncompressed. This version is bigger than the others with all functions included." }, { "code": null, "e": 2059, "s": 1933, "text": "query.min.js is the minified version of the jQuery where spaces and unnecessary characters are removed to make the size less." }, { "code": null, "e": 2185, "s": 2059, "text": "query.min.js is the minified version of the jQuery where spaces and unnecessary characters are removed to make the size less." }, { "code": null, "e": 2324, "s": 2185, "text": "jquery.slim.js is the less functional version where some less used functions are removed. It includes the most popular and core functions." }, { "code": null, "e": 2463, "s": 2324, "text": "jquery.slim.js is the less functional version where some less used functions are removed. It includes the most popular and core functions." }, { "code": null, "e": 2621, "s": 2463, "text": "jquery.slim.min.js is the smallest version where spaces and unnecessary characters and some functions are removed. It's a minified version of jquery.slim.js." }, { "code": null, "e": 2779, "s": 2621, "text": "jquery.slim.min.js is the smallest version where spaces and unnecessary characters and some functions are removed. It's a minified version of jquery.slim.js." }, { "code": null, "e": 2924, "s": 2779, "text": "To link normal jQuery from Google CDN, add the Google CDN address in the src attribute of the script tag. The jquery.js can be added like below." }, { "code": null, "e": 3009, "s": 2924, "text": "<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.js\"></script>" }, { "code": null, "e": 3107, "s": 3009, "text": "Let’s understand how to link minified jQuery from Google CDN with the help of a complete example." }, { "code": null, "e": 3250, "s": 3107, "text": "Here, we are using the Google CDN version of the library. You can try to run the following code to learn how to use Google CDN to link jQuery." }, { "code": null, "e": 3623, "s": 3250, "text": "<html>\n <head>\n <title>jQuery Google CDN</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.js\"></script>\n <script>\n $(document).ready(function() {\n document.write(\"Hello, World! We are using Uncompressed jQuery.\");\n });\n </script>\n </head>\n <body>\n <h1>Hello</h1>\n </body>\n</html>" }, { "code": null, "e": 3664, "s": 3623, "text": "This will produce the following result -" }, { "code": null, "e": 3712, "s": 3664, "text": "Hello, World! We are using Uncompressed jQuery." }, { "code": null, "e": 3880, "s": 3712, "text": "We can link a minified jQuery from Google CDN by using script tag and providing the Google CDN address as the src attribute. The jquery.min.js can be added like below." }, { "code": null, "e": 3969, "s": 3880, "text": "<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\"></script>" }, { "code": null, "e": 4067, "s": 3969, "text": "Let’s understand how to link minified jQuery from Google CDN with the help of a complete example." }, { "code": null, "e": 4164, "s": 4067, "text": "Here, in the example below we include the minified jQuery library in your HTML page as follows –" }, { "code": null, "e": 4546, "s": 4164, "text": "<html>\n <head>\n <title>jQuery Google CDN</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\"> </script>\n <script>\n $(document).ready(function() {\n document.write(\"Hello, World! We are using Minified jQuery.\");\n });\n </script>\n </head>\n <body>\n <h1>Hello</h1>\n </body>\n</html>" }, { "code": null, "e": 4624, "s": 4546, "text": "On successful execution of the above code, It will produce following result -" }, { "code": null, "e": 4668, "s": 4624, "text": "Hello, World! We are using Minified jQuery." }, { "code": null, "e": 4819, "s": 4668, "text": "We add the Google CDN address in the src attribute of the script tag, to link slim jQuery from Google CDN. The jquery.slim.js can be added like below." }, { "code": null, "e": 4909, "s": 4819, "text": "<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.slim.js\"></script>" }, { "code": null, "e": 5007, "s": 4909, "text": "Let’s understand how to link minified jQuery from Google CDN with the help of a complete example." }, { "code": null, "e": 5097, "s": 5007, "text": "Here, in the example below we link the slim jQuery library in your HTML page as follows –" }, { "code": null, "e": 5470, "s": 5097, "text": "<html>\n <head>\n <title>jQuery Google CDN</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.slim.js\"> </script>\n <script>\n $(document).ready(function() {\n document.write(\"Hello, World! We are using Slim jQuery.\");\n });\n </script>\n </head>\n <body>\n <h1>Hello</h1>\n </body>\n</html>" }, { "code": null, "e": 5511, "s": 5470, "text": "This will produce the following result -" }, { "code": null, "e": 5551, "s": 5511, "text": "Hello, World! We are using Slim jQuery." }, { "code": null, "e": 5716, "s": 5551, "text": "To link slim and minified jQuery from Google CDN, add the Google CDN address in the src attribute of the script tag. The jquery.slim.min.js can be added like below." }, { "code": null, "e": 5810, "s": 5716, "text": "<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.slim.min.js\"></script>" }, { "code": null, "e": 5917, "s": 5810, "text": "Let’s understand how to link slim and minified jQuery from Google CDN with the help of a complete example." }, { "code": null, "e": 6078, "s": 5917, "text": "Here, we are using the Google CDN version of the library. You can try to run the following code to learn how to use Google CDN to link slim and minified jQuery." }, { "code": null, "e": 6500, "s": 6078, "text": "<html>\n <head>\n <title>jQuery Google CDN</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.slim.min.js\"> </script>\n <script>\n $(document).ready(function() {\n document.write(\"Hello, World! We are using Slim andMinified jQuery.\");\n });\n </script>\n </head>\n <body>\n <h1>Hello</h1>\n </body>\n</html>" }, { "code": null, "e": 6548, "s": 6500, "text": "The browser will display the following result -" }, { "code": null, "e": 6601, "s": 6548, "text": "Hello, World! We are using Slim and Minified jQuery." }, { "code": null, "e": 6767, "s": 6601, "text": "Since the jQuery file is loaded from Google CDN and not from your website, it decreases the load on your website. It improves the overall performance of the website." }, { "code": null, "e": 6933, "s": 6767, "text": "Since the jQuery file is loaded from Google CDN and not from your website, it decreases the load on your website. It improves the overall performance of the website." }, { "code": null, "e": 7061, "s": 6933, "text": "Google has servers all over the world decreasing the latency. It ensures that the user will get geographically close responses." }, { "code": null, "e": 7189, "s": 7061, "text": "Google has servers all over the world decreasing the latency. It ensures that the user will get geographically close responses." }, { "code": null, "e": 7312, "s": 7189, "text": "The users already have the file ready as more websites use jQuery from Google CDN. It increases the chance of a cache-hit." }, { "code": null, "e": 7435, "s": 7312, "text": "The users already have the file ready as more websites use jQuery from Google CDN. It increases the chance of a cache-hit." } ]
Design Pattern Quick Guide
Design patterns represent the best practices used by experienced object-oriented software developers. Design patterns are solutions to general problems that software developers faced during software development. These solutions were obtained by trial and error by numerous software developers over quite a substantial period of time. In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson und John Vlissides published a book titled Design Patterns - Elements of Reusable Object-Oriented Software which initiated the concept of Design Pattern in Software development. These authors are collectively known as Gang of Four (GOF). According to these authors design patterns are primarily based on the following principles of object orientated design. Program to an interface not an implementation Program to an interface not an implementation Favor object composition over inheritance Favor object composition over inheritance Design Patterns have two main usages in software development. Design patterns provide a standard terminology and are specific to particular scenario. For example, a singleton design pattern signifies use of single object so all developers familiar with single design pattern will make use of single object and they can tell each other that program is following a singleton pattern. Design patterns have been evolved over a long period of time and they provide best solutions to certain problems faced during software development. Learning these patterns helps un-experienced developers to learn software design in an easy and faster way. As per the design pattern reference book Design Patterns - Elements of Reusable Object-Oriented Software , there are 23 design patterns. These patterns can be classified in three categories: Creational, Structural and behavioral patterns. We'll also discuss another category of design patterns: J2EE design patterns. Factory pattern is one of the most used design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface. We're going to create a Shape interface and concrete classes implementing the Shape interface. A factory class ShapeFactory is defined as a next step. FactoryPatternDemo, our demo class will use ShapeFactory to get a Shape object. It will pass information (CIRCLE / RECTANGLE / SQUARE) to ShapeFactory to get the type of object it needs. Create an interface. Shape.java public interface Shape { void draw(); } Create concrete classes implementing the same interface. Rectangle.java public class Rectangle implements Shape { @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } } Square.java public class Square implements Shape { @Override public void draw() { System.out.println("Inside Square::draw() method."); } } Circle.java public class Circle implements Shape { @Override public void draw() { System.out.println("Inside Circle::draw() method."); } } Create a Factory to generate object of concrete class based on given information. ShapeFactory.java public class ShapeFactory { //use getShape method to get object of type shape public Shape getShape(String shapeType){ if(shapeType == null){ return null; } if(shapeType.equalsIgnoreCase("CIRCLE")){ return new Circle(); } else if(shapeType.equalsIgnoreCase("RECTANGLE")){ return new Rectangle(); } else if(shapeType.equalsIgnoreCase("SQUARE")){ return new Square(); } return null; } } Use the Factory to get object of concrete class by passing an information such as type. FactoryPatternDemo.java public class FactoryPatternDemo { public static void main(String[] args) { ShapeFactory shapeFactory = new ShapeFactory(); //get an object of Circle and call its draw method. Shape shape1 = shapeFactory.getShape("CIRCLE"); //call draw method of Circle shape1.draw(); //get an object of Rectangle and call its draw method. Shape shape2 = shapeFactory.getShape("RECTANGLE"); //call draw method of Rectangle shape2.draw(); //get an object of Square and call its draw method. Shape shape3 = shapeFactory.getShape("SQUARE"); //call draw method of square shape3.draw(); } } Verify the output. Inside Circle::draw() method. Inside Rectangle::draw() method. Inside Square::draw() method. Abstract Factory patterns work around a super-factory which creates other factories. This factory is also called as factory of factories. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. In Abstract Factory pattern an interface is responsible for creating a factory of related objects without explicitly specifying their classes. Each generated factory can give the objects as per the Factory pattern. We are going to create a Shape interface and a concrete class implementing it. We create an abstract factory class AbstractFactory as next step. Factory class ShapeFactory is defined, which extends AbstractFactory. A factory creator/generator class FactoryProducer is created. AbstractFactoryPatternDemo, our demo class uses FactoryProducer to get a AbstractFactory object. It will pass information (CIRCLE / RECTANGLE / SQUARE for Shape) to AbstractFactory to get the type of object it needs. Create an interface for Shapes. Shape.java public interface Shape { void draw(); } Create concrete classes implementing the same interface. RoundedRectangle.java public class RoundedRectangle implements Shape { @Override public void draw() { System.out.println("Inside RoundedRectangle::draw() method."); } } RoundedSquare.java public class RoundedSquare implements Shape { @Override public void draw() { System.out.println("Inside RoundedSquare::draw() method."); } } Rectangle.java public class Rectangle implements Shape { @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } } Create an Abstract class to get factories for Normal and Rounded Shape Objects. AbstractFactory.java public abstract class AbstractFactory { abstract Shape getShape(String shapeType) ; } Create Factory classes extending AbstractFactory to generate object of concrete class based on given information. ShapeFactory.java public class ShapeFactory extends AbstractFactory { @Override public Shape getShape(String shapeType){ if(shapeType.equalsIgnoreCase("RECTANGLE")){ return new Rectangle(); }else if(shapeType.equalsIgnoreCase("SQUARE")){ return new Square(); } return null; } } RoundedShapeFactory.java public class RoundedShapeFactory extends AbstractFactory { @Override public Shape getShape(String shapeType){ if(shapeType.equalsIgnoreCase("RECTANGLE")){ return new RoundedRectangle(); }else if(shapeType.equalsIgnoreCase("SQUARE")){ return new RoundedSquare(); } return null; } } Create a Factory generator/producer class to get factories by passing an information such as Shape FactoryProducer.java public class FactoryProducer { public static AbstractFactory getFactory(boolean rounded){ if(rounded){ return new RoundedShapeFactory(); }else{ return new ShapeFactory(); } } } Use the FactoryProducer to get AbstractFactory in order to get factories of concrete classes by passing an information such as type. AbstractFactoryPatternDemo.java public class AbstractFactoryPatternDemo { public static void main(String[] args) { //get shape factory AbstractFactory shapeFactory = FactoryProducer.getFactory(false); //get an object of Shape Rectangle Shape shape1 = shapeFactory.getShape("RECTANGLE"); //call draw method of Shape Rectangle shape1.draw(); //get an object of Shape Square Shape shape2 = shapeFactory.getShape("SQUARE"); //call draw method of Shape Square shape2.draw(); //get shape factory AbstractFactory shapeFactory1 = FactoryProducer.getFactory(true); //get an object of Shape Rectangle Shape shape3 = shapeFactory1.getShape("RECTANGLE"); //call draw method of Shape Rectangle shape3.draw(); //get an object of Shape Square Shape shape4 = shapeFactory1.getShape("SQUARE"); //call draw method of Shape Square shape4.draw(); } } Verify the output. Inside Rectangle::draw() method. Inside Square::draw() method. Inside RoundedRectangle::draw() method. Inside RoundedSquare::draw() method. Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best way to create an object. This pattern involves a single class which is responsible to creates own object while making sure that only single object get created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class. We're going to create a SingleObject class. SingleObject class have its constructor as private and have a static instance of itself. SingleObject class provides a static method to get its static instance to outside world. SingletonPatternDemo, our demo class will use SingleObject class to get a SingleObject object. Create a Singleton Class. SingleObject.java public class SingleObject { //create an object of SingleObject private static SingleObject instance = new SingleObject(); //make the constructor private so that this class cannot be //instantiated private SingleObject(){} //Get the only object available public static SingleObject getInstance(){ return instance; } public void showMessage(){ System.out.println("Hello World!"); } } Get the only object from the singleton class. SingletonPatternDemo.java public class SingletonPatternDemo { public static void main(String[] args) { //illegal construct //Compile Time Error: The constructor SingleObject() is not visible //SingleObject object = new SingleObject(); //Get the only object available SingleObject object = SingleObject.getInstance(); //show the message object.showMessage(); } } Verify the output. Hello World! Builder pattern builds a complex object using simple objects and using a step by step approach. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. A Builder class builds the final object step by step. This builder is independent of other objects. We've considered a business case of fast-food restaurant where a typical meal could be a burger and a cold drink. Burger could be either a Veg Burger or Chicken Burger and will be packed by a wrapper. Cold drink could be either a coke or pepsi and will be packed in a bottle. We're going to create an Item interface representing food items such as burgers and cold drinks and concrete classes implementing the Item interface and a Packing interface representing packaging of food items and concrete classes implementing the Packing interface as burger would be packed in wrapper and cold drink would be packed as bottle. We then create a Meal class having ArrayList of Item and a MealBuilder to build different types of Meal object by combining Item. BuilderPatternDemo, our demo class will use MealBuilder to build a Meal. Create an interface Item representing food item and packing. Item.java public interface Item { public String name(); public Packing packing(); public float price(); } Packing.java public interface Packing { public String pack(); } Create concreate classes implementing the Packing interface. Wrapper.java public class Wrapper implements Packing { @Override public String pack() { return "Wrapper"; } } Bottle.java public class Bottle implements Packing { @Override public String pack() { return "Bottle"; } } Create abstract classes implementing the item interface providing default functionalities. Burger.java public abstract class Burger implements Item { @Override public Packing packing() { return new Wrapper(); } @Override public abstract float price(); } ColdDrink.java public abstract class ColdDrink implements Item { @Override public Packing packing() { return new Bottle(); } @Override public abstract float price(); } Create concrete classes extending Burger and ColdDrink classes VegBurger.java public class VegBurger extends Burger { @Override public float price() { return 25.0f; } @Override public String name() { return "Veg Burger"; } } ChickenBurger.java public class ChickenBurger extends Burger { @Override public float price() { return 50.5f; } @Override public String name() { return "Chicken Burger"; } } Coke.java public class Coke extends ColdDrink { @Override public float price() { return 30.0f; } @Override public String name() { return "Coke"; } } Pepsi.java public class Pepsi extends ColdDrink { @Override public float price() { return 35.0f; } @Override public String name() { return "Pepsi"; } } Create a Meal class having Item objects defined above. Meal.java import java.util.ArrayList; import java.util.List; public class Meal { private List<Item> items = new ArrayList<Item>(); public void addItem(Item item){ items.add(item); } public float getCost(){ float cost = 0.0f; for (Item item : items) { cost += item.price(); } return cost; } public void showItems(){ for (Item item : items) { System.out.print("Item : "+item.name()); System.out.print(", Packing : "+item.packing().pack()); System.out.println(", Price : "+item.price()); } } } Create a MealBuilder class, the actual builder class responsible to create Meal objects. MealBuilder.java public class MealBuilder { public Meal prepareVegMeal (){ Meal meal = new Meal(); meal.addItem(new VegBurger()); meal.addItem(new Coke()); return meal; } public Meal prepareNonVegMeal (){ Meal meal = new Meal(); meal.addItem(new ChickenBurger()); meal.addItem(new Pepsi()); return meal; } } BuiderPatternDemo uses MealBuider to demonstrate builder pattern. BuilderPatternDemo.java public class BuilderPatternDemo { public static void main(String[] args) { MealBuilder mealBuilder = new MealBuilder(); Meal vegMeal = mealBuilder.prepareVegMeal(); System.out.println("Veg Meal"); vegMeal.showItems(); System.out.println("Total Cost: " +vegMeal.getCost()); Meal nonVegMeal = mealBuilder.prepareNonVegMeal(); System.out.println("\n\nNon-Veg Meal"); nonVegMeal.showItems(); System.out.println("Total Cost: " +nonVegMeal.getCost()); } } Verify the output. Veg Meal Item : Veg Burger, Packing : Wrapper, Price : 25.0 Item : Coke, Packing : Bottle, Price : 30.0 Total Cost: 55.0 Non-Veg Meal Item : Chicken Burger, Packing : Wrapper, Price : 50.5 Item : Pepsi, Packing : Bottle, Price : 35.0 Total Cost: 85.5 Prototype pattern refers to creating duplicate object while keeping performance in mind. This type of design pattern comes under creational pattern as this pattern provides one of the best way to create an object. This pattern involves implementing a prototype interface which tells to create a clone of the current object. This pattern is used when creation of object directly is costly. For example, a object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database as as and when needed thus reducing database calls. We're going to create an abstract class Shape and concrete classes extending the Shape class. A class ShapeCache is defined as a next step which stores shape objects in a Hashtable and returns their clone when requested. PrototypPatternDemo, our demo class will use ShapeCache class to get a Shape object. Create an abstract class implementing Clonable interface. Shape.java public abstract class Shape implements Cloneable { private String id; protected String type; abstract void draw(); public String getType(){ return type; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Object clone() { Object clone = null; try { clone = super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return clone; } } Create concrete classes extending the above class. Rectangle.java public class Rectangle extends Shape { public Rectangle(){ type = "Rectangle"; } @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } } Square.java public class Square extends Shape { public Square(){ type = "Square"; } @Override public void draw() { System.out.println("Inside Square::draw() method."); } } Circle.java public class Circle extends Shape { public Circle(){ type = "Circle"; } @Override public void draw() { System.out.println("Inside Circle::draw() method."); } } Create a class to get concreate classes from database and store them in a Hashtable. ShapeCache.java import java.util.Hashtable; public class ShapeCache { private static Hashtable<String, Shape> shapeMap = new Hashtable<String, Shape>(); public static Shape getShape(String shapeId) { Shape cachedShape = shapeMap.get(shapeId); return (Shape) cachedShape.clone(); } // for each shape run database query and create shape // shapeMap.put(shapeKey, shape); // for example, we are adding three shapes public static void loadCache() { Circle circle = new Circle(); circle.setId("1"); shapeMap.put(circle.getId(),circle); Square square = new Square(); square.setId("2"); shapeMap.put(square.getId(),square); Rectangle rectangle = new Rectangle(); rectangle.setId("3"); shapeMap.put(rectangle.getId(),rectangle); } } PrototypePatternDemo uses ShapeCache class to get clones of shapes stored in a Hashtable. PrototypePatternDemo.java public class PrototypePatternDemo { public static void main(String[] args) { ShapeCache.loadCache(); Shape clonedShape = (Shape) ShapeCache.getShape("1"); System.out.println("Shape : " + clonedShape.getType()); Shape clonedShape2 = (Shape) ShapeCache.getShape("2"); System.out.println("Shape : " + clonedShape2.getType()); Shape clonedShape3 = (Shape) ShapeCache.getShape("3"); System.out.println("Shape : " + clonedShape3.getType()); } } Verify the output. Shape : Circle Shape : Square Shape : Rectangle Adapter pattern works as a bridge between two incompatible interfaces. This type of design pattern comes under structural pattern as this pattern combines the capability of two independent interfaces. This pattern involves a single class which is responsible to join functionalities of independent or incompatible interfaces. A real life example could be a case of card reader which acts as an adapter between memory card and a laptop. You plugins the memory card into card reader and card reader into the laptop so that memory card can be read via laptop. We are demonstrating use of Adapter pattern via following example in which an audio player device can play mp3 files only and wants to use an advanced audio player capable of playing vlc and mp4 files. We've an interface MediaPlayer interface and a concrete class AudioPlayer implementing the MediaPlayer interface. AudioPlayer can play mp3 format audio files by default. We're having another interface AdvancedMediaPlayer and concrete classes implementing the AdvancedMediaPlayer interface.These classes can play vlc and mp4 format files. We want to make AudioPlayer to play other formats as well. To attain this, we've created an adapter class MediaAdapter which implements the MediaPlayer interface and uses AdvancedMediaPlayer objects to play the required format. AudioPlayer uses the adapter class MediaAdapter passing it the desired audio type without knowing the actual class which can play the desired format. AdapterPatternDemo, our demo class will use AudioPlayer class to play various formats. Create interfaces for Media Player and Advanced Media Player. MediaPlayer.java public interface MediaPlayer { public void play(String audioType, String fileName); } AdvancedMediaPlayer.java public interface AdvancedMediaPlayer { public void playVlc(String fileName); public void playMp4(String fileName); } Create concrete classes implementing the AdvancedMediaPlayer interface. VlcPlayer.java public class VlcPlayer implements AdvancedMediaPlayer{ @Override public void playVlc(String fileName) { System.out.println("Playing vlc file. Name: "+ fileName); } @Override public void playMp4(String fileName) { //do nothing } } Mp4Player.java public class Mp4Player implements AdvancedMediaPlayer{ @Override public void playVlc(String fileName) { //do nothing } @Override public void playMp4(String fileName) { System.out.println("Playing mp4 file. Name: "+ fileName); } } Create adapter class implementing the MediaPlayer interface. MediaAdapter.java public class MediaAdapter implements MediaPlayer { AdvancedMediaPlayer advancedMusicPlayer; public MediaAdapter(String audioType){ if(audioType.equalsIgnoreCase("vlc") ){ advancedMusicPlayer = new VlcPlayer(); } else if (audioType.equalsIgnoreCase("mp4")){ advancedMusicPlayer = new Mp4Player(); } } @Override public void play(String audioType, String fileName) { if(audioType.equalsIgnoreCase("vlc")){ advancedMusicPlayer.playVlc(fileName); }else if(audioType.equalsIgnoreCase("mp4")){ advancedMusicPlayer.playMp4(fileName); } } } Create concrete class implementing the MediaPlayer interface. AudioPlayer.java public class AudioPlayer implements MediaPlayer { MediaAdapter mediaAdapter; @Override public void play(String audioType, String fileName) { //inbuilt support to play mp3 music files if(audioType.equalsIgnoreCase("mp3")){ System.out.println("Playing mp3 file. Name: "+ fileName); } //mediaAdapter is providing support to play other file formats else if(audioType.equalsIgnoreCase("vlc") || audioType.equalsIgnoreCase("mp4")){ mediaAdapter = new MediaAdapter(audioType); mediaAdapter.play(audioType, fileName); } else{ System.out.println("Invalid media. "+ audioType + " format not supported"); } } } Use the AudioPlayer to play different types of audio formats. AdapterPatternDemo.java public class AdapterPatternDemo { public static void main(String[] args) { AudioPlayer audioPlayer = new AudioPlayer(); audioPlayer.play("mp3", "beyond the horizon.mp3"); audioPlayer.play("mp4", "alone.mp4"); audioPlayer.play("vlc", "far far away.vlc"); audioPlayer.play("avi", "mind me.avi"); } } Verify the output. Playing mp3 file. Name: beyond the horizon.mp3 Playing mp4 file. Name: alone.mp4 Playing vlc file. Name: far far away.vlc Invalid media. avi format not supported Bridge is used where we need to decouple an abstraction from its implementation so that the two can vary independently. This type of design pattern comes under structural pattern as this pattern decouples implementation class and abstract class by providing a bridge structure between them. This pattern involves an interface which acts as a bridge which makes the functionality of concrete classes independent from interface implementer classes. Both types of classes can be altered structurally without affecting each other. We are demonstrating use of Bridge pattern via following example in which a circle can be drawn in different colors using same abstract class method but different bridge implementer classes. We've an interface DrawAPI interface which is acting as a bridge implementer and concrete classes RedCircle, GreenCircle implementing the DrawAPI interface. Shape is an abstract class and will use object of DrawAPI. BridgePatternDemo, our demo class will use Shape class to draw different colored circle. Create bridge implementer interface. DrawAPI.java public interface DrawAPI { public void drawCircle(int radius, int x, int y); } Create concrete bridge implementer classes implementing the DrawAPI interface. RedCircle.java public class RedCircle implements DrawAPI { @Override public void drawCircle(int radius, int x, int y) { System.out.println("Drawing Circle[ color: red, radius: " + radius +", x: " +x+", "+ y +"]"); } } GreenCircle.java public class GreenCircle implements DrawAPI { @Override public void drawCircle(int radius, int x, int y) { System.out.println("Drawing Circle[ color: green, radius: " + radius +", x: " +x+", "+ y +"]"); } } Create an abstract class Shape using the DrawAPI interface. Shape.java public abstract class Shape { protected DrawAPI drawAPI; protected Shape(DrawAPI drawAPI){ this.drawAPI = drawAPI; } public abstract void draw(); } Create concrete class implementing the Shape interface. Circle.java public class Circle extends Shape { private int x, y, radius; public Circle(int x, int y, int radius, DrawAPI drawAPI) { super(drawAPI); this.x = x; this.y = y; this.radius = radius; } public void draw() { drawAPI.drawCircle(radius,x,y); } } Use the Shape and DrawAPI classes to draw different colored circles. BridgePatternDemo.java public class BridgePatternDemo { public static void main(String[] args) { Shape redCircle = new Circle(100,100, 10, new RedCircle()); Shape greenCircle = new Circle(100,100, 10, new GreenCircle()); redCircle.draw(); greenCircle.draw(); } } Verify the output. Drawing Circle[ color: red, radius: 10, x: 100, 100] Drawing Circle[ color: green, radius: 10, x: 100, 100] Filter pattern or Criteria pattern is a design pattern that enables developers to filter a set of objects, using different criteria, chaining them in a decoupled way through logical operations. This type of design pattern comes under structural pattern as this pattern is combining multiple criteria to obtain single criteria. We're going to create a Person object, Criteria interface and concrete classes implementing this interface to filter list of Person objects. CriteriaPatternDemo, our demo class uses Criteria objects to filter List of Person objects based on various criteria and their combinations. Create a class on which criteria is to be applied. Person.java public class Person { private String name; private String gender; private String maritalStatus; public Person(String name,String gender,String maritalStatus){ this.name = name; this.gender = gender; this.maritalStatus = maritalStatus; } public String getName() { return name; } public String getGender() { return gender; } public String getMaritalStatus() { return maritalStatus; } } Create an interface for Criteria. Criteria.java import java.util.List; public interface Criteria { public List<Person> meetCriteria(List<Person> persons); } Create concrete classes implementing the Criteria interface. CriteriaMale.java import java.util.ArrayList; import java.util.List; public class CriteriaMale implements Criteria { @Override public List<Person> meetCriteria(List<Person> persons) { List<Person> malePersons = new ArrayList<Person>(); for (Person person : persons) { if(person.getGender().equalsIgnoreCase("MALE")){ malePersons.add(person); } } return malePersons; } } CriteriaFemale.java import java.util.ArrayList; import java.util.List; public class CriteriaFemale implements Criteria { @Override public List<Person> meetCriteria(List<Person> persons) { List<Person> femalePersons = new ArrayList<Person>(); for (Person person : persons) { if(person.getGender().equalsIgnoreCase("FEMALE")){ femalePersons.add(person); } } return femalePersons; } } CriteriaSingle.java import java.util.ArrayList; import java.util.List; public class CriteriaSingle implements Criteria { @Override public List<Person> meetCriteria(List<Person> persons) { List<Person> singlePersons = new ArrayList<Person>(); for (Person person : persons) { if(person.getMaritalStatus().equalsIgnoreCase("SINGLE")){ singlePersons.add(person); } } return singlePersons; } } AndCriteria.java import java.util.List; public class AndCriteria implements Criteria { private Criteria criteria; private Criteria otherCriteria; public AndCriteria(Criteria criteria, Criteria otherCriteria) { this.criteria = criteria; this.otherCriteria = otherCriteria; } @Override public List<Person> meetCriteria(List<Person> persons) { List<Person> firstCriteriaPersons = criteria.meetCriteria(persons); return otherCriteria.meetCriteria(firstCriteriaPersons); } } OrCriteria.java import java.util.List; public class AndCriteria implements Criteria { private Criteria criteria; private Criteria otherCriteria; public AndCriteria(Criteria criteria, Criteria otherCriteria) { this.criteria = criteria; this.otherCriteria = otherCriteria; } @Override public List<Person> meetCriteria(List<Person> persons) { List<Person> firstCriteriaItems = criteria.meetCriteria(persons); List<Person> otherCriteriaItems = otherCriteria.meetCriteria(persons); for (Person person : otherCriteriaItems) { if(!firstCriteriaItems.contains(person)){ firstCriteriaItems.add(person); } } return firstCriteriaItems; } } Use different Criteria and their combination to filter out persons. CriteriaPatternDemo.java import java.util.ArrayList; import java.util.List; public class CriteriaPatternDemo { public static void main(String[] args) { List<Person> persons = new ArrayList<Person>(); persons.add(new Person("Robert","Male", "Single")); persons.add(new Person("John","Male", "Married")); persons.add(new Person("Laura","Female", "Married")); persons.add(new Person("Diana","Female", "Single")); persons.add(new Person("Mike","Male", "Single")); persons.add(new Person("Bobby","Male", "Single")); Criteria male = new CriteriaMale(); Criteria female = new CriteriaFemale(); Criteria single = new CriteriaSingle(); Criteria singleMale = new AndCriteria(single, male); Criteria singleOrFemale = new OrCriteria(single, female); System.out.println("Males: "); printPersons(male.meetCriteria(persons)); System.out.println("\nFemales: "); printPersons(female.meetCriteria(persons)); System.out.println("\nSingle Males: "); printPersons(singleMale.meetCriteria(persons)); System.out.println("\nSingle Or Females: "); printPersons(singleOrFemale.meetCriteria(persons)); } public static void printPersons(List<Person> persons){ for (Person person : persons) { System.out.println("Person : [ Name : " + person.getName() +", Gender : " + person.getGender() +", Marital Status : " + person.getMaritalStatus() +" ]"); } } } Verify the output. Males: Person : [ Name : Robert, Gender : Male, Marital Status : Single ] Person : [ Name : John, Gender : Male, Marital Status : Married ] Person : [ Name : Mike, Gender : Male, Marital Status : Single ] Person : [ Name : Bobby, Gender : Male, Marital Status : Single ] Females: Person : [ Name : Laura, Gender : Female, Marital Status : Married ] Person : [ Name : Diana, Gender : Female, Marital Status : Single ] Single Males: Person : [ Name : Robert, Gender : Male, Marital Status : Single ] Person : [ Name : Mike, Gender : Male, Marital Status : Single ] Person : [ Name : Bobby, Gender : Male, Marital Status : Single ] Single Or Females: Person : [ Name : Robert, Gender : Male, Marital Status : Single ] Person : [ Name : Diana, Gender : Female, Marital Status : Single ] Person : [ Name : Mike, Gender : Male, Marital Status : Single ] Person : [ Name : Bobby, Gender : Male, Marital Status : Single ] Person : [ Name : Laura, Gender : Female, Marital Status : Married ] Composite pattern is used where we need to treat a group of objects in similar way as a single object. Composite pattern composes objects in term of a tree structure to represent part as well as whole hierarchy . This type of design pattern comes under structural pattern as this pattern creates a tree structure of group of objects. This pattern creates a class contains group of its own objects. This class provides ways to modify its group of same objects. We are demonstrating use of Composite pattern via following example in which show employees hierarchy of an organization. We've a class Employee which acts as composite pattern actor class. CompositePatternDemo, our demo class will use Employee class to add department level hierarchy and print all employees. Create Employee class having list of Employee objects. Employee.java import java.util.ArrayList; import java.util.List; public class Employee { private String name; private String dept; private int salary; private List<Employee> subordinates; // constructor public Employee(String name,String dept, int sal) { this.name = name; this.dept = dept; this.salary = sal; subordinates = new ArrayList<Employee>(); } public void add(Employee e) { subordinates.add(e); } public void remove(Employee e) { subordinates.remove(e); } public List<Employee> getSubordinates(){ return subordinates; } public String toString(){ return ("Employee :[ Name : "+ name +", dept : "+ dept + ", salary :" + salary+" ]"); } } Use the Employee class to create and print employee hierarchy. CompositePatternDemo.java public class CompositePatternDemo { public static void main(String[] args) { Employee CEO = new Employee("John","CEO", 30000); Employee headSales = new Employee("Robert","Head Sales", 20000); Employee headMarketing = new Employee("Michel","Head Marketing", 20000); Employee clerk1 = new Employee("Laura","Marketing", 10000); Employee clerk2 = new Employee("Bob","Marketing", 10000); Employee salesExecutive1 = new Employee("Richard","Sales", 10000); Employee salesExecutive2 = new Employee("Rob","Sales", 10000); CEO.add(headSales); CEO.add(headMarketing); headSales.add(salesExecutive1); headSales.add(salesExecutive2); headMarketing.add(clerk1); headMarketing.add(clerk2); //print all employees of the organization System.out.println(CEO); for (Employee headEmployee : CEO.getSubordinates()) { System.out.println(headEmployee); for (Employee employee : headEmployee.getSubordinates()) { System.out.println(employee); } } } } Verify the output. Employee :[ Name : John, dept : CEO, salary :30000 ] Employee :[ Name : Robert, dept : Head Sales, salary :20000 ] Employee :[ Name : Richard, dept : Sales, salary :10000 ] Employee :[ Name : Rob, dept : Sales, salary :10000 ] Employee :[ Name : Michel, dept : Head Marketing, salary :20000 ] Employee :[ Name : Laura, dept : Marketing, salary :10000 ] Employee :[ Name : Bob, dept : Marketing, salary :10000 ] Decorator pattern allows to add new functionality an existing object without altering its structure. This type of design pattern comes under structural pattern as this pattern acts as a wrapper to existing class. This pattern creates a decorator class which wraps the original class and provides additional functionality keeping class methods signature intact. We are demonstrating use of Decorator pattern via following example in which we'll decorate a shape with some color without alter shape class. We're going to create a Shape interface and concrete classes implementing the Shape interface. We then create a abstract decorator class ShapeDecorator implementing the Shape interface and having Shape object as its instance variable. RedShapeDecorator is concrete class implementing ShapeDecorator. DecoratorPatternDemo, our demo class will use RedShapeDecorator to decorate Shape objects. Create an interface. Shape.java public interface Shape { void draw(); } Create concrete classes implementing the same interface. Rectangle.java public class Rectangle implements Shape { @Override public void draw() { System.out.println("Shape: Rectangle"); } } Circle.java public class Circle implements Shape { @Override public void draw() { System.out.println("Shape: Circle"); } } Create abstract decorator class implementing the Shape interface. ShapeDecorator.java public abstract class ShapeDecorator implements Shape { protected Shape decoratedShape; public ShapeDecorator(Shape decoratedShape){ this.decoratedShape = decoratedShape; } public void draw(){ decoratedShape.draw(); } } Create concrete decorator class extending the ShapeDecorator class. RedShapeDecorator.java public class RedShapeDecorator extends ShapeDecorator { public RedShapeDecorator(Shape decoratedShape) { super(decoratedShape); } @Override public void draw() { decoratedShape.draw(); setRedBorder(decoratedShape); } private void setRedBorder(Shape decoratedShape){ System.out.println("Border Color: Red"); } } Use the RedShapeDecorator to decorate Shape objects. DecoratorPatternDemo.java public class DecoratorPatternDemo { public static void main(String[] args) { Shape circle = new Circle(); Shape redCircle = new RedShapeDecorator(new Circle()); Shape redRectangle = new RedShapeDecorator(new Rectangle()); System.out.println("Circle with normal border"); circle.draw(); System.out.println("\nCircle of red border"); redCircle.draw(); System.out.println("\nRectangle of red border"); redRectangle.draw(); } } Verify the output. Circle with normal border Shape: Circle Circle of red border Shape: Circle Border Color: Red Rectangle of red border Shape: Rectangle Border Color: Red Facade pattern hides the complexities of the system and provides an interface to the client using which the client can access the system. This type of design pattern comes under structural pattern as this pattern adds an interface to exiting system to hide its complexities. This pattern involves a single class which provides simplified methods which are required by client and delegates calls to existing system classes methods. We're going to create a Shape interface and concrete classes implementing the Shape interface. A facade class ShapeMaker is defined as a next step. ShapeMaker class uses the concrete classes to delegates user calls to these classes. FacadePatternDemo, our demo class will use ShapeMaker class to show the results. Create an interface. Shape.java public interface Shape { void draw(); } Create concrete classes implementing the same interface. Rectangle.java public class Rectangle implements Shape { @Override public void draw() { System.out.println("Rectangle::draw()"); } } Square.java public class Square implements Shape { @Override public void draw() { System.out.println("Square::draw()"); } } Circle.java public class Circle implements Shape { @Override public void draw() { System.out.println("Circle::draw()"); } } Create a facade class. ShapeMaker.java public class ShapeMaker { private Shape circle; private Shape rectangle; private Shape square; public ShapeMaker() { circle = new Circle(); rectangle = new Rectangle(); square = new Square(); } public void drawCircle(){ circle.draw(); } public void drawRectangle(){ rectangle.draw(); } public void drawSquare(){ square.draw(); } } Use the facade to draw various types of shapes. FacadePatternDemo.java public class FacadePatternDemo { public static void main(String[] args) { ShapeMaker shapeMaker = new ShapeMaker(); shapeMaker.drawCircle(); shapeMaker.drawRectangle(); shapeMaker.drawSquare(); } } Verify the output. Circle::draw() Rectangle::draw() Square::draw() Flyweight pattern is primarily used to reduce the number of objects created, to decrease memory footprint and increase performance. This type of design pattern comes under structural pattern as this pattern provides ways to decrease objects count thus improving application required objects structure. Flyweight pattern try to reuse already existing similar kind objects by storing them and creates new object when no matching object is found. We'll demonstrate this pattern by drawing 20 circle of different locations but we'll creating only 5 objects. Only 5 colors are available so color property is used to check already existing Circle objects. We're going to create a Shape interface and concrete class Circle implementing the Shape interface. A factory class ShapeFactory is defined as a next step. ShapeFactory have a HashMap of Circle having key as color of the Circle object. Whenever a request comes to create a circle of particular color to ShapeFactory. ShapeFactory checks the circle object in its HashMap, if object of Circle found, that object is returned otherwise a new object is created, stored in hashmap for future use and returned to client. FlyWeightPatternDemo, our demo class will use ShapeFactory to get a Shape object. It will pass information (red / green / blue/ black / white) to ShapeFactory to get the circle of desired color it needs. Create an interface. Shape.java public interface Shape { void draw(); } Create concrete class implementing the same interface. Circle.java public class Circle implements Shape { private String color; private int x; private int y; private int radius; public Circle(String color){ this.color = color; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public void setRadius(int radius) { this.radius = radius; } @Override public void draw() { System.out.println("Circle: Draw() [Color : " + color +", x : " + x +", y :" + y +", radius :" + radius); } } Create a Factory to generate object of concrete class based on given information. ShapeFactory.java import java.util.HashMap; public class ShapeFactory { // Uncomment the compiler directive line and // javac *.java will compile properly. // @SuppressWarnings("unchecked") private static final HashMap circleMap = new HashMap(); public static Shape getCircle(String color) { Circle circle = (Circle)circleMap.get(color); if(circle == null) { circle = new Circle(color); circleMap.put(color, circle); System.out.println("Creating circle of color : " + color); } return circle; } } Use the Factory to get object of concrete class by passing an information such as color. FlyweightPatternDemo.java public class FlyweightPatternDemo { private static final String colors[] = { "Red", "Green", "Blue", "White", "Black" }; public static void main(String[] args) { for(int i=0; i < 20; ++i) { Circle circle = (Circle)ShapeFactory.getCircle(getRandomColor()); circle.setX(getRandomX()); circle.setY(getRandomY()); circle.setRadius(100); circle.draw(); } } private static String getRandomColor() { return colors[(int)(Math.random()*colors.length)]; } private static int getRandomX() { return (int)(Math.random()*100 ); } private static int getRandomY() { return (int)(Math.random()*100); } } Verify the output. Creating circle of color : Black Circle: Draw() [Color : Black, x : 36, y :71, radius :100 Creating circle of color : Green Circle: Draw() [Color : Green, x : 27, y :27, radius :100 Creating circle of color : White Circle: Draw() [Color : White, x : 64, y :10, radius :100 Creating circle of color : Red Circle: Draw() [Color : Red, x : 15, y :44, radius :100 Circle: Draw() [Color : Green, x : 19, y :10, radius :100 Circle: Draw() [Color : Green, x : 94, y :32, radius :100 Circle: Draw() [Color : White, x : 69, y :98, radius :100 Creating circle of color : Blue Circle: Draw() [Color : Blue, x : 13, y :4, radius :100 Circle: Draw() [Color : Green, x : 21, y :21, radius :100 Circle: Draw() [Color : Blue, x : 55, y :86, radius :100 Circle: Draw() [Color : White, x : 90, y :70, radius :100 Circle: Draw() [Color : Green, x : 78, y :3, radius :100 Circle: Draw() [Color : Green, x : 64, y :89, radius :100 Circle: Draw() [Color : Blue, x : 3, y :91, radius :100 Circle: Draw() [Color : Blue, x : 62, y :82, radius :100 Circle: Draw() [Color : Green, x : 97, y :61, radius :100 Circle: Draw() [Color : Green, x : 86, y :12, radius :100 Circle: Draw() [Color : Green, x : 38, y :93, radius :100 Circle: Draw() [Color : Red, x : 76, y :82, radius :100 Circle: Draw() [Color : Blue, x : 95, y :82, radius :100 In Proxy pattern, a class represents functionality of another class. This type of design pattern comes under structural pattern. In Proxy pattern, we create object having original object to interface its functionality to outer world. We're going to create a Image interface and concrete classes implementing the Image interface. ProxyImage is a a proxy class to reduce memory footprint of RealImage object loading. ProxyPatternDemo, our demo class will use ProxyImage to get a Image object to load and display as it needs. Create an interface. Image.java public interface Image { void display(); } Create concrete classes implementing the same interface. RealImage.java public class RealImage implements Image { private String fileName; public RealImage(String fileName){ this.fileName = fileName; loadFromDisk(fileName); } @Override public void display() { System.out.println("Displaying " + fileName); } private void loadFromDisk(String fileName){ System.out.println("Loading " + fileName); } } ProxyImage.java public class ProxyImage implements Image{ private RealImage realImage; private String fileName; public ProxyImage(String fileName){ this.fileName = fileName; } @Override public void display() { if(realImage == null){ realImage = new RealImage(fileName); } realImage.display(); } } Use the ProxyImage to get object of RealImage class when required. ProxyPatternDemo.java public class ProxyPatternDemo { public static void main(String[] args) { Image image = new ProxyImage("test_10mb.jpg"); //image will be loaded from disk image.display(); System.out.println(""); //image will not be loaded from disk image.display(); } } Verify the output. Loading test_10mb.jpg Displaying test_10mb.jpg Displaying test_10mb.jpg As the name suggest, the chain of responsibility pattern creates a chain of receiver objects for a request. This pattern decouples sender and receiver of a request based on type of request. This pattern comes under behavioral patterns. In this pattern, normally each receiver contains reference to another receiver. If one object cannot handle the request then it passes the same to the next receiver and so on. We've created an abstract class AbstractLogger with a level of logging. Then we've created three types of loggers extending the AbstractLogger. Each logger checks the level of message to its level and print accordingly otherwise does not print and pass the message to its next logger. Create an abstract logger class. AbstractLogger.java public abstract class AbstractLogger { public static int INFO = 1; public static int DEBUG = 2; public static int ERROR = 3; protected int level; //next element in chain or responsibility protected AbstractLogger nextLogger; public void setNextLogger(AbstractLogger nextLogger){ this.nextLogger = nextLogger; } public void logMessage(int level, String message){ if(this.level <= level){ write(message); } if(nextLogger !=null){ nextLogger.logMessage(level, message); } } abstract protected void write(String message); } Create concrete classes extending the logger. ConsoleLogger.java public class ConsoleLogger extends AbstractLogger { public ConsoleLogger(int level){ this.level = level; } @Override protected void write(String message) { System.out.println("Standard Console::Logger: " + message); } } ErrorLogger.java public class ErrorLogger extends AbstractLogger { public ErrorLogger(int level){ this.level = level; } @Override protected void write(String message) { System.out.println("Error Console::Logger: " + message); } } FileLogger.java public class FileLogger extends AbstractLogger { public FileLogger(int level){ this.level = level; } @Override protected void write(String message) { System.out.println("File::Logger: " + message); } } Create different types of loggers. Assign them error levels and set next logger in each logger. Next logger in each logger represents the part of the chain. ChainPatternDemo.java public class ChainPatternDemo { private static AbstractLogger getChainOfLoggers(){ AbstractLogger errorLogger = new ErrorLogger(AbstractLogger.ERROR); AbstractLogger fileLogger = new FileLogger(AbstractLogger.DEBUG); AbstractLogger consoleLogger = new ConsoleLogger(AbstractLogger.INFO); errorLogger.setNextLogger(fileLogger); fileLogger.setNextLogger(consoleLogger); return errorLogger; } public static void main(String[] args) { AbstractLogger loggerChain = getChainOfLoggers(); loggerChain.logMessage(AbstractLogger.INFO, "This is an information."); loggerChain.logMessage(AbstractLogger.DEBUG, "This is an debug level information."); loggerChain.logMessage(AbstractLogger.ERROR, "This is an error information."); } } Verify the output. Standard Console::Logger: This is an information. File::Logger: This is an debug level information. Standard Console::Logger: This is an debug level information. Error Console::Logger: This is an error information. File::Logger: This is an error information. Standard Console::Logger: This is an error information. Command pattern is a data driven design pattern and falls under behavioral pattern category. A request is wrapped under a object as command and passed to invoker object. Invoker object looks for the appropriate object which can handle this command and pass the command to the corresponding object and that object executes the command. We've created an interface Order which is acting as a command. We've created a Stock class which acts as a request. We've concrete command classes BuyStock and SellStock implementing Order interface which will do actual command processing. A class Broker is created which acts as a invoker object. It can take order and place orders. Broker object uses command pattern to identify which object will execute which command based on type of command. CommandPatternDemo, our demo class will use Broker class to demonstrate command pattern. Create a command interface. Order.java public interface Order { void execute(); } Create a request class. Stock.java public class Stock { private String name = "ABC"; private int quantity = 10; public void buy(){ System.out.println("Stock [ Name: "+name+", Quantity: " + quantity +" ] bought"); } public void sell(){ System.out.println("Stock [ Name: "+name+", Quantity: " + quantity +" ] sold"); } } Create concrete classes implementing the Order interface. BuyStock.java public class BuyStock implements Order { private Stock abcStock; public BuyStock(Stock abcStock){ this.abcStock = abcStock; } public void execute() { abcStock.buy(); } } SellStock.java public class SellStock implements Order { private Stock abcStock; public SellStock(Stock abcStock){ this.abcStock = abcStock; } public void execute() { abcStock.sell(); } } Create command invoker class. Broker.java import java.util.ArrayList; import java.util.List; public class Broker { private List<Order> orderList = new ArrayList<Order>(); public void takeOrder(Order order){ orderList.add(order); } public void placeOrders(){ for (Order order : orderList) { order.execute(); } orderList.clear(); } } Use the Broker class to take and execute commands. CommandPatternDemo.java public class CommandPatternDemo { public static void main(String[] args) { Stock abcStock = new Stock(); BuyStock buyStockOrder = new BuyStock(abcStock); SellStock sellStockOrder = new SellStock(abcStock); Broker broker = new Broker(); broker.takeOrder(buyStockOrder); broker.takeOrder(sellStockOrder); broker.placeOrders(); } } Verify the output. Stock [ Name: ABC, Quantity: 10 ] bought Stock [ Name: ABC, Quantity: 10 ] sold Interpreter pattern provides way to evaluate language grammar or expression. This type of pattern comes under behavioral patterns. This pattern involves implementing a expression interface which tells to interpret a particular context. This pattern is used in SQL parsing, symbol processing engine etc. We're going to create an interface Expression and concrete classes implementing the Expression interface. A class TerminalExpression is defined which acts as a main interpreter of context in question. Other classes OrExpression, AndExpression are used to create combinational expressions. InterpreterPatternDemo, our demo class will use Expression class to create rules and demonstrate parsing of expressions. Create an expression interface. Expression.java public interface Expression { public boolean interpret(String context); } Create concrete classes implementing the above interface. TerminalExpression.java public class TerminalExpression implements Expression { private String data; public TerminalExpression(String data){ this.data = data; } @Override public boolean interpret(String context) { if(context.contains(data)){ return true; } return false; } } OrExpression.java public class OrExpression implements Expression { private Expression expr1 = null; private Expression expr2 = null; public OrExpression(Expression expr1, Expression expr2) { this.expr1 = expr1; this.expr2 = expr2; } @Override public boolean interpret(String context) { return expr1.interpret(context) || expr2.interpret(context); } } AndExpression.java public class AndExpression implements Expression { private Expression expr1 = null; private Expression expr2 = null; public AndExpression(Expression expr1, Expression expr2) { this.expr1 = expr1; this.expr2 = expr2; } @Override public boolean interpret(String context) { return expr1.interpret(context) && expr2.interpret(context); } } InterpreterPatternDemo uses Expression class to create rules and then parse them. InterpreterPatternDemo.java public class InterpreterPatternDemo { //Rule: Robert and John are male public static Expression getMaleExpression(){ Expression robert = new TerminalExpression("Robert"); Expression john = new TerminalExpression("John"); return new OrExpression(robert, john); } //Rule: Julie is a married women public static Expression getMarriedWomanExpression(){ Expression julie = new TerminalExpression("Julie"); Expression married = new TerminalExpression("Married"); return new AndExpression(julie, married); } public static void main(String[] args) { Expression isMale = getMaleExpression(); Expression isMarriedWoman = getMarriedWomanExpression(); System.out.println("John is male? " + isMale.interpret("John")); System.out.println("Julie is a married women? " + isMarriedWoman.interpret("Married Julie")); } } Verify the output. John is male? true Julie is a married women? true Iterator pattern is very commonly used design pattern in Java and .Net programming environment. This pattern is used to get a way to access the elements of a collection object in sequential manner without any need to know its underlying representation. Iterator pattern falls under behavioral pattern category. We're going to create a Iterator interface which narrates navigation method and a Container interface which retruns the iterator . Concrete classes implementing the Container interface will be responsible to implement Iterator interface and use it IteratorPatternDemo, our demo class will use NamesRepository, a concrete class implementation to print a Names stored as a collection in NamesRepository. Create interfaces. Iterator.java public interface Iterator { public boolean hasNext(); public Object next(); } Container.java public interface Container { public Iterator getIterator(); } Create concrete class implementing the Container interface. This class has inner class NameIterator implementing the Iterator interface. NameRepository.java public class NameRepository implements Container { public String names[] = {"Robert" , "John" ,"Julie" , "Lora"}; @Override public Iterator getIterator() { return new NameIterator(); } private class NameIterator implements Iterator { int index; @Override public boolean hasNext() { if(index < names.length){ return true; } return false; } @Override public Object next() { if(this.hasNext()){ return names[index++]; } return null; } } } Use the NameRepository to get iterator and print names. IteratorPatternDemo.java public class IteratorPatternDemo { public static void main(String[] args) { NameRepository namesRepository = new NameRepository(); for(Iterator iter = namesRepository.getIterator(); iter.hasNext();){ String name = (String)iter.next(); System.out.println("Name : " + name); } } } Verify the output. Name : Robert Name : John Name : Julie Name : Lora Mediator pattern is used to reduce communication complexity between multiple objects or classes. This pattern provides a mediator class which normally handles all the communications between different classes and supports easy maintainability of the code by loose coupling. Mediator pattern falls under behavioral pattern category. We're demonstrating mediator pattern by example of a Chat Room where multiple users can send message to Chat Room and it is the responsibility of Chat Room to show the messages to all users. We've created two classes ChatRoom and User. User objects will use ChatRoom method to share their messages. MediatorPatternDemo, our demo class will use User objects to show communication between them. Create mediator class. ChatRoom.java import java.util.Date; public class ChatRoom { public static void showMessage(User user, String message){ System.out.println(new Date().toString() + " [" + user.getName() +"] : " + message); } } Create user class User.java public class User { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public User(String name){ this.name = name; } public void sendMessage(String message){ ChatRoom.showMessage(this,message); } } Use the User object to show communications between them. MediatorPatternDemo.java public class MediatorPatternDemo { public static void main(String[] args) { User robert = new User("Robert"); User john = new User("John"); robert.sendMessage("Hi! John!"); john.sendMessage("Hello! Robert!"); } } Verify the output. Thu Jan 31 16:05:46 IST 2013 [Robert] : Hi! John! Thu Jan 31 16:05:46 IST 2013 [John] : Hello! Robert! Memento pattern is used to reduce where we want to restore state of an object to a previous state. Memento pattern falls under behavioral pattern category. Memento pattern uses three actor classes. Memento contains state of an object to be restored. Originator creates and stores states in Memento objects and Caretaker object which is responsible to restore object state from Memento. We've created classes Memento, Originator and CareTaker. MementoPatternDemo, our demo class will use CareTaker and Originator objects to show restoration of object states. Create Memento class. Memento.java public class Memento { private String state; public Memento(String state){ this.state = state; } public String getState(){ return state; } } Create Originator class Originator.java public class Originator { private String state; public void setState(String state){ this.state = state; } public String getState(){ return state; } public Memento saveStateToMemento(){ return new Memento(state); } public void getStateFromMemento(Memento Memento){ state = memento.getState(); } } Create CareTaker class CareTaker.java import java.util.ArrayList; import java.util.List; public class CareTaker { private List<Memento> mementoList = new ArrayList<Memento>(); public void add(Memento state){ mementoList.add(state); } public Memento get(int index){ return mementoList.get(index); } } Use CareTaker and Originator objects. MementoPatternDemo.java public class MementoPatternDemo { public static void main(String[] args) { Originator originator = new Originator(); CareTaker careTaker = new CareTaker(); originator.setState("State #1"); originator.setState("State #2"); careTaker.add(originator.saveStateToMemento()); originator.setState("State #3"); careTaker.add(originator.saveStateToMemento()); originator.setState("State #4"); System.out.println("Current State: " + originator.getState()); originator.getStateFromMemento(careTaker.get(0)); System.out.println("First saved State: " + originator.getState()); originator.getStateFromMemento(careTaker.get(1)); System.out.println("Second saved State: " + originator.getState()); } } Verify the output. Current State: State #4 First saved State: State #2 Second saved State: State #3 Observer pattern is used when there is one to many relationship between objects such as if one object is modified, its depenedent objects are to be notified automatically. Observer pattern falls under behavioral pattern category. Observer pattern uses three actor classes. Subject, Observer and Client. Subject, an object having methods to attach and de-attach observers to a client object. We've created classes Subject, Observer abstract class and concrete classes extending the abstract class the Observer. ObserverPatternDemo, our demo class will use Subject and concrete class objects to show observer pattern in action. Create Subject class. Subject.java import java.util.ArrayList; import java.util.List; public class Subject { private List<Observer> observers = new ArrayList<Observer>(); private int state; public int getState() { return state; } public void setState(int state) { this.state = state; notifyAllObservers(); } public void attach(Observer observer){ observers.add(observer); } public void notifyAllObservers(){ for (Observer observer : observers) { observer.update(); } } } Create Observer class. Observer.java public abstract class Observer { protected Subject subject; public abstract void update(); } Create concrete observer classes BinaryObserver.java public class BinaryObserver extends Observer{ public BinaryObserver(Subject subject){ this.subject = subject; this.subject.attach(this); } @Override public void update() { System.out.println( "Binary String: " + Integer.toBinaryString( subject.getState() ) ); } } OctalObserver.java public class OctalObserver extends Observer{ public OctalObserver(Subject subject){ this.subject = subject; this.subject.attach(this); } @Override public void update() { System.out.println( "Octal String: " + Integer.toOctalString( subject.getState() ) ); } } HexaObserver.java public class HexaObserver extends Observer{ public HexaObserver(Subject subject){ this.subject = subject; this.subject.attach(this); } @Override public void update() { System.out.println( "Hex String: " + Integer.toHexString( subject.getState() ).toUpperCase() ); } } Use Subject and concrete observer objects. ObserverPatternDemo.java public class ObserverPatternDemo { public static void main(String[] args) { Subject subject = new Subject(); new HexaObserver(subject); new OctalObserver(subject); new BinaryObserver(subject); System.out.println("First state change: 15"); subject.setState(15); System.out.println("Second state change: 10"); subject.setState(10); } } Verify the output. First state change: 15 Hex String: F Octal String: 17 Binary String: 1111 Second state change: 10 Hex String: A Octal String: 12 Binary String: 1010 In State pattern a class behavior changes based on its state. This type of design pattern comes under behavior pattern. In State pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes. We're going to create a State interface defining a action and concrete state classes implementing the State interface. Context is a class which carries a State. StaePatternDemo, our demo class will use Context and state objects to demonstrate change in Context behavior based on type of state it is in. Create an interface. Image.java public interface State { public void doAction(Context context); } Create concrete classes implementing the same interface. StartState.java public class StartState implements State { public void doAction(Context context) { System.out.println("Player is in start state"); context.setState(this); } public String toString(){ return "Start State"; } } StopState.java public class StopState implements State { public void doAction(Context context) { System.out.println("Player is in stop state"); context.setState(this); } public String toString(){ return "Stop State"; } } Create Context Class. Context.java public class Context { private State state; public Context(){ state = null; } public void setState(State state){ this.state = state; } public State getState(){ return state; } } Use the Context to see change in behaviour when State changes. StatePatternDemo.java public class StatePatternDemo { public static void main(String[] args) { Context context = new Context(); StartState startState = new StartState(); startState.doAction(context); System.out.println(context.getState().toString()); StopState stopState = new StopState(); stopState.doAction(context); System.out.println(context.getState().toString()); } } Verify the output. Player is in start state Start State Player is in stop state Stop State In Null Object pattern, a null object replaces check of NULL object instance. Instead of putting if check for a null value, Null Object reflects a do nothing relationship. Such Null object can also be used to provide default behaviour in case data is not available. In Null Object pattern, we create a abstract class specifying the various operations to be done, concreate classes extending this class and a null object class providing do nothing implemention of this class and will be used seemlessly where we need to check null value. We're going to create a AbstractCustomer abstract class defining opearations, here the name of the customer and concrete classes extending the AbstractCustomer class. A factory class CustomerFactory is created to return either RealCustomer or NullCustomer objects based on the name of customer passed to it. NullPatternDemo, our demo class will use CustomerFactory to demonstrate use of Null Object pattern. Create an abstract class. AbstractCustomer.java public abstract class AbstractCustomer { protected String name; public abstract boolean isNil(); public abstract String getName(); } Create concrete classes extending the above class. RealCustomer.java public class RealCustomer extends AbstractCustomer { public RealCustomer(String name) { this.name = name; } @Override public String getName() { return name; } @Override public boolean isNil() { return false; } } NullCustomer.java public class NullCustomer extends AbstractCustomer { @Override public String getName() { return "Not Available in Customer Database"; } @Override public boolean isNil() { return true; } } Create CustomerFactory Class. CustomerFactory.java public class CustomerFactory { public static final String[] names = {"Rob", "Joe", "Julie"}; public static AbstractCustomer getCustomer(String name){ for (int i = 0; i < names.length; i++) { if (names[i].equalsIgnoreCase(name)){ return new RealCustomer(name); } } return new NullCustomer(); } } Use the CustomerFactory get either RealCustomer or NullCustomer objects based on the name of customer passed to it. NullPatternDemo.java public class NullPatternDemo { public static void main(String[] args) { AbstractCustomer customer1 = CustomerFactory.getCustomer("Rob"); AbstractCustomer customer2 = CustomerFactory.getCustomer("Bob"); AbstractCustomer customer3 = CustomerFactory.getCustomer("Julie"); AbstractCustomer customer4 = CustomerFactory.getCustomer("Laura"); System.out.println("Customers"); System.out.println(customer1.getName()); System.out.println(customer2.getName()); System.out.println(customer3.getName()); System.out.println(customer4.getName()); } } Verify the output. Customers Rob Not Available in Customer Database Julie Not Available in Customer Database In Strategy pattern, a class behavior or its algorithm can be changed at run time. This type of design pattern comes under behavior pattern. In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object. The strategy object changes the executing algorithm of the context object. We're going to create a Strategy interface defining a action and concrete strategy classes implementing the Strategy interface. Context is a class which uses a Strategy. StrategyPatternDemo, our demo class will use Context and strategy objects to demonstrate change in Context behaviour based on strategy it deploys or uses. Create an interface. Strategy.java public interface Strategy { public int doOperation(int num1, int num2); } Create concrete classes implementing the same interface. OperationAdd.java public class OperationAdd implements Strategy{ @Override public int doOperation(int num1, int num2) { return num1 + num2; } } OperationSubstract.java public class OperationSubstract implements Strategy{ @Override public int doOperation(int num1, int num2) { return num1 - num2; } } OperationMultiply.java public class OperationMultiply implements Strategy{ @Override public int doOperation(int num1, int num2) { return num1 * num2; } } Create Context Class. Context.java public class Context { private Strategy strategy; public Context(Strategy strategy){ this.strategy = strategy; } public int executeStrategy(int num1, int num2){ return strategy.doOperation(num1, num2); } } Use the Context to see change in behaviour when it changes its Strategy. StatePatternDemo.java public class StrategyPatternDemo { public static void main(String[] args) { Context context = new Context(new OperationAdd()); System.out.println("10 + 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationSubstract()); System.out.println("10 - 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationMultiply()); System.out.println("10 * 5 = " + context.executeStrategy(10, 5)); } } Verify the output. 10 + 5 = 15 10 - 5 = 5 10 * 5 = 50 In Template pattern, an abstract class exposes defined way(s)/template(s) to execute its methods. Its subclasses can overrides the method implementations as per need basis but the invocation is to be in the same way as defined by an abstract class. This pattern comes under behavior pattern category. We're going to create a Game abstract class defining operations with a template method set to be final so that it cannot be overridden. Cricket and Football are concrete classes extend Game and override its methods. TemplatePatternDemo, our demo class will use Game to demonstrate use of template pattern. Create an abstract class with a template method being final. Game.java public abstract class Game { abstract void initialize(); abstract void startPlay(); abstract void endPlay(); //template method public final void play(){ //initialize the game initialize(); //start game startPlay(); //end game endPlay(); } } Create concrete classes extending the above class. Cricket.java public class Cricket extends Game { @Override void endPlay() { System.out.println("Cricket Game Finished!"); } @Override void initialize() { System.out.println("Cricket Game Initialized! Start playing."); } @Override void startPlay() { System.out.println("Cricket Game Started. Enjoy the game!"); } } Football.java public class Football extends Game { @Override void endPlay() { System.out.println("Football Game Finished!"); } @Override void initialize() { System.out.println("Football Game Initialized! Start playing."); } @Override void startPlay() { System.out.println("Football Game Started. Enjoy the game!"); } } Use the Game's template method play() to demonstrate a defined way of playing game. TemplatePatternDemo.java public class TemplatePatternDemo { public static void main(String[] args) { Game game = new Cricket(); game.play(); System.out.println(); game = new Football(); game.play(); } } Verify the output. Cricket Game Initialized! Start playing. Cricket Game Started. Enjoy the game! Cricket Game Finished! Football Game Initialized! Start playing. Football Game Started. Enjoy the game! Football Game Finished! In Visitor pattern, we use a visitor class which changes the executing algorithm of an element class. By this way, execution algorithm of element can varies as visitor varies. This pattern comes under behavior pattern category. As per the pattern, element object has to accept the visitor object so that visitor object handles the operation on the element object. We're going to create a ComputerPart interface defining accept opearation.Keyboard, Mouse, Monitor and Computer are concrete classes implementing ComputerPart interface. We'll define another interface ComputerPartVisitor which will define a visitor class operations. Computer uses concrete visitor to do corresponding action. VisitorPatternDemo, our demo class will use Computer, ComputerPartVisitor classes to demonstrate use of visitor pattern. Define an interface to represent element. ComputerPart.java public interface class ComputerPart { public void accept(ComputerPartVisitor computerPartVisitor); } Create concrete classes extending the above class. Keyboard.java public class Keyboard implements ComputerPart { @Override public void accept(ComputerPartVisitor computerPartVisitor) { computerPartVisitor.visit(this); } } Monitor.java public class Monitor implements ComputerPart { @Override public void accept(ComputerPartVisitor computerPartVisitor) { computerPartVisitor.visit(this); } } Mouse.java public class Mouse implements ComputerPart { @Override public void accept(ComputerPartVisitor computerPartVisitor) { computerPartVisitor.visit(this); } } Computer.java public class Computer implements ComputerPart { ComputerPart[] parts; public Computer(){ parts = new ComputerPart[] {new Mouse(), new Keyboard(), new Monitor()}; } @Override public void accept(ComputerPartVisitor computerPartVisitor) { for (int i = 0; i < parts.length; i++) { parts[i].accept(computerPartVisitor); } computerPartVisitor.visit(this); } } Define an interface to represent visitor. ComputerPartVisitor.java public interface ComputerPartVisitor { public void visit(Computer computer); public void visit(Mouse mouse); public void visit(Keyboard keyboard); public void visit(Monitor monitor); } Create concrete visitor implementing the above class. ComputerPartDisplayVisitor.java public class ComputerPartDisplayVisitor implements ComputerPartVisitor { @Override public void visit(Computer computer) { System.out.println("Displaying Computer."); } @Override public void visit(Mouse mouse) { System.out.println("Displaying Mouse."); } @Override public void visit(Keyboard keyboard) { System.out.println("Displaying Keyboard."); } @Override public void visit(Monitor monitor) { System.out.println("Displaying Monitor."); } } Use the ComputerPartDisplayVisitor to display parts of Computer. VisitorPatternDemo.java public class VisitorPatternDemo { public static void main(String[] args) { ComputerPart computer = new Computer(); computer.accept(new ComputerPartDisplayVisitor()); } } Verify the output. Displaying Mouse. Displaying Keyboard. Displaying Monitor. Displaying Computer. MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate application's concerns. Model - Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data changes. Model - Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data changes. View - View represents the visualization of the data that model contains. View - View represents the visualization of the data that model contains. Controller - Controller acts on both Model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps View and Model separate. Controller - Controller acts on both Model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps View and Model separate. We're going to create a Student object acting as a model.StudentView will be a view class which can print student details on console and StudentController is the controller class responsible to store data in Student object and update view StudentView accordingly. MVCPatternDemo, our demo class will use StudentController to demonstrate use of MVC pattern. Create Model. Student.java public class Student { private String rollNo; private String name; public String getRollNo() { return rollNo; } public void setRollNo(String rollNo) { this.rollNo = rollNo; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Create View. StudentView.java public class StudentView { public void printStudentDetails(String studentName, String studentRollNo){ System.out.println("Student: "); System.out.println("Name: " + studentName); System.out.println("Roll No: " + studentRollNo); } } Create Controller. StudentController.java public class StudentController { private Student model; private StudentView view; public StudentController(Student model, StudentView view){ this.model = model; this.view = view; } public void setStudentName(String name){ model.setName(name); } public String getStudentName(){ return model.getName(); } public void setStudentRollNo(String rollNo){ model.setRollNo(rollNo); } public String getStudentRollNo(){ return model.getRollNo(); } public void updateView(){ view.printStudentDetails(model.getName(), model.getRollNo()); } } Use the StudentController methods to demonstrate MVC design pattern usage. MVCPatternDemo.java public class MVCPatternDemo { public static void main(String[] args) { //fetch student record based on his roll no from the database Student model = retriveStudentFromDatabase(); //Create a view : to write student details on console StudentView view = new StudentView(); StudentController controller = new StudentController(model, view); controller.updateView(); //update model data controller.setStudentName("John"); controller.updateView(); } private static Student retriveStudentFromDatabase(){ Student student = new Student(); student.setName("Robert"); student.setRollNo("10"); return student; } } Verify the output. Student: Name: Robert Roll No: 10 Student: Name: Julie Roll No: 10 Business Delegate Pattern is used to decouple presentation tier and business tier. It is basically use to reduce communication or remote lookup functionality to business tier code in presentation tier code. In business tier we've following entities. Client - Presentation tier code may be JSP, servlet or UI java code. Client - Presentation tier code may be JSP, servlet or UI java code. Business Delegate - A single entry point class for client entities to provide access to Business Service methods. Business Delegate - A single entry point class for client entities to provide access to Business Service methods. LookUp Service - Lookup service object is responsible to get relative business implementation and provide business object access to business delegate object. LookUp Service - Lookup service object is responsible to get relative business implementation and provide business object access to business delegate object. Business Service - Business Service interface. Concrete classes implements this business service to provide actual business implementation logic. Business Service - Business Service interface. Concrete classes implements this business service to provide actual business implementation logic. We're going to create a Client, BusinessDelegate, BusinessService, LookUpService, JMSService and EJBService representing various entities of Business Delegate pattern. BusinessDelegatePatternDemo, our demo class will use BusinessDelegate and Client to demonstrate use of Business Delegate pattern. Create BusinessService Interface. BusinessService.java public interface BusinessService { public void doProcessing(); } Create Concreate Service Classes. EJBService.java public class EJBService implements BusinessService { @Override public void doProcessing() { System.out.println("Processing task by invoking EJB Service"); } } JMSService.java public class JMSService implements BusinessService { @Override public void doProcessing() { System.out.println("Processing task by invoking JMS Service"); } } Create Business Lookup Service. BusinessLookUp.java public class BusinessLookUp { public BusinessService getBusinessService(String serviceType){ if(serviceType.equalsIgnoreCase("EJB")){ return new EJBService(); }else { return new JMSService(); } } } Create Business Delegate. BusinessLookUp.java public class BusinessDelegate { private BusinessLookUp lookupService = new BusinessLookUp(); private BusinessService businessService; private String serviceType; public void setServiceType(String serviceType){ this.serviceType = serviceType; } public void doTask(){ businessService = lookupService.getBusinessService(serviceType); businessService.doProcessing(); } } Create Client. Student.java public class Client { BusinessDelegate businessService; public Client(BusinessDelegate businessService){ this.businessService = businessService; } public void doTask(){ businessService.doTask(); } } Use BusinessDelegate and Client classes to demonstrate Business Delegate pattern. BusinessDelegatePatternDemo.java public class BusinessDelegatePatternDemo { public static void main(String[] args) { BusinessDelegate businessDelegate = new BusinessDelegate(); businessDelegate.setServiceType("EJB"); Client client = new Client(businessDelegate); client.doTask(); businessDelegate.setServiceType("JMS"); client.doTask(); } } Verify the output. Processing task by invoking EJB Service Processing task by invoking JMS Service Composite Entity pattern is used in EJB persistence mechanism. A Composite entity is an EJB entity bean which represents a graph of objects. When a composite entity is updated, internally dependent objects beans get updated automatically as being managed by EJB entity bean. Following are the participants in Composite Entity Bean. Composite Entity - It is primary entity bean.It can be coarse grained or can contain a coarse grained object to be used for persistence purpose. Composite Entity - It is primary entity bean.It can be coarse grained or can contain a coarse grained object to be used for persistence purpose. Coarse-Grained Object -This object contains dependent objects. It has its own life cycle and also manages life cycle of dependent objects. Coarse-Grained Object -This object contains dependent objects. It has its own life cycle and also manages life cycle of dependent objects. Dependent Object - Dependent objects is an object which depends on Coarse-Grained object for its persistence lifecycle. Dependent Object - Dependent objects is an object which depends on Coarse-Grained object for its persistence lifecycle. Strategies - Strategies represents how to implement a Composite Entity. Strategies - Strategies represents how to implement a Composite Entity. We're going to create CompositeEntity object acting as CompositeEntity. CoarseGrainedObject will be a class which contains dependent objects. CompositeEntityPatternDemo, our demo class will use Client class to demonstrate use of Composite Entity pattern. Create Dependent Objects. DependentObject1.java public class DependentObject1 { private String data; public void setData(String data){ this.data = data; } public String getData(){ return data; } } DependentObject2.java public class DependentObject2 { private String data; public void setData(String data){ this.data = data; } public String getData(){ return data; } } Create Coarse Grained Object. CoarseGrainedObject.java public class CoarseGrainedObject { DependentObject1 do1 = new DependentObject1(); DependentObject2 do2 = new DependentObject2(); public void setData(String data1, String data2){ do1.setData(data1); do2.setData(data2); } public String[] getData(){ return new String[] {do1.getData(),do2.getData()}; } } Create Composite Entity. CompositeEntity.java public class CompositeEntity { private CoarseGrainedObject cgo = new CoarseGrainedObject(); public void setData(String data1, String data2){ cgo.setData(data1, data2); } public String[] getData(){ return cgo.getData(); } } Create Client class to use Composite Entity. Client.java public class Client { private CompositeEntity compositeEntity = new CompositeEntity(); public void printData(){ for (int i = 0; i < compositeEntity.getData().length; i++) { System.out.println("Data: " + compositeEntity.getData()[i]); } } public void setData(String data1, String data2){ compositeEntity.setData(data1, data2); } } Use the Client to demonstrate Composite Entity design pattern usage. CompositeEntityPatternDemo.java public class CompositeEntityPatternDemo { public static void main(String[] args) { Client client = new Client(); client.setData("Test", "Data"); client.printData(); client.setData("Second Test", "Data1"); client.printData(); } } Verify the output. Data: Test Data: Data Data: Second Test Data: Data1 Data Access Object Pattern or DAO pattern is used to separate low level data accessing API or operations from high level business services. Following are the participants in Data Access Object Pattern. Data Access Object Interface - This interface defines the standard operations to be performed on a model object(s). Data Access Object Interface - This interface defines the standard operations to be performed on a model object(s). Data Access Object concrete class -This class implements above interface. This class is responsible to get data from a datasource which can be database / xml or any other storage mechanism. Data Access Object concrete class -This class implements above interface. This class is responsible to get data from a datasource which can be database / xml or any other storage mechanism. Model Object or Value Object - This object is simple POJO containing get/set methods to store data retrieved using DAO class. Model Object or Value Object - This object is simple POJO containing get/set methods to store data retrieved using DAO class. We're going to create a Student object acting as a Model or Value Object.StudentDao is Data Access Object Interface.StudentDaoImpl is concrete class implementing Data Access Object Interface. DaoPatternDemo, our demo class will use StudentDao demonstrate use of Data Access Object pattern. Create Value Object. Student.java public class Student { private String name; private int rollNo; Student(String name, int rollNo){ this.name = name; this.rollNo = rollNo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getRollNo() { return rollNo; } public void setRollNo(int rollNo) { this.rollNo = rollNo; } } Create Data Access Object Interface. StudentDao.java import java.util.List; public interface StudentDao { public List<Student> getAllStudents(); public Student getStudent(int rollNo); public void updateStudent(Student student); public void deleteStudent(Student student); } Create concreate class implementing above interface. StudentDaoImpl.java import java.util.ArrayList; import java.util.List; public class StudentDaoImpl implements StudentDao { //list is working as a database List<Student> students; public StudentDaoImpl(){ students = new ArrayList<Student>(); Student student1 = new Student("Robert",0); Student student2 = new Student("John",1); students.add(student1); students.add(student2); } @Override public void deleteStudent(Student student) { students.remove(student.getRollNo()); System.out.println("Student: Roll No " + student.getRollNo() +", deleted from database"); } //retrive list of students from the database @Override public List<Student> getAllStudents() { return students; } @Override public Student getStudent(int rollNo) { return students.get(rollNo); } @Override public void updateStudent(Student student) { students.get(student.getRollNo()).setName(student.getName()); System.out.println("Student: Roll No " + student.getRollNo() +", updated in the database"); } } Use the StudentDao to demonstrate Data Access Object pattern usage. CompositeEntityPatternDemo.java public class DaoPatternDemo { public static void main(String[] args) { StudentDao studentDao = new StudentDaoImpl(); //print all students for (Student student : studentDao.getAllStudents()) { System.out.println("Student: [RollNo : " +student.getRollNo()+", Name : "+student.getName()+" ]"); } //update student Student student =studentDao.getAllStudents().get(0); student.setName("Michael"); studentDao.updateStudent(student); //get the student studentDao.getStudent(0); System.out.println("Student: [RollNo : " +student.getRollNo()+", Name : "+student.getName()+" ]"); } } Verify the output. Student: [RollNo : 0, Name : Robert ] Student: [RollNo : 1, Name : John ] Student: Roll No 0, updated in the database Student: [RollNo : 0, Name : Michael ] The front controller design pattern is used to provide a centralized request handling mechanism so that all requests will be handled by a single handler. This handler can do the authentication/ authorization/ logging or tracking of request and then pass the requests to corresponding handlers. Following are the entities of this type of design pattern. Front Controller - Single handler for all kind of request coming to the application (either web based/ desktop based). Front Controller - Single handler for all kind of request coming to the application (either web based/ desktop based). Dispatcher - Front Controller may use a dispatcher object which can dispatch the request to corresponding specific handler. Dispatcher - Front Controller may use a dispatcher object which can dispatch the request to corresponding specific handler. View - Views are the object for which the requests are made. View - Views are the object for which the requests are made. We're going to create a FrontController,Dispatcher to act as Front Controller and Dispatcher correspondingly. HomeView and StudentView represent various views for which requests can come to front controller. FrontControllerPatternDemo, our demo class will use FrontController ato demonstrate Front Controller Design Pattern. Create Views. HomeView.java public class HomeView { public void show(){ System.out.println("Displaying Home Page"); } } StudentView.java public class StudentView { public void show(){ System.out.println("Displaying Student Page"); } } Create Dispatcher. Dispatcher.java public class Dispatcher { private StudentView studentView; private HomeView homeView; public Dispatcher(){ studentView = new StudentView(); homeView = new HomeView(); } public void dispatch(String request){ if(request.equalsIgnoreCase("STUDENT")){ studentView.show(); }else{ homeView.show(); } } } Create FrontController Context.java public class FrontController { private Dispatcher dispatcher; public FrontController(){ dispatcher = new Dispatcher(); } private boolean isAuthenticUser(){ System.out.println("User is authenticated successfully."); return true; } private void trackRequest(String request){ System.out.println("Page requested: " + request); } public void dispatchRequest(String request){ //log each request trackRequest(request); //authenticate the user if(isAuthenticUser()){ dispatcher.dispatch(request); } } } Use the FrontController to demonstrate Front Controller Design Pattern. FrontControllerPatternDemo.java public class FrontControllerPatternDemo { public static void main(String[] args) { FrontController frontController = new FrontController(); frontController.dispatchRequest("HOME"); frontController.dispatchRequest("STUDENT"); } } Verify the output. Page requested: HOME User is authenticated successfully. Displaying Home Page Page requested: STUDENT User is authenticated successfully. Displaying Student Page The intercepting filter design pattern is used when we want to do some pre-processing / post-processing with request or response of the application. Filters are defined and applied on the request before passing the request to actual target application. Filters can do the authentication/ authorization/ logging or tracking of request and then pass the requests to corresponding handlers. Following are the entities of this type of design pattern. Filter - Filter which will perform certain task prior or after execution of request by request handler. Filter - Filter which will perform certain task prior or after execution of request by request handler. Filter Chain - Filter Chain carries multiple filters and help to execute them in defined order on target. Filter Chain - Filter Chain carries multiple filters and help to execute them in defined order on target. Target - Target object is the request handler Target - Target object is the request handler Filter Manager - Filter Manager manages the filters and Filter Chain. Filter Manager - Filter Manager manages the filters and Filter Chain. Client - Client is the object who sends request to the Target object. Client - Client is the object who sends request to the Target object. We're going to create a FilterChain,FilterManager, Target, Client as various objects representing our entities.AuthenticationFilter and DebugFilter represents concrete filters. InterceptingFilterDemo, our demo class will use Client to demonstrate Intercepting Filter Design Pattern. Create Filter interface. Filter.java public interface Filter { public void execute(String request); } Create concrete filters. AuthenticationFilter.java public class AuthenticationFilter implements Filter { public void execute(String request){ System.out.println("Authenticating request: " + request); } } DebugFilter.java public class DebugFilter implements Filter { public void execute(String request){ System.out.println("request log: " + request); } } Create Target Target.java public class Target { public void execute(String request){ System.out.println("Executing request: " + request); } } Create Filter Chain FilterChain.java import java.util.ArrayList; import java.util.List; public class FilterChain { private List<Filter> filters = new ArrayList<Filter>(); private Target target; public void addFilter(Filter filter){ filters.add(filter); } public void execute(String request){ for (Filter filter : filters) { filter.execute(request); } target.execute(request); } public void setTarget(Target target){ this.target = target; } } Create Filter Manager FilterManager.java public class FilterManager { FilterChain filterChain; public FilterManager(Target target){ filterChain = new FilterChain(); filterChain.setTarget(target); } public void setFilter(Filter filter){ filterChain.addFilter(filter); } public void filterRequest(String request){ filterChain.execute(request); } } Create Client Client.java public class Client { FilterManager filterManager; public void setFilterManager(FilterManager filterManager){ this.filterManager = filterManager; } public void sendRequest(String request){ filterManager.filterRequest(request); } } Use the Client to demonstrate Intercepting Filter Design Pattern. FrontControllerPatternDemo.java public class InterceptingFilterDemo { public static void main(String[] args) { FilterManager filterManager = new FilterManager(new Target()); filterManager.setFilter(new AuthenticationFilter()); filterManager.setFilter(new DebugFilter()); Client client = new Client(); client.setFilterManager(filterManager); client.sendRequest("HOME"); } } Verify the output. Authenticating request: HOME request log: HOME Executing request: HOME The service locator design pattern is used when we want to locate various services using JNDI lookup. Considering high cost of looking up JNDI for a service, Service Locator pattern makes use of caching technique. For the first time a service is required, Service Locator looks up in JNDI and caches the service object. Further lookup or same service via Service Locator is done in its cache which improves the performance of application to great extent. Following are the entities of this type of design pattern. Service - Actual Service which will process the request. Reference of such service is to be looked upon in JNDI server. Service - Actual Service which will process the request. Reference of such service is to be looked upon in JNDI server. Context / Initial Context -JNDI Context, carries the reference to service used for lookup purpose. Context / Initial Context -JNDI Context, carries the reference to service used for lookup purpose. Service Locator - Service Locator is a single point of contact to get services by JNDI lookup, caching the services. Service Locator - Service Locator is a single point of contact to get services by JNDI lookup, caching the services. Cache - Cache to store references of services to reuse them Cache - Cache to store references of services to reuse them Client - Client is the object who invokes the services via ServiceLocator. Client - Client is the object who invokes the services via ServiceLocator. We're going to create a ServiceLocator,InitialContext, Cache, Service as various objects representing our entities.Service1 and Service2 represents concrete services. ServiceLocatorPatternDemo, our demo class is acting as a client here and will use ServiceLocator to demonstrate Service Locator Design Pattern. Create Service interface. Service.java public interface Service { public String getName(); public void execute(); } Create concrete services. Service1.java public class Service1 implements Service { public void execute(){ System.out.println("Executing Service1"); } @Override public String getName() { return "Service1"; } } Service2.java public class Service2 implements Service { public void execute(){ System.out.println("Executing Service2"); } @Override public String getName() { return "Service2"; } } Create InitialContext for JNDI lookup InitialContext.java public class InitialContext { public Object lookup(String jndiName){ if(jndiName.equalsIgnoreCase("SERVICE1")){ System.out.println("Looking up and creating a new Service1 object"); return new Service1(); }else if (jndiName.equalsIgnoreCase("SERVICE2")){ System.out.println("Looking up and creating a new Service2 object"); return new Service2(); } return null; } } Create Cache Cache.java import java.util.ArrayList; import java.util.List; public class Cache { private List<Service> services; public Cache(){ services = new ArrayList<Service>(); } public Service getService(String serviceName){ for (Service service : services) { if(service.getName().equalsIgnoreCase(serviceName)){ System.out.println("Returning cached "+serviceName+" object"); return service; } } return null; } public void addService(Service newService){ boolean exists = false; for (Service service : services) { if(service.getName().equalsIgnoreCase(newService.getName())){ exists = true; } } if(!exists){ services.add(newService); } } } Create Service Locator ServiceLocator.java public class ServiceLocator { private static Cache cache; static { cache = new Cache(); } public static Service getService(String jndiName){ Service service = cache.getService(jndiName); if(service != null){ return service; } InitialContext context = new InitialContext(); Service service1 = (Service)context.lookup(jndiName); cache.addService(service1); return service1; } } Use the ServiceLocator to demonstrate Service Locator Design Pattern. ServiceLocatorPatternDemo.java public class ServiceLocatorPatternDemo { public static void main(String[] args) { Service service = ServiceLocator.getService("Service1"); service.execute(); service = ServiceLocator.getService("Service2"); service.execute(); service = ServiceLocator.getService("Service1"); service.execute(); service = ServiceLocator.getService("Service2"); service.execute(); } } Verify the output. Looking up and creating a new Service1 object Executing Service1 Looking up and creating a new Service2 object Executing Service2 Returning cached Service1 object Executing Service1 Returning cached Service2 object Executing Service2 The Transfer Object pattern is used when we want to pass data with multiple attributes in one shot from client to server. Transfer object is also known as Value Object. Transfer Object is a simple POJO class having getter/setter methods and is serializable so that it can be transferred over the network. It do not have any behavior. Server Side business class normally fetches data from the database and fills the POJO and send it to the client or pass it by value. For client, transfer object is read-only. Client can create its own transfer object and pass it to server to update values in database in one shot. Following are the entities of this type of design pattern. Business Object - Business Service which fills the Transfer Object with data. Business Object - Business Service which fills the Transfer Object with data. Transfer Object -Simple POJO, having methods to set/get attributes only. Transfer Object -Simple POJO, having methods to set/get attributes only. Client - Client either requests or sends the Transfer Object to Business Object. Client - Client either requests or sends the Transfer Object to Business Object. We're going to create a StudentBO as Business Object,Student as Transfer Object representing our entities. TransferObjectPatternDemo, our demo class is acting as a client here and will use StudentBO and Student to demonstrate Transfer Object Design Pattern. Create Transfer Object. StudentVO.java public class StudentVO { private String name; private int rollNo; StudentVO(String name, int rollNo){ this.name = name; this.rollNo = rollNo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getRollNo() { return rollNo; } public void setRollNo(int rollNo) { this.rollNo = rollNo; } } Create Business Object. StudentBO.java import java.util.ArrayList; import java.util.List; public class StudentBO { //list is working as a database List<StudentVO> students; public StudentBO(){ students = new ArrayList<StudentVO>(); StudentVO student1 = new StudentVO("Robert",0); StudentVO student2 = new StudentVO("John",1); students.add(student1); students.add(student2); } public void deleteStudent(StudentVO student) { students.remove(student.getRollNo()); System.out.println("Student: Roll No " + student.getRollNo() +", deleted from database"); } //retrive list of students from the database public List<StudentVO> getAllStudents() { return students; } public StudentVO getStudent(int rollNo) { return students.get(rollNo); } public void updateStudent(StudentVO student) { students.get(student.getRollNo()).setName(student.getName()); System.out.println("Student: Roll No " + student.getRollNo() +", updated in the database"); } } Use the StudentBO to demonstrate Transfer Object Design Pattern. TransferObjectPatternDemo.java public class TransferObjectPatternDemo { public static void main(String[] args) { StudentBO studentBusinessObject = new StudentBO(); //print all students for (StudentVO student : studentBusinessObject.getAllStudents()) { System.out.println("Student: [RollNo : " +student.getRollNo()+", Name : "+student.getName()+" ]"); } //update student StudentVO student =studentBusinessObject.getAllStudents().get(0); student.setName("Michael"); studentBusinessObject.updateStudent(student); //get the student studentBusinessObject.getStudent(0); System.out.println("Student: [RollNo : " +student.getRollNo()+", Name : "+student.getName()+" ]"); } } Verify the output. Student: [RollNo : 0, Name : Robert ] Student: [RollNo : 1, Name : John ] Student: Roll No 0, updated in the database Student: [RollNo : 0, Name : Michael ] 102 Lectures 10 hours Arnab Chakraborty 30 Lectures 3 hours Arnab Chakraborty 31 Lectures 4 hours Arnab Chakraborty 43 Lectures 1.5 hours Manoj Kumar 7 Lectures 1 hours Zach Miller 54 Lectures 4 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 3085, "s": 2751, "text": "Design patterns represent the best practices used by experienced object-oriented software developers. Design patterns are solutions to general problems that software developers faced during software development.\nThese solutions were obtained by trial and error by numerous software developers over quite a substantial period of time." }, { "code": null, "e": 3327, "s": 3085, "text": "In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson und John Vlissides published a book titled Design Patterns - Elements of Reusable Object-Oriented Software which initiated the concept of Design Pattern in Software development. " }, { "code": null, "e": 3507, "s": 3327, "text": "These authors are collectively known as Gang of Four (GOF). According to these authors design patterns are primarily based on the following principles of object orientated design." }, { "code": null, "e": 3553, "s": 3507, "text": "Program to an interface not an implementation" }, { "code": null, "e": 3599, "s": 3553, "text": "Program to an interface not an implementation" }, { "code": null, "e": 3641, "s": 3599, "text": "Favor object composition over inheritance" }, { "code": null, "e": 3683, "s": 3641, "text": "Favor object composition over inheritance" }, { "code": null, "e": 3745, "s": 3683, "text": "Design Patterns have two main usages in software development." }, { "code": null, "e": 4065, "s": 3745, "text": "Design patterns provide a standard terminology and are specific to particular scenario. For example, a singleton design pattern signifies use of single object so all developers familiar with single design pattern will make use of single object and they can tell each other that program is following a singleton pattern." }, { "code": null, "e": 4321, "s": 4065, "text": "Design patterns have been evolved over a long period of time and they provide best solutions to certain problems faced during software development. Learning these patterns helps un-experienced developers to learn software design in an easy and faster way." }, { "code": null, "e": 4639, "s": 4321, "text": "As per the design pattern reference book Design Patterns - Elements of Reusable Object-Oriented Software , there are 23 design patterns. These patterns can be classified in three categories: Creational, Structural and behavioral patterns. We'll also discuss another category of design patterns: J2EE design patterns.\n" }, { "code": null, "e": 4830, "s": 4639, "text": "Factory pattern is one of the most used design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object." }, { "code": null, "e": 4977, "s": 4830, "text": "In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface." }, { "code": null, "e": 5128, "s": 4977, "text": "We're going to create a Shape interface and concrete classes implementing the Shape interface. A factory class ShapeFactory is defined as a next step." }, { "code": null, "e": 5315, "s": 5128, "text": "FactoryPatternDemo, our demo class will use ShapeFactory to get a Shape object. It will pass information (CIRCLE / RECTANGLE / SQUARE) to ShapeFactory to get the type of object it needs." }, { "code": null, "e": 5336, "s": 5315, "text": "Create an interface." }, { "code": null, "e": 5347, "s": 5336, "text": "Shape.java" }, { "code": null, "e": 5390, "s": 5347, "text": "public interface Shape {\n void draw();\n}" }, { "code": null, "e": 5447, "s": 5390, "text": "Create concrete classes implementing the same interface." }, { "code": null, "e": 5462, "s": 5447, "text": "Rectangle.java" }, { "code": null, "e": 5611, "s": 5462, "text": "public class Rectangle implements Shape {\n\n @Override\n public void draw() {\n System.out.println(\"Inside Rectangle::draw() method.\");\n }\n}" }, { "code": null, "e": 5623, "s": 5611, "text": "Square.java" }, { "code": null, "e": 5766, "s": 5623, "text": "public class Square implements Shape {\n\n @Override\n public void draw() {\n System.out.println(\"Inside Square::draw() method.\");\n }\n}" }, { "code": null, "e": 5778, "s": 5766, "text": "Circle.java" }, { "code": null, "e": 5921, "s": 5778, "text": "public class Circle implements Shape {\n\n @Override\n public void draw() {\n System.out.println(\"Inside Circle::draw() method.\");\n }\n}" }, { "code": null, "e": 6003, "s": 5921, "text": "Create a Factory to generate object of concrete class based on given information." }, { "code": null, "e": 6021, "s": 6003, "text": "ShapeFactory.java" }, { "code": null, "e": 6498, "s": 6021, "text": "public class ShapeFactory {\n\t\n //use getShape method to get object of type shape \n public Shape getShape(String shapeType){\n if(shapeType == null){\n return null;\n }\t\t\n if(shapeType.equalsIgnoreCase(\"CIRCLE\")){\n return new Circle();\n } else if(shapeType.equalsIgnoreCase(\"RECTANGLE\")){\n return new Rectangle();\n } else if(shapeType.equalsIgnoreCase(\"SQUARE\")){\n return new Square();\n }\n return null;\n }\n}" }, { "code": null, "e": 6586, "s": 6498, "text": "Use the Factory to get object of concrete class by passing an information such as type." }, { "code": null, "e": 6610, "s": 6586, "text": "FactoryPatternDemo.java" }, { "code": null, "e": 7269, "s": 6610, "text": "public class FactoryPatternDemo {\n\n public static void main(String[] args) {\n ShapeFactory shapeFactory = new ShapeFactory();\n\n //get an object of Circle and call its draw method.\n Shape shape1 = shapeFactory.getShape(\"CIRCLE\");\n\n //call draw method of Circle\n shape1.draw();\n\n //get an object of Rectangle and call its draw method.\n Shape shape2 = shapeFactory.getShape(\"RECTANGLE\");\n\n //call draw method of Rectangle\n shape2.draw();\n\n //get an object of Square and call its draw method.\n Shape shape3 = shapeFactory.getShape(\"SQUARE\");\n\n //call draw method of square\n shape3.draw();\n }\n}" }, { "code": null, "e": 7288, "s": 7269, "text": "Verify the output." }, { "code": null, "e": 7382, "s": 7288, "text": "Inside Circle::draw() method.\nInside Rectangle::draw() method.\nInside Square::draw() method.\n" }, { "code": null, "e": 7646, "s": 7382, "text": "Abstract Factory patterns work around a super-factory which creates other factories. This factory is also called as factory of factories. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object." }, { "code": null, "e": 7862, "s": 7646, "text": "In Abstract Factory pattern an interface is responsible for creating a factory of related objects without explicitly specifying their classes. Each generated factory can give the objects as per the Factory pattern." }, { "code": null, "e": 8139, "s": 7862, "text": "We are going to create a Shape interface and a concrete class implementing it. We create an abstract factory class AbstractFactory as next step. Factory class ShapeFactory is defined, which extends AbstractFactory. A factory creator/generator class FactoryProducer is created." }, { "code": null, "e": 8356, "s": 8139, "text": "AbstractFactoryPatternDemo, our demo class uses FactoryProducer to get a AbstractFactory object. It will pass information (CIRCLE / RECTANGLE / SQUARE for Shape) to AbstractFactory to get the type of object it needs." }, { "code": null, "e": 8388, "s": 8356, "text": "Create an interface for Shapes." }, { "code": null, "e": 8399, "s": 8388, "text": "Shape.java" }, { "code": null, "e": 8442, "s": 8399, "text": "public interface Shape {\n void draw();\n}" }, { "code": null, "e": 8499, "s": 8442, "text": "Create concrete classes implementing the same interface." }, { "code": null, "e": 8521, "s": 8499, "text": "RoundedRectangle.java" }, { "code": null, "e": 8683, "s": 8521, "text": "public class RoundedRectangle implements Shape {\n @Override\n public void draw() {\n System.out.println(\"Inside RoundedRectangle::draw() method.\");\n }\n}" }, { "code": null, "e": 8702, "s": 8683, "text": "RoundedSquare.java" }, { "code": null, "e": 8858, "s": 8702, "text": "public class RoundedSquare implements Shape {\n @Override\n public void draw() {\n System.out.println(\"Inside RoundedSquare::draw() method.\");\n }\n}" }, { "code": null, "e": 8873, "s": 8858, "text": "Rectangle.java" }, { "code": null, "e": 9021, "s": 8873, "text": "public class Rectangle implements Shape {\n @Override\n public void draw() {\n System.out.println(\"Inside Rectangle::draw() method.\");\n }\n}" }, { "code": null, "e": 9101, "s": 9021, "text": "Create an Abstract class to get factories for Normal and Rounded Shape Objects." }, { "code": null, "e": 9122, "s": 9101, "text": "AbstractFactory.java" }, { "code": null, "e": 9211, "s": 9122, "text": "public abstract class AbstractFactory {\n abstract Shape getShape(String shapeType) ;\n}" }, { "code": null, "e": 9325, "s": 9211, "text": "Create Factory classes extending AbstractFactory to generate object of concrete class based on given information." }, { "code": null, "e": 9343, "s": 9325, "text": "ShapeFactory.java" }, { "code": null, "e": 9669, "s": 9343, "text": "public class ShapeFactory extends AbstractFactory {\n @Override\n public Shape getShape(String shapeType){ \n if(shapeType.equalsIgnoreCase(\"RECTANGLE\")){\n return new Rectangle(); \n }else if(shapeType.equalsIgnoreCase(\"SQUARE\")){\n return new Square();\n }\t \n return null;\n }\n}" }, { "code": null, "e": 9694, "s": 9669, "text": "RoundedShapeFactory.java" }, { "code": null, "e": 10041, "s": 9694, "text": "public class RoundedShapeFactory extends AbstractFactory {\n @Override\n public Shape getShape(String shapeType){ \n if(shapeType.equalsIgnoreCase(\"RECTANGLE\")){\n return new RoundedRectangle(); \n }else if(shapeType.equalsIgnoreCase(\"SQUARE\")){\n return new RoundedSquare();\n }\t \n return null;\n }\n}" }, { "code": null, "e": 10140, "s": 10041, "text": "Create a Factory generator/producer class to get factories by passing an information such as Shape" }, { "code": null, "e": 10161, "s": 10140, "text": "FactoryProducer.java" }, { "code": null, "e": 10392, "s": 10161, "text": "public class FactoryProducer {\n public static AbstractFactory getFactory(boolean rounded){ \n if(rounded){\n return new RoundedShapeFactory(); \n }else{\n return new ShapeFactory();\n }\n }\n}" }, { "code": null, "e": 10525, "s": 10392, "text": "Use the FactoryProducer to get AbstractFactory in order to get factories of concrete classes by passing an information such as type." }, { "code": null, "e": 10557, "s": 10525, "text": "AbstractFactoryPatternDemo.java" }, { "code": null, "e": 11491, "s": 10557, "text": "public class AbstractFactoryPatternDemo {\n public static void main(String[] args) {\n //get shape factory\n AbstractFactory shapeFactory = FactoryProducer.getFactory(false);\n //get an object of Shape Rectangle\n Shape shape1 = shapeFactory.getShape(\"RECTANGLE\");\n //call draw method of Shape Rectangle\n shape1.draw();\n //get an object of Shape Square \n Shape shape2 = shapeFactory.getShape(\"SQUARE\");\n //call draw method of Shape Square\n shape2.draw();\n //get shape factory\n AbstractFactory shapeFactory1 = FactoryProducer.getFactory(true);\n //get an object of Shape Rectangle\n Shape shape3 = shapeFactory1.getShape(\"RECTANGLE\");\n //call draw method of Shape Rectangle\n shape3.draw();\n //get an object of Shape Square \n Shape shape4 = shapeFactory1.getShape(\"SQUARE\");\n //call draw method of Shape Square\n shape4.draw();\n \n }\n}" }, { "code": null, "e": 11510, "s": 11491, "text": "Verify the output." }, { "code": null, "e": 11651, "s": 11510, "text": "Inside Rectangle::draw() method.\nInside Square::draw() method.\nInside RoundedRectangle::draw() method.\nInside RoundedSquare::draw() method.\n" }, { "code": null, "e": 11842, "s": 11651, "text": "Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best way to create an object." }, { "code": null, "e": 12113, "s": 11842, "text": "This pattern involves a single class which is responsible to creates own object while making sure that only single object get created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class." }, { "code": null, "e": 12246, "s": 12113, "text": "We're going to create a SingleObject class. SingleObject class have its constructor as private and have a static instance of itself." }, { "code": null, "e": 12430, "s": 12246, "text": "SingleObject class provides a static method to get its static instance to outside world. SingletonPatternDemo, our demo class will use SingleObject class to get a SingleObject object." }, { "code": null, "e": 12456, "s": 12430, "text": "Create a Singleton Class." }, { "code": null, "e": 12474, "s": 12456, "text": "SingleObject.java" }, { "code": null, "e": 12902, "s": 12474, "text": "public class SingleObject {\n\n //create an object of SingleObject\n private static SingleObject instance = new SingleObject();\n\n //make the constructor private so that this class cannot be\n //instantiated\n private SingleObject(){}\n\n //Get the only object available\n public static SingleObject getInstance(){\n return instance;\n }\n\n public void showMessage(){\n System.out.println(\"Hello World!\");\n }\n}" }, { "code": null, "e": 12948, "s": 12902, "text": "Get the only object from the singleton class." }, { "code": null, "e": 12974, "s": 12948, "text": "SingletonPatternDemo.java" }, { "code": null, "e": 13361, "s": 12974, "text": "public class SingletonPatternDemo {\n public static void main(String[] args) {\n\n //illegal construct\n //Compile Time Error: The constructor SingleObject() is not visible\n //SingleObject object = new SingleObject();\n\n //Get the only object available\n SingleObject object = SingleObject.getInstance();\n\n //show the message\n object.showMessage();\n }\n}" }, { "code": null, "e": 13380, "s": 13361, "text": "Verify the output." }, { "code": null, "e": 13394, "s": 13380, "text": "Hello World!\n" }, { "code": null, "e": 13616, "s": 13394, "text": "Builder pattern builds a complex object using simple objects and using a step by step approach. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object." }, { "code": null, "e": 13716, "s": 13616, "text": "A Builder class builds the final object step by step. This builder is independent of other objects." }, { "code": null, "e": 13992, "s": 13716, "text": "We've considered a business case of fast-food restaurant where a typical meal could be a burger and a cold drink. Burger could be either a Veg Burger or Chicken Burger and will be packed by a wrapper. Cold drink could be either a coke or pepsi and will be packed in a bottle." }, { "code": null, "e": 14337, "s": 13992, "text": "We're going to create an Item interface representing food items such as burgers and cold drinks and concrete classes implementing the Item interface and a Packing interface representing packaging of food items and concrete classes implementing the Packing interface as burger would be packed in wrapper and cold drink would be packed as bottle." }, { "code": null, "e": 14540, "s": 14337, "text": "We then create a Meal class having ArrayList of Item and a MealBuilder to build different types of Meal object by combining Item. BuilderPatternDemo, our demo class will use MealBuilder to build a Meal." }, { "code": null, "e": 14601, "s": 14540, "text": "Create an interface Item representing food item and packing." }, { "code": null, "e": 14611, "s": 14601, "text": "Item.java" }, { "code": null, "e": 14717, "s": 14611, "text": "public interface Item {\n public String name();\n public Packing packing();\n public float price();\t\n}" }, { "code": null, "e": 14730, "s": 14717, "text": "Packing.java" }, { "code": null, "e": 14784, "s": 14730, "text": "public interface Packing {\n public String pack();\n}" }, { "code": null, "e": 14845, "s": 14784, "text": "Create concreate classes implementing the Packing interface." }, { "code": null, "e": 14858, "s": 14845, "text": "Wrapper.java" }, { "code": null, "e": 14971, "s": 14858, "text": "public class Wrapper implements Packing {\n\n @Override\n public String pack() {\n return \"Wrapper\";\n }\n}" }, { "code": null, "e": 14983, "s": 14971, "text": "Bottle.java" }, { "code": null, "e": 15094, "s": 14983, "text": "public class Bottle implements Packing {\n\n @Override\n public String pack() {\n return \"Bottle\";\n }\n}" }, { "code": null, "e": 15185, "s": 15094, "text": "Create abstract classes implementing the item interface providing default functionalities." }, { "code": null, "e": 15197, "s": 15185, "text": "Burger.java" }, { "code": null, "e": 15371, "s": 15197, "text": "public abstract class Burger implements Item {\n\n @Override\n public Packing packing() {\n return new Wrapper();\n }\n\n @Override\n public abstract float price();\n}" }, { "code": null, "e": 15386, "s": 15371, "text": "ColdDrink.java" }, { "code": null, "e": 15553, "s": 15386, "text": "public abstract class ColdDrink implements Item {\n\n\t@Override\n\tpublic Packing packing() {\n return new Bottle();\n\t}\n\n\t@Override\n\tpublic abstract float price();\n}" }, { "code": null, "e": 15616, "s": 15553, "text": "Create concrete classes extending Burger and ColdDrink classes" }, { "code": null, "e": 15631, "s": 15616, "text": "VegBurger.java" }, { "code": null, "e": 15810, "s": 15631, "text": "public class VegBurger extends Burger {\n\n @Override\n public float price() {\n return 25.0f;\n }\n\n @Override\n public String name() {\n return \"Veg Burger\";\n }\n}" }, { "code": null, "e": 15829, "s": 15810, "text": "ChickenBurger.java" }, { "code": null, "e": 16016, "s": 15829, "text": "public class ChickenBurger extends Burger {\n\n @Override\n public float price() {\n return 50.5f;\n }\n\n @Override\n public String name() {\n return \"Chicken Burger\";\n }\n}" }, { "code": null, "e": 16026, "s": 16016, "text": "Coke.java" }, { "code": null, "e": 16197, "s": 16026, "text": "public class Coke extends ColdDrink {\n\n @Override\n public float price() {\n return 30.0f;\n }\n\n @Override\n public String name() {\n return \"Coke\";\n }\n}" }, { "code": null, "e": 16208, "s": 16197, "text": "Pepsi.java" }, { "code": null, "e": 16381, "s": 16208, "text": "public class Pepsi extends ColdDrink {\n\n @Override\n public float price() {\n return 35.0f;\n }\n\n @Override\n public String name() {\n return \"Pepsi\";\n }\n}" }, { "code": null, "e": 16436, "s": 16381, "text": "Create a Meal class having Item objects defined above." }, { "code": null, "e": 16446, "s": 16436, "text": "Meal.java" }, { "code": null, "e": 17036, "s": 16446, "text": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class Meal {\n private List<Item> items = new ArrayList<Item>();\t\n\n public void addItem(Item item){\n items.add(item);\n }\n\n public float getCost(){\n float cost = 0.0f;\n for (Item item : items) {\n cost += item.price();\n }\t\t\n return cost;\n }\n\n public void showItems(){\n for (Item item : items) {\n System.out.print(\"Item : \"+item.name());\n System.out.print(\", Packing : \"+item.packing().pack());\n System.out.println(\", Price : \"+item.price());\n }\t\t\n }\t\n}" }, { "code": null, "e": 17125, "s": 17036, "text": "Create a MealBuilder class, the actual builder class responsible to create Meal objects." }, { "code": null, "e": 17142, "s": 17125, "text": "MealBuilder.java" }, { "code": null, "e": 17498, "s": 17142, "text": "public class MealBuilder {\n\n public Meal prepareVegMeal (){\n Meal meal = new Meal();\n meal.addItem(new VegBurger());\n meal.addItem(new Coke());\n return meal;\n } \n\n public Meal prepareNonVegMeal (){\n Meal meal = new Meal();\n meal.addItem(new ChickenBurger());\n meal.addItem(new Pepsi());\n return meal;\n }\n}" }, { "code": null, "e": 17564, "s": 17498, "text": "BuiderPatternDemo uses MealBuider to demonstrate builder pattern." }, { "code": null, "e": 17588, "s": 17564, "text": "BuilderPatternDemo.java" }, { "code": null, "e": 18100, "s": 17588, "text": "public class BuilderPatternDemo {\n public static void main(String[] args) {\n MealBuilder mealBuilder = new MealBuilder();\n\n Meal vegMeal = mealBuilder.prepareVegMeal();\n System.out.println(\"Veg Meal\");\n vegMeal.showItems();\n System.out.println(\"Total Cost: \" +vegMeal.getCost());\n\n Meal nonVegMeal = mealBuilder.prepareNonVegMeal();\n System.out.println(\"\\n\\nNon-Veg Meal\");\n nonVegMeal.showItems();\n System.out.println(\"Total Cost: \" +nonVegMeal.getCost());\n }\n}" }, { "code": null, "e": 18119, "s": 18100, "text": "Verify the output." }, { "code": null, "e": 18372, "s": 18119, "text": "Veg Meal\nItem : Veg Burger, Packing : Wrapper, Price : 25.0\nItem : Coke, Packing : Bottle, Price : 30.0\nTotal Cost: 55.0\n\nNon-Veg Meal\nItem : Chicken Burger, Packing : Wrapper, Price : 50.5\nItem : Pepsi, Packing : Bottle, Price : 35.0\nTotal Cost: 85.5\n" }, { "code": null, "e": 18586, "s": 18372, "text": "Prototype pattern refers to creating duplicate object while keeping performance in mind. This type of design pattern comes under creational pattern as this pattern provides one of the best way to create an object." }, { "code": null, "e": 18970, "s": 18586, "text": "This pattern involves implementing a prototype interface which tells to create a clone of the current object. This pattern is used when creation of object directly is costly. For example, a object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database as as and when needed thus reducing database calls." }, { "code": null, "e": 19192, "s": 18970, "text": "We're going to create an abstract class Shape and concrete classes extending the Shape class. A class ShapeCache is defined as a next step which stores shape objects in a Hashtable and returns their clone when requested." }, { "code": null, "e": 19277, "s": 19192, "text": "PrototypPatternDemo, our demo class will use ShapeCache class to get a Shape object." }, { "code": null, "e": 19335, "s": 19277, "text": "Create an abstract class implementing Clonable interface." }, { "code": null, "e": 19346, "s": 19335, "text": "Shape.java" }, { "code": null, "e": 19864, "s": 19346, "text": "public abstract class Shape implements Cloneable {\n \n private String id;\n protected String type;\n \n abstract void draw();\n \n public String getType(){\n return type;\n }\n \n public String getId() {\n return id;\n }\n \n public void setId(String id) {\n this.id = id;\n }\n \n public Object clone() {\n Object clone = null;\n try {\n clone = super.clone();\n } catch (CloneNotSupportedException e) {\n e.printStackTrace();\n }\n return clone;\n }\n}" }, { "code": null, "e": 19915, "s": 19864, "text": "Create concrete classes extending the above class." }, { "code": null, "e": 19930, "s": 19915, "text": "Rectangle.java" }, { "code": null, "e": 20130, "s": 19930, "text": "public class Rectangle extends Shape {\n\n public Rectangle(){\n type = \"Rectangle\";\n }\n\n @Override\n public void draw() {\n System.out.println(\"Inside Rectangle::draw() method.\");\n }\n}" }, { "code": null, "e": 20142, "s": 20130, "text": "Square.java" }, { "code": null, "e": 20330, "s": 20142, "text": "public class Square extends Shape {\n\n public Square(){\n type = \"Square\";\n }\n\n @Override\n public void draw() {\n System.out.println(\"Inside Square::draw() method.\");\n }\n}" }, { "code": null, "e": 20342, "s": 20330, "text": "Circle.java" }, { "code": null, "e": 20530, "s": 20342, "text": "public class Circle extends Shape {\n\n public Circle(){\n type = \"Circle\";\n }\n\n @Override\n public void draw() {\n System.out.println(\"Inside Circle::draw() method.\");\n }\n}" }, { "code": null, "e": 20615, "s": 20530, "text": "Create a class to get concreate classes from database and store them in a Hashtable." }, { "code": null, "e": 20631, "s": 20615, "text": "ShapeCache.java" }, { "code": null, "e": 21444, "s": 20631, "text": "import java.util.Hashtable;\n\npublic class ShapeCache {\n\t\n private static Hashtable<String, Shape> shapeMap \n = new Hashtable<String, Shape>();\n\n public static Shape getShape(String shapeId) {\n Shape cachedShape = shapeMap.get(shapeId);\n return (Shape) cachedShape.clone();\n }\n\n // for each shape run database query and create shape\n // shapeMap.put(shapeKey, shape);\n // for example, we are adding three shapes\n public static void loadCache() {\n Circle circle = new Circle();\n circle.setId(\"1\");\n shapeMap.put(circle.getId(),circle);\n\n Square square = new Square();\n square.setId(\"2\");\n shapeMap.put(square.getId(),square);\n\n Rectangle rectangle = new Rectangle();\n rectangle.setId(\"3\");\n shapeMap.put(rectangle.getId(),rectangle);\n }\n}" }, { "code": null, "e": 21535, "s": 21444, "text": "PrototypePatternDemo uses ShapeCache class to get clones of shapes stored in a Hashtable." }, { "code": null, "e": 21561, "s": 21535, "text": "PrototypePatternDemo.java" }, { "code": null, "e": 22057, "s": 21561, "text": "public class PrototypePatternDemo {\n public static void main(String[] args) {\n ShapeCache.loadCache();\n\n Shape clonedShape = (Shape) ShapeCache.getShape(\"1\");\n System.out.println(\"Shape : \" + clonedShape.getType());\t\t\n\n Shape clonedShape2 = (Shape) ShapeCache.getShape(\"2\");\n System.out.println(\"Shape : \" + clonedShape2.getType());\t\t\n\n Shape clonedShape3 = (Shape) ShapeCache.getShape(\"3\");\n System.out.println(\"Shape : \" + clonedShape3.getType());\t\t\n }\n}" }, { "code": null, "e": 22076, "s": 22057, "text": "Verify the output." }, { "code": null, "e": 22125, "s": 22076, "text": "Shape : Circle\nShape : Square\nShape : Rectangle\n" }, { "code": null, "e": 22327, "s": 22125, "text": "Adapter pattern works as a bridge between two incompatible interfaces. This type of design pattern comes under structural pattern as this pattern combines the capability of two independent interfaces." }, { "code": null, "e": 22683, "s": 22327, "text": "This pattern involves a single class which is responsible to join functionalities of independent or incompatible interfaces. A real life example could be a case of card reader which acts as an adapter between memory card and a laptop. You plugins the memory card into card reader and card reader into the laptop so that memory card can be read via laptop." }, { "code": null, "e": 22886, "s": 22683, "text": "We are demonstrating use of Adapter pattern via following example in which an audio player device can play mp3 files only and wants to use an advanced audio player capable of playing vlc and mp4 files. " }, { "code": null, "e": 23056, "s": 22886, "text": "We've an interface MediaPlayer interface and a concrete class AudioPlayer implementing the MediaPlayer interface. AudioPlayer can play mp3 format audio files by default." }, { "code": null, "e": 23224, "s": 23056, "text": "We're having another interface AdvancedMediaPlayer and concrete classes implementing the AdvancedMediaPlayer interface.These classes can play vlc and mp4 format files." }, { "code": null, "e": 23452, "s": 23224, "text": "We want to make AudioPlayer to play other formats as well. To attain this, we've created an adapter class MediaAdapter which implements the MediaPlayer interface and uses AdvancedMediaPlayer objects to play the required format." }, { "code": null, "e": 23689, "s": 23452, "text": "AudioPlayer uses the adapter class MediaAdapter passing it the desired audio type without knowing the actual class which can play the desired format. AdapterPatternDemo, our demo class will use AudioPlayer class to play various formats." }, { "code": null, "e": 23751, "s": 23689, "text": "Create interfaces for Media Player and Advanced Media Player." }, { "code": null, "e": 23768, "s": 23751, "text": "MediaPlayer.java" }, { "code": null, "e": 23857, "s": 23768, "text": "public interface MediaPlayer {\n public void play(String audioType, String fileName);\n}" }, { "code": null, "e": 23882, "s": 23857, "text": "AdvancedMediaPlayer.java" }, { "code": null, "e": 24006, "s": 23882, "text": "public interface AdvancedMediaPlayer {\t\n public void playVlc(String fileName);\n public void playMp4(String fileName);\n}" }, { "code": null, "e": 24078, "s": 24006, "text": "Create concrete classes implementing the AdvancedMediaPlayer interface." }, { "code": null, "e": 24093, "s": 24078, "text": "VlcPlayer.java" }, { "code": null, "e": 24356, "s": 24093, "text": "public class VlcPlayer implements AdvancedMediaPlayer{\n @Override\n public void playVlc(String fileName) {\n System.out.println(\"Playing vlc file. Name: \"+ fileName);\t\t\n }\n\n @Override\n public void playMp4(String fileName) {\n //do nothing\n }\n}" }, { "code": null, "e": 24371, "s": 24356, "text": "Mp4Player.java" }, { "code": null, "e": 24635, "s": 24371, "text": "public class Mp4Player implements AdvancedMediaPlayer{\n\n @Override\n public void playVlc(String fileName) {\n //do nothing\n }\n\n @Override\n public void playMp4(String fileName) {\n System.out.println(\"Playing mp4 file. Name: \"+ fileName);\t\t\n }\n}" }, { "code": null, "e": 24696, "s": 24635, "text": "Create adapter class implementing the MediaPlayer interface." }, { "code": null, "e": 24714, "s": 24696, "text": "MediaAdapter.java" }, { "code": null, "e": 25343, "s": 24714, "text": "public class MediaAdapter implements MediaPlayer {\n\n AdvancedMediaPlayer advancedMusicPlayer;\n\n public MediaAdapter(String audioType){\n if(audioType.equalsIgnoreCase(\"vlc\") ){\n advancedMusicPlayer = new VlcPlayer();\t\t\t\n } else if (audioType.equalsIgnoreCase(\"mp4\")){\n advancedMusicPlayer = new Mp4Player();\n }\t\n }\n\n @Override\n public void play(String audioType, String fileName) {\n if(audioType.equalsIgnoreCase(\"vlc\")){\n advancedMusicPlayer.playVlc(fileName);\n }else if(audioType.equalsIgnoreCase(\"mp4\")){\n advancedMusicPlayer.playMp4(fileName);\n }\n }\n}" }, { "code": null, "e": 25405, "s": 25343, "text": "Create concrete class implementing the MediaPlayer interface." }, { "code": null, "e": 25422, "s": 25405, "text": "AudioPlayer.java" }, { "code": null, "e": 26152, "s": 25422, "text": "public class AudioPlayer implements MediaPlayer {\n MediaAdapter mediaAdapter; \n\n @Override\n public void play(String audioType, String fileName) {\t\t\n\n //inbuilt support to play mp3 music files\n if(audioType.equalsIgnoreCase(\"mp3\")){\n System.out.println(\"Playing mp3 file. Name: \"+ fileName);\t\t\t\n } \n //mediaAdapter is providing support to play other file formats\n else if(audioType.equalsIgnoreCase(\"vlc\") \n || audioType.equalsIgnoreCase(\"mp4\")){\n mediaAdapter = new MediaAdapter(audioType);\n mediaAdapter.play(audioType, fileName);\n }\n else{\n System.out.println(\"Invalid media. \"+\n audioType + \" format not supported\");\n }\n } \n}" }, { "code": null, "e": 26214, "s": 26152, "text": "Use the AudioPlayer to play different types of audio formats." }, { "code": null, "e": 26238, "s": 26214, "text": "AdapterPatternDemo.java" }, { "code": null, "e": 26573, "s": 26238, "text": "public class AdapterPatternDemo {\n public static void main(String[] args) {\n AudioPlayer audioPlayer = new AudioPlayer();\n\n audioPlayer.play(\"mp3\", \"beyond the horizon.mp3\");\n audioPlayer.play(\"mp4\", \"alone.mp4\");\n audioPlayer.play(\"vlc\", \"far far away.vlc\");\n audioPlayer.play(\"avi\", \"mind me.avi\");\n }\n}" }, { "code": null, "e": 26592, "s": 26573, "text": "Verify the output." }, { "code": null, "e": 26755, "s": 26592, "text": "Playing mp3 file. Name: beyond the horizon.mp3\nPlaying mp4 file. Name: alone.mp4\nPlaying vlc file. Name: far far away.vlc\nInvalid media. avi format not supported\n" }, { "code": null, "e": 27046, "s": 26755, "text": "Bridge is used where we need to decouple an abstraction from its implementation so that the two can vary independently. This type of design pattern comes under structural pattern as this pattern decouples implementation class and abstract class by providing a bridge structure between them." }, { "code": null, "e": 27282, "s": 27046, "text": "This pattern involves an interface which acts as a bridge which makes the functionality of concrete classes independent from interface implementer classes. Both types of classes can be altered structurally without affecting each other." }, { "code": null, "e": 27474, "s": 27282, "text": "We are demonstrating use of Bridge pattern via following example in which a circle can be drawn in different colors using same abstract class method but different bridge implementer classes. " }, { "code": null, "e": 27779, "s": 27474, "text": "We've an interface DrawAPI interface which is acting as a bridge implementer and concrete classes RedCircle, GreenCircle implementing the DrawAPI interface. Shape is an abstract class and will use object of DrawAPI. BridgePatternDemo, our demo class will use Shape class to draw different colored circle." }, { "code": null, "e": 27816, "s": 27779, "text": "Create bridge implementer interface." }, { "code": null, "e": 27829, "s": 27816, "text": "DrawAPI.java" }, { "code": null, "e": 27911, "s": 27829, "text": "public interface DrawAPI {\n public void drawCircle(int radius, int x, int y);\n}" }, { "code": null, "e": 27990, "s": 27911, "text": "Create concrete bridge implementer classes implementing the DrawAPI interface." }, { "code": null, "e": 28005, "s": 27990, "text": "RedCircle.java" }, { "code": null, "e": 28232, "s": 28005, "text": "public class RedCircle implements DrawAPI {\n @Override\n public void drawCircle(int radius, int x, int y) {\n System.out.println(\"Drawing Circle[ color: red, radius: \"\n + radius +\", x: \" +x+\", \"+ y +\"]\");\n }\n}" }, { "code": null, "e": 28249, "s": 28232, "text": "GreenCircle.java" }, { "code": null, "e": 28480, "s": 28249, "text": "public class GreenCircle implements DrawAPI {\n @Override\n public void drawCircle(int radius, int x, int y) {\n System.out.println(\"Drawing Circle[ color: green, radius: \"\n + radius +\", x: \" +x+\", \"+ y +\"]\");\n }\n}" }, { "code": null, "e": 28540, "s": 28480, "text": "Create an abstract class Shape using the DrawAPI interface." }, { "code": null, "e": 28551, "s": 28540, "text": "Shape.java" }, { "code": null, "e": 28718, "s": 28551, "text": "public abstract class Shape {\n protected DrawAPI drawAPI;\n protected Shape(DrawAPI drawAPI){\n this.drawAPI = drawAPI;\n }\n public abstract void draw();\t\n}" }, { "code": null, "e": 28774, "s": 28718, "text": "Create concrete class implementing the Shape interface." }, { "code": null, "e": 28786, "s": 28774, "text": "Circle.java" }, { "code": null, "e": 29079, "s": 28786, "text": "public class Circle extends Shape {\n private int x, y, radius;\n\n public Circle(int x, int y, int radius, DrawAPI drawAPI) {\n super(drawAPI);\n this.x = x; \n this.y = y; \n this.radius = radius;\n }\n\n public void draw() {\n drawAPI.drawCircle(radius,x,y);\n }\n}" }, { "code": null, "e": 29148, "s": 29079, "text": "Use the Shape and DrawAPI classes to draw different colored circles." }, { "code": null, "e": 29171, "s": 29148, "text": "BridgePatternDemo.java" }, { "code": null, "e": 29442, "s": 29171, "text": "public class BridgePatternDemo {\n public static void main(String[] args) {\n Shape redCircle = new Circle(100,100, 10, new RedCircle());\n Shape greenCircle = new Circle(100,100, 10, new GreenCircle());\n\n redCircle.draw();\n greenCircle.draw();\n }\n}" }, { "code": null, "e": 29461, "s": 29442, "text": "Verify the output." }, { "code": null, "e": 29571, "s": 29461, "text": "Drawing Circle[ color: red, radius: 10, x: 100, 100]\nDrawing Circle[ color: green, radius: 10, x: 100, 100]\n" }, { "code": null, "e": 29898, "s": 29571, "text": "Filter pattern or Criteria pattern is a design pattern that enables developers to filter a set of objects, using different criteria, chaining them in a decoupled way through logical operations. This type of design pattern comes under structural pattern as this pattern is combining multiple criteria to obtain single criteria." }, { "code": null, "e": 30183, "s": 29900, "text": "We're going to create a Person object, Criteria interface and concrete classes implementing this interface to filter list of Person objects. CriteriaPatternDemo, our demo class uses Criteria objects to filter List of Person objects based on various criteria and their combinations." }, { "code": null, "e": 30234, "s": 30183, "text": "Create a class on which criteria is to be applied." }, { "code": null, "e": 30246, "s": 30234, "text": "Person.java" }, { "code": null, "e": 30706, "s": 30246, "text": "public class Person {\n\t\n private String name;\n private String gender;\n private String maritalStatus;\n\n public Person(String name,String gender,String maritalStatus){\n this.name = name;\n this.gender = gender;\n this.maritalStatus = maritalStatus;\t\t\n }\n\n public String getName() {\n return name;\n }\n public String getGender() {\n return gender;\n }\n public String getMaritalStatus() {\n return maritalStatus;\n }\t\n}" }, { "code": null, "e": 30740, "s": 30706, "text": "Create an interface for Criteria." }, { "code": null, "e": 30754, "s": 30740, "text": "Criteria.java" }, { "code": null, "e": 30867, "s": 30754, "text": "import java.util.List;\n\npublic interface Criteria {\n public List<Person> meetCriteria(List<Person> persons);\n}" }, { "code": null, "e": 30928, "s": 30867, "text": "Create concrete classes implementing the Criteria interface." }, { "code": null, "e": 30946, "s": 30928, "text": "CriteriaMale.java" }, { "code": null, "e": 31364, "s": 30946, "text": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class CriteriaMale implements Criteria {\n\n @Override\n public List<Person> meetCriteria(List<Person> persons) {\n List<Person> malePersons = new ArrayList<Person>(); \n for (Person person : persons) {\n if(person.getGender().equalsIgnoreCase(\"MALE\")){\n malePersons.add(person);\n }\n }\n return malePersons;\n }\n}" }, { "code": null, "e": 31384, "s": 31364, "text": "CriteriaFemale.java" }, { "code": null, "e": 31812, "s": 31384, "text": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class CriteriaFemale implements Criteria {\n\n @Override\n public List<Person> meetCriteria(List<Person> persons) {\n List<Person> femalePersons = new ArrayList<Person>(); \n for (Person person : persons) {\n if(person.getGender().equalsIgnoreCase(\"FEMALE\")){\n femalePersons.add(person);\n }\n }\n return femalePersons;\n }\n}" }, { "code": null, "e": 31832, "s": 31812, "text": "CriteriaSingle.java" }, { "code": null, "e": 32267, "s": 31832, "text": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class CriteriaSingle implements Criteria {\n\n @Override\n public List<Person> meetCriteria(List<Person> persons) {\n List<Person> singlePersons = new ArrayList<Person>(); \n for (Person person : persons) {\n if(person.getMaritalStatus().equalsIgnoreCase(\"SINGLE\")){\n singlePersons.add(person);\n }\n }\n return singlePersons;\n }\n}" }, { "code": null, "e": 32284, "s": 32267, "text": "AndCriteria.java" }, { "code": null, "e": 32789, "s": 32284, "text": "import java.util.List;\n\npublic class AndCriteria implements Criteria {\n\n private Criteria criteria;\n private Criteria otherCriteria;\n\n public AndCriteria(Criteria criteria, Criteria otherCriteria) {\n this.criteria = criteria;\n this.otherCriteria = otherCriteria; \n }\n\n @Override\n public List<Person> meetCriteria(List<Person> persons) {\n List<Person> firstCriteriaPersons = criteria.meetCriteria(persons);\t\t\n return otherCriteria.meetCriteria(firstCriteriaPersons);\n }\n}" }, { "code": null, "e": 32805, "s": 32789, "text": "OrCriteria.java" }, { "code": null, "e": 33515, "s": 32805, "text": "import java.util.List;\n\npublic class AndCriteria implements Criteria {\n\n private Criteria criteria;\n private Criteria otherCriteria;\n\n public AndCriteria(Criteria criteria, Criteria otherCriteria) {\n this.criteria = criteria;\n this.otherCriteria = otherCriteria; \n }\n\n @Override\n public List<Person> meetCriteria(List<Person> persons) {\n List<Person> firstCriteriaItems = criteria.meetCriteria(persons);\n List<Person> otherCriteriaItems = otherCriteria.meetCriteria(persons);\n\n for (Person person : otherCriteriaItems) {\n if(!firstCriteriaItems.contains(person)){\n\t firstCriteriaItems.add(person);\n }\n }\t\n return firstCriteriaItems;\n }\n}" }, { "code": null, "e": 33583, "s": 33515, "text": "Use different Criteria and their combination to filter out persons." }, { "code": null, "e": 33608, "s": 33583, "text": "CriteriaPatternDemo.java" }, { "code": null, "e": 35112, "s": 33608, "text": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class CriteriaPatternDemo {\n public static void main(String[] args) {\n List<Person> persons = new ArrayList<Person>();\n\n persons.add(new Person(\"Robert\",\"Male\", \"Single\"));\n persons.add(new Person(\"John\",\"Male\", \"Married\"));\n persons.add(new Person(\"Laura\",\"Female\", \"Married\"));\n persons.add(new Person(\"Diana\",\"Female\", \"Single\"));\n persons.add(new Person(\"Mike\",\"Male\", \"Single\"));\n persons.add(new Person(\"Bobby\",\"Male\", \"Single\"));\n\n Criteria male = new CriteriaMale();\n Criteria female = new CriteriaFemale();\n Criteria single = new CriteriaSingle();\n Criteria singleMale = new AndCriteria(single, male);\n Criteria singleOrFemale = new OrCriteria(single, female);\n\n System.out.println(\"Males: \");\n printPersons(male.meetCriteria(persons));\n\n System.out.println(\"\\nFemales: \");\n printPersons(female.meetCriteria(persons));\n\n System.out.println(\"\\nSingle Males: \");\n printPersons(singleMale.meetCriteria(persons));\n\n System.out.println(\"\\nSingle Or Females: \");\n printPersons(singleOrFemale.meetCriteria(persons));\n }\n\n public static void printPersons(List<Person> persons){\n for (Person person : persons) {\n System.out.println(\"Person : [ Name : \" + person.getName() \n +\", Gender : \" + person.getGender() \n +\", Marital Status : \" + person.getMaritalStatus()\n +\" ]\");\n }\n } \n}" }, { "code": null, "e": 35131, "s": 35112, "text": "Verify the output." }, { "code": null, "e": 36122, "s": 35131, "text": "Males: \nPerson : [ Name : Robert, Gender : Male, Marital Status : Single ]\nPerson : [ Name : John, Gender : Male, Marital Status : Married ]\nPerson : [ Name : Mike, Gender : Male, Marital Status : Single ]\nPerson : [ Name : Bobby, Gender : Male, Marital Status : Single ]\n\nFemales: \nPerson : [ Name : Laura, Gender : Female, Marital Status : Married ]\nPerson : [ Name : Diana, Gender : Female, Marital Status : Single ]\n\nSingle Males: \nPerson : [ Name : Robert, Gender : Male, Marital Status : Single ]\nPerson : [ Name : Mike, Gender : Male, Marital Status : Single ]\nPerson : [ Name : Bobby, Gender : Male, Marital Status : Single ]\n\nSingle Or Females: \nPerson : [ Name : Robert, Gender : Male, Marital Status : Single ]\nPerson : [ Name : Diana, Gender : Female, Marital Status : Single ]\nPerson : [ Name : Mike, Gender : Male, Marital Status : Single ]\nPerson : [ Name : Bobby, Gender : Male, Marital Status : Single ]\nPerson : [ Name : Laura, Gender : Female, Marital Status : Married ]\n" }, { "code": null, "e": 36456, "s": 36122, "text": "Composite pattern is used where we need to treat a group of objects in similar way as a single object. Composite pattern composes objects in term of a tree structure to represent part as well as whole hierarchy . This type of design pattern comes under structural pattern as this pattern creates a tree structure of group of objects." }, { "code": null, "e": 36582, "s": 36456, "text": "This pattern creates a class contains group of its own objects. This class provides ways to modify its group of same objects." }, { "code": null, "e": 36705, "s": 36582, "text": "We are demonstrating use of Composite pattern via following example in which show employees hierarchy of an organization." }, { "code": null, "e": 36893, "s": 36705, "text": "We've a class Employee which acts as composite pattern actor class. CompositePatternDemo, our demo class will use Employee class to add department level hierarchy and print all employees." }, { "code": null, "e": 36948, "s": 36893, "text": "Create Employee class having list of Employee objects." }, { "code": null, "e": 36962, "s": 36948, "text": "Employee.java" }, { "code": null, "e": 37708, "s": 36962, "text": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class Employee {\n private String name;\n private String dept;\n private int salary;\n private List<Employee> subordinates;\n\n // constructor\n public Employee(String name,String dept, int sal) {\n this.name = name;\n this.dept = dept;\n this.salary = sal;\n subordinates = new ArrayList<Employee>();\n }\n\n public void add(Employee e) {\n subordinates.add(e);\n }\n\n public void remove(Employee e) {\n subordinates.remove(e);\n }\n\n public List<Employee> getSubordinates(){\n return subordinates;\n }\n\n public String toString(){\n return (\"Employee :[ Name : \"+ name \n +\", dept : \"+ dept + \", salary :\"\n + salary+\" ]\");\n } \n}" }, { "code": null, "e": 37771, "s": 37708, "text": "Use the Employee class to create and print employee hierarchy." }, { "code": null, "e": 37797, "s": 37771, "text": "CompositePatternDemo.java" }, { "code": null, "e": 38882, "s": 37797, "text": "public class CompositePatternDemo {\n public static void main(String[] args) {\n Employee CEO = new Employee(\"John\",\"CEO\", 30000);\n\n Employee headSales = new Employee(\"Robert\",\"Head Sales\", 20000);\n\n Employee headMarketing = new Employee(\"Michel\",\"Head Marketing\", 20000);\n\n Employee clerk1 = new Employee(\"Laura\",\"Marketing\", 10000);\n Employee clerk2 = new Employee(\"Bob\",\"Marketing\", 10000);\n\n Employee salesExecutive1 = new Employee(\"Richard\",\"Sales\", 10000);\n Employee salesExecutive2 = new Employee(\"Rob\",\"Sales\", 10000);\n\n CEO.add(headSales);\n CEO.add(headMarketing);\n\n headSales.add(salesExecutive1);\n headSales.add(salesExecutive2);\n\n headMarketing.add(clerk1);\n headMarketing.add(clerk2);\n\n //print all employees of the organization\n System.out.println(CEO); \n for (Employee headEmployee : CEO.getSubordinates()) {\n System.out.println(headEmployee);\n for (Employee employee : headEmployee.getSubordinates()) {\n System.out.println(employee);\n }\n }\t\t\n }\n}" }, { "code": null, "e": 38901, "s": 38882, "text": "Verify the output." }, { "code": null, "e": 39313, "s": 38901, "text": "Employee :[ Name : John, dept : CEO, salary :30000 ]\nEmployee :[ Name : Robert, dept : Head Sales, salary :20000 ]\nEmployee :[ Name : Richard, dept : Sales, salary :10000 ]\nEmployee :[ Name : Rob, dept : Sales, salary :10000 ]\nEmployee :[ Name : Michel, dept : Head Marketing, salary :20000 ]\nEmployee :[ Name : Laura, dept : Marketing, salary :10000 ]\nEmployee :[ Name : Bob, dept : Marketing, salary :10000 ]\n" }, { "code": null, "e": 39526, "s": 39313, "text": "Decorator pattern allows to add new functionality an existing object without altering its structure. This type of design pattern comes under structural pattern as this pattern acts as a wrapper to existing class." }, { "code": null, "e": 39674, "s": 39526, "text": "This pattern creates a decorator class which wraps the original class and provides additional functionality keeping class methods signature intact." }, { "code": null, "e": 39817, "s": 39674, "text": "We are demonstrating use of Decorator pattern via following example in which we'll decorate a shape with some color without alter shape class." }, { "code": null, "e": 40052, "s": 39817, "text": "We're going to create a Shape interface and concrete classes implementing the Shape interface. We then create a abstract decorator class ShapeDecorator implementing the Shape interface and having Shape object as its instance variable." }, { "code": null, "e": 40118, "s": 40052, "text": "RedShapeDecorator is concrete class implementing ShapeDecorator. " }, { "code": null, "e": 40210, "s": 40118, "text": "DecoratorPatternDemo, our demo class will use RedShapeDecorator to decorate Shape objects. " }, { "code": null, "e": 40231, "s": 40210, "text": "Create an interface." }, { "code": null, "e": 40242, "s": 40231, "text": "Shape.java" }, { "code": null, "e": 40285, "s": 40242, "text": "public interface Shape {\n void draw();\n}" }, { "code": null, "e": 40342, "s": 40285, "text": "Create concrete classes implementing the same interface." }, { "code": null, "e": 40357, "s": 40342, "text": "Rectangle.java" }, { "code": null, "e": 40490, "s": 40357, "text": "public class Rectangle implements Shape {\n\n @Override\n public void draw() {\n System.out.println(\"Shape: Rectangle\");\n }\n}" }, { "code": null, "e": 40502, "s": 40490, "text": "Circle.java" }, { "code": null, "e": 40629, "s": 40502, "text": "public class Circle implements Shape {\n\n @Override\n public void draw() {\n System.out.println(\"Shape: Circle\");\n }\n}" }, { "code": null, "e": 40695, "s": 40629, "text": "Create abstract decorator class implementing the Shape interface." }, { "code": null, "e": 40715, "s": 40695, "text": "ShapeDecorator.java" }, { "code": null, "e": 40965, "s": 40715, "text": "public abstract class ShapeDecorator implements Shape {\n protected Shape decoratedShape;\n\n public ShapeDecorator(Shape decoratedShape){\n this.decoratedShape = decoratedShape;\n }\n\n public void draw(){\n decoratedShape.draw();\n }\t\n}" }, { "code": null, "e": 41033, "s": 40965, "text": "Create concrete decorator class extending the ShapeDecorator class." }, { "code": null, "e": 41056, "s": 41033, "text": "RedShapeDecorator.java" }, { "code": null, "e": 41424, "s": 41056, "text": "public class RedShapeDecorator extends ShapeDecorator {\n\n public RedShapeDecorator(Shape decoratedShape) {\n super(decoratedShape);\t\t\n }\n\n @Override\n public void draw() {\n decoratedShape.draw();\t \n setRedBorder(decoratedShape);\n }\n\n private void setRedBorder(Shape decoratedShape){\n System.out.println(\"Border Color: Red\");\n }\n}" }, { "code": null, "e": 41477, "s": 41424, "text": "Use the RedShapeDecorator to decorate Shape objects." }, { "code": null, "e": 41503, "s": 41477, "text": "DecoratorPatternDemo.java" }, { "code": null, "e": 41992, "s": 41503, "text": "public class DecoratorPatternDemo {\n public static void main(String[] args) {\n\n Shape circle = new Circle();\n\n Shape redCircle = new RedShapeDecorator(new Circle());\n\n Shape redRectangle = new RedShapeDecorator(new Rectangle());\n System.out.println(\"Circle with normal border\");\n circle.draw();\n\n System.out.println(\"\\nCircle of red border\");\n redCircle.draw();\n\n System.out.println(\"\\nRectangle of red border\");\n redRectangle.draw();\n }\n}" }, { "code": null, "e": 42011, "s": 41992, "text": "Verify the output." }, { "code": null, "e": 42166, "s": 42011, "text": "Circle with normal border\nShape: Circle\n\nCircle of red border\nShape: Circle\nBorder Color: Red\n\nRectangle of red border\nShape: Rectangle\nBorder Color: Red\n" }, { "code": null, "e": 42441, "s": 42166, "text": "Facade pattern hides the complexities of the system and provides an interface to the client using which the client can access the system. This type of design pattern comes under structural pattern as this pattern adds an interface to exiting system to hide its complexities." }, { "code": null, "e": 42597, "s": 42441, "text": "This pattern involves a single class which provides simplified methods which are required by client and delegates calls to existing system classes methods." }, { "code": null, "e": 42745, "s": 42597, "text": "We're going to create a Shape interface and concrete classes implementing the Shape interface. A facade class ShapeMaker is defined as a next step." }, { "code": null, "e": 42911, "s": 42745, "text": "ShapeMaker class uses the concrete classes to delegates user calls to these classes. FacadePatternDemo, our demo class will use ShapeMaker class to show the results." }, { "code": null, "e": 42932, "s": 42911, "text": "Create an interface." }, { "code": null, "e": 42943, "s": 42932, "text": "Shape.java" }, { "code": null, "e": 42986, "s": 42943, "text": "public interface Shape {\n void draw();\n}" }, { "code": null, "e": 43043, "s": 42986, "text": "Create concrete classes implementing the same interface." }, { "code": null, "e": 43058, "s": 43043, "text": "Rectangle.java" }, { "code": null, "e": 43192, "s": 43058, "text": "public class Rectangle implements Shape {\n\n @Override\n public void draw() {\n System.out.println(\"Rectangle::draw()\");\n }\n}" }, { "code": null, "e": 43204, "s": 43192, "text": "Square.java" }, { "code": null, "e": 43332, "s": 43204, "text": "public class Square implements Shape {\n\n @Override\n public void draw() {\n System.out.println(\"Square::draw()\");\n }\n}" }, { "code": null, "e": 43344, "s": 43332, "text": "Circle.java" }, { "code": null, "e": 43472, "s": 43344, "text": "public class Circle implements Shape {\n\n @Override\n public void draw() {\n System.out.println(\"Circle::draw()\");\n }\n}" }, { "code": null, "e": 43495, "s": 43472, "text": "Create a facade class." }, { "code": null, "e": 43511, "s": 43495, "text": "ShapeMaker.java" }, { "code": null, "e": 43913, "s": 43511, "text": "public class ShapeMaker {\n private Shape circle;\n private Shape rectangle;\n private Shape square;\n\n public ShapeMaker() {\n circle = new Circle();\n rectangle = new Rectangle();\n square = new Square();\n }\n\n public void drawCircle(){\n circle.draw();\n }\n public void drawRectangle(){\n rectangle.draw();\n }\n public void drawSquare(){\n square.draw();\n }\n}" }, { "code": null, "e": 43961, "s": 43913, "text": "Use the facade to draw various types of shapes." }, { "code": null, "e": 43984, "s": 43961, "text": "FacadePatternDemo.java" }, { "code": null, "e": 44215, "s": 43984, "text": "public class FacadePatternDemo {\n public static void main(String[] args) {\n ShapeMaker shapeMaker = new ShapeMaker();\n\n shapeMaker.drawCircle();\n shapeMaker.drawRectangle();\n shapeMaker.drawSquare();\t\t\n }\n}" }, { "code": null, "e": 44234, "s": 44215, "text": "Verify the output." }, { "code": null, "e": 44283, "s": 44234, "text": "Circle::draw()\nRectangle::draw()\nSquare::draw()\n" }, { "code": null, "e": 44585, "s": 44283, "text": "Flyweight pattern is primarily used to reduce the number of objects created, to decrease memory footprint and increase performance. This type of design pattern comes under structural pattern as this pattern provides ways to decrease objects count thus improving application required objects structure." }, { "code": null, "e": 44933, "s": 44585, "text": "Flyweight pattern try to reuse already existing similar kind objects by storing them and creates new object when no matching object is found. We'll demonstrate this pattern by drawing 20 circle of different locations but we'll creating only 5 objects. Only 5 colors are available so color property is used to check already existing Circle objects." }, { "code": null, "e": 45089, "s": 44933, "text": "We're going to create a Shape interface and concrete class Circle implementing the Shape interface. A factory class ShapeFactory is defined as a next step." }, { "code": null, "e": 45447, "s": 45089, "text": "ShapeFactory have a HashMap of Circle having key as color of the Circle object. Whenever a request comes to create a circle of particular color to ShapeFactory. ShapeFactory checks the circle object in its HashMap, if object of Circle found, that object is returned otherwise a new object is created, stored in hashmap for future use and returned to client." }, { "code": null, "e": 45651, "s": 45447, "text": "FlyWeightPatternDemo, our demo class will use ShapeFactory to get a Shape object. It will pass information (red / green / blue/ black / white) to ShapeFactory to get the circle of desired color it needs." }, { "code": null, "e": 45672, "s": 45651, "text": "Create an interface." }, { "code": null, "e": 45683, "s": 45672, "text": "Shape.java" }, { "code": null, "e": 45726, "s": 45683, "text": "public interface Shape {\n void draw();\n}" }, { "code": null, "e": 45781, "s": 45726, "text": "Create concrete class implementing the same interface." }, { "code": null, "e": 45793, "s": 45781, "text": "Circle.java" }, { "code": null, "e": 46328, "s": 45793, "text": "public class Circle implements Shape {\n private String color;\n private int x;\n private int y;\n private int radius;\n\n public Circle(String color){\n this.color = color;\t\t\n }\n\n public void setX(int x) {\n this.x = x;\n }\n\n public void setY(int y) {\n this.y = y;\n }\n\n public void setRadius(int radius) {\n this.radius = radius;\n }\n\n @Override\n public void draw() {\n System.out.println(\"Circle: Draw() [Color : \" + color \n +\", x : \" + x +\", y :\" + y +\", radius :\" + radius);\n }\n}" }, { "code": null, "e": 46410, "s": 46328, "text": "Create a Factory to generate object of concrete class based on given information." }, { "code": null, "e": 46428, "s": 46410, "text": "ShapeFactory.java" }, { "code": null, "e": 46980, "s": 46428, "text": "import java.util.HashMap;\n\npublic class ShapeFactory {\n\n // Uncomment the compiler directive line and\n // javac *.java will compile properly.\n // @SuppressWarnings(\"unchecked\")\n private static final HashMap circleMap = new HashMap();\n\n public static Shape getCircle(String color) {\n Circle circle = (Circle)circleMap.get(color);\n\n if(circle == null) {\n circle = new Circle(color);\n circleMap.put(color, circle);\n System.out.println(\"Creating circle of color : \" + color);\n }\n return circle;\n }\n}" }, { "code": null, "e": 47069, "s": 46980, "text": "Use the Factory to get object of concrete class by passing an information such as color." }, { "code": null, "e": 47095, "s": 47069, "text": "FlyweightPatternDemo.java" }, { "code": null, "e": 47805, "s": 47095, "text": "public class FlyweightPatternDemo {\n private static final String colors[] = \n { \"Red\", \"Green\", \"Blue\", \"White\", \"Black\" };\n public static void main(String[] args) {\n\n for(int i=0; i < 20; ++i) {\n Circle circle = \n (Circle)ShapeFactory.getCircle(getRandomColor());\n circle.setX(getRandomX());\n circle.setY(getRandomY());\n circle.setRadius(100);\n circle.draw();\n }\n }\n private static String getRandomColor() {\n return colors[(int)(Math.random()*colors.length)];\n }\n private static int getRandomX() {\n return (int)(Math.random()*100 );\n }\n private static int getRandomY() {\n return (int)(Math.random()*100);\n }\n}" }, { "code": null, "e": 47824, "s": 47805, "text": "Verify the output." }, { "code": null, "e": 49135, "s": 47824, "text": "Creating circle of color : Black\nCircle: Draw() [Color : Black, x : 36, y :71, radius :100\nCreating circle of color : Green\nCircle: Draw() [Color : Green, x : 27, y :27, radius :100\nCreating circle of color : White\nCircle: Draw() [Color : White, x : 64, y :10, radius :100\nCreating circle of color : Red\nCircle: Draw() [Color : Red, x : 15, y :44, radius :100\nCircle: Draw() [Color : Green, x : 19, y :10, radius :100\nCircle: Draw() [Color : Green, x : 94, y :32, radius :100\nCircle: Draw() [Color : White, x : 69, y :98, radius :100\nCreating circle of color : Blue\nCircle: Draw() [Color : Blue, x : 13, y :4, radius :100\nCircle: Draw() [Color : Green, x : 21, y :21, radius :100\nCircle: Draw() [Color : Blue, x : 55, y :86, radius :100\nCircle: Draw() [Color : White, x : 90, y :70, radius :100\nCircle: Draw() [Color : Green, x : 78, y :3, radius :100\nCircle: Draw() [Color : Green, x : 64, y :89, radius :100\nCircle: Draw() [Color : Blue, x : 3, y :91, radius :100\nCircle: Draw() [Color : Blue, x : 62, y :82, radius :100\nCircle: Draw() [Color : Green, x : 97, y :61, radius :100\nCircle: Draw() [Color : Green, x : 86, y :12, radius :100\nCircle: Draw() [Color : Green, x : 38, y :93, radius :100\nCircle: Draw() [Color : Red, x : 76, y :82, radius :100\nCircle: Draw() [Color : Blue, x : 95, y :82, radius :100\n" }, { "code": null, "e": 49264, "s": 49135, "text": "In Proxy pattern, a class represents functionality of another class. This type of design pattern comes under structural pattern." }, { "code": null, "e": 49369, "s": 49264, "text": "In Proxy pattern, we create object having original object to interface its functionality to outer world." }, { "code": null, "e": 49550, "s": 49369, "text": "We're going to create a Image interface and concrete classes implementing the Image interface. ProxyImage is a a proxy class to reduce memory footprint of RealImage object loading." }, { "code": null, "e": 49658, "s": 49550, "text": "ProxyPatternDemo, our demo class will use ProxyImage to get a Image object to load and display as it needs." }, { "code": null, "e": 49679, "s": 49658, "text": "Create an interface." }, { "code": null, "e": 49690, "s": 49679, "text": "Image.java" }, { "code": null, "e": 49736, "s": 49690, "text": "public interface Image {\n void display();\n}" }, { "code": null, "e": 49793, "s": 49736, "text": "Create concrete classes implementing the same interface." }, { "code": null, "e": 49808, "s": 49793, "text": "RealImage.java" }, { "code": null, "e": 50187, "s": 49808, "text": "public class RealImage implements Image {\n\n private String fileName;\n\n public RealImage(String fileName){\n this.fileName = fileName;\n loadFromDisk(fileName);\n }\n\n @Override\n public void display() {\n System.out.println(\"Displaying \" + fileName);\n }\n\n private void loadFromDisk(String fileName){\n System.out.println(\"Loading \" + fileName);\n }\n}" }, { "code": null, "e": 50203, "s": 50187, "text": "ProxyImage.java" }, { "code": null, "e": 50541, "s": 50203, "text": "public class ProxyImage implements Image{\n\n private RealImage realImage;\n private String fileName;\n\n public ProxyImage(String fileName){\n this.fileName = fileName;\n }\n\n @Override\n public void display() {\n if(realImage == null){\n realImage = new RealImage(fileName);\n }\n realImage.display();\n }\n}" }, { "code": null, "e": 50608, "s": 50541, "text": "Use the ProxyImage to get object of RealImage class when required." }, { "code": null, "e": 50630, "s": 50608, "text": "ProxyPatternDemo.java" }, { "code": null, "e": 50930, "s": 50630, "text": "public class ProxyPatternDemo {\n\t\n public static void main(String[] args) {\n Image image = new ProxyImage(\"test_10mb.jpg\");\n\n //image will be loaded from disk\n image.display(); \n System.out.println(\"\");\n //image will not be loaded from disk\n image.display(); \t\n }\n}" }, { "code": null, "e": 50949, "s": 50930, "text": "Verify the output." }, { "code": null, "e": 51023, "s": 50949, "text": "Loading test_10mb.jpg\nDisplaying test_10mb.jpg\n\nDisplaying test_10mb.jpg\n" }, { "code": null, "e": 51261, "s": 51023, "text": "As the name suggest, the chain of responsibility pattern creates a chain of receiver objects for a request. This pattern decouples sender and receiver of a request based on type of request. This pattern comes under behavioral patterns. " }, { "code": null, "e": 51439, "s": 51263, "text": "In this pattern, normally each receiver contains reference to another receiver. If one object cannot handle the request then it passes the same to the next receiver and so on." }, { "code": null, "e": 51724, "s": 51439, "text": "We've created an abstract class AbstractLogger with a level of logging. Then we've created three types of loggers extending the AbstractLogger. Each logger checks the level of message to its level and print accordingly otherwise does not print and pass the message to its next logger." }, { "code": null, "e": 51757, "s": 51724, "text": "Create an abstract logger class." }, { "code": null, "e": 51777, "s": 51757, "text": "AbstractLogger.java" }, { "code": null, "e": 52385, "s": 51777, "text": "public abstract class AbstractLogger {\n public static int INFO = 1;\n public static int DEBUG = 2;\n public static int ERROR = 3;\n\n protected int level;\n\n //next element in chain or responsibility\n protected AbstractLogger nextLogger;\n\n public void setNextLogger(AbstractLogger nextLogger){\n this.nextLogger = nextLogger;\n }\n\n public void logMessage(int level, String message){\n if(this.level <= level){\n write(message);\n }\n if(nextLogger !=null){\n nextLogger.logMessage(level, message);\n }\n }\n\n abstract protected void write(String message);\n\t\n}" }, { "code": null, "e": 52431, "s": 52385, "text": "Create concrete classes extending the logger." }, { "code": null, "e": 52450, "s": 52431, "text": "ConsoleLogger.java" }, { "code": null, "e": 52701, "s": 52450, "text": "public class ConsoleLogger extends AbstractLogger {\n\n public ConsoleLogger(int level){\n this.level = level;\n }\n\n @Override\n protected void write(String message) {\t\t\n System.out.println(\"Standard Console::Logger: \" + message);\n }\n}" }, { "code": null, "e": 52718, "s": 52701, "text": "ErrorLogger.java" }, { "code": null, "e": 52962, "s": 52718, "text": "public class ErrorLogger extends AbstractLogger {\n\n public ErrorLogger(int level){\n this.level = level;\n }\n\n @Override\n protected void write(String message) {\t\t\n System.out.println(\"Error Console::Logger: \" + message);\n }\n}" }, { "code": null, "e": 52978, "s": 52962, "text": "FileLogger.java" }, { "code": null, "e": 53211, "s": 52978, "text": "public class FileLogger extends AbstractLogger {\n\n public FileLogger(int level){\n this.level = level;\n }\n\n @Override\n protected void write(String message) {\t\t\n System.out.println(\"File::Logger: \" + message);\n }\n}" }, { "code": null, "e": 53368, "s": 53211, "text": "Create different types of loggers. Assign them error levels and set next logger in each logger. Next logger in each logger represents the part of the chain." }, { "code": null, "e": 53390, "s": 53368, "text": "ChainPatternDemo.java" }, { "code": null, "e": 54223, "s": 53390, "text": "public class ChainPatternDemo {\n\t\n private static AbstractLogger getChainOfLoggers(){\n\n AbstractLogger errorLogger = new ErrorLogger(AbstractLogger.ERROR);\n AbstractLogger fileLogger = new FileLogger(AbstractLogger.DEBUG);\n AbstractLogger consoleLogger = new ConsoleLogger(AbstractLogger.INFO);\n\n errorLogger.setNextLogger(fileLogger);\n fileLogger.setNextLogger(consoleLogger);\n\n return errorLogger;\t\n }\n\n public static void main(String[] args) {\n AbstractLogger loggerChain = getChainOfLoggers();\n\n loggerChain.logMessage(AbstractLogger.INFO, \n \"This is an information.\");\n\n loggerChain.logMessage(AbstractLogger.DEBUG, \n \"This is an debug level information.\");\n\n loggerChain.logMessage(AbstractLogger.ERROR, \n \"This is an error information.\");\n }\n}" }, { "code": null, "e": 54242, "s": 54223, "text": "Verify the output." }, { "code": null, "e": 54558, "s": 54242, "text": "Standard Console::Logger: This is an information.\nFile::Logger: This is an debug level information.\nStandard Console::Logger: This is an debug level information.\nError Console::Logger: This is an error information.\nFile::Logger: This is an error information.\nStandard Console::Logger: This is an error information.\n" }, { "code": null, "e": 54895, "s": 54558, "text": "Command pattern is a data driven design pattern and falls under behavioral pattern category. A request is wrapped under a object as command and passed to invoker object. Invoker object looks for the appropriate object which can handle this command and pass the command to the corresponding object and that object executes the command. " }, { "code": null, "e": 55231, "s": 54897, "text": "We've created an interface Order which is acting as a command. We've created a Stock class which acts as a request. We've concrete command classes BuyStock and SellStock implementing Order interface which will do actual command processing. A class Broker is created which acts as a invoker object. It can take order and place orders." }, { "code": null, "e": 55433, "s": 55231, "text": "Broker object uses command pattern to identify which object will execute which command based on type of command. CommandPatternDemo, our demo class will use Broker class to demonstrate command pattern." }, { "code": null, "e": 55461, "s": 55433, "text": "Create a command interface." }, { "code": null, "e": 55472, "s": 55461, "text": "Order.java" }, { "code": null, "e": 55518, "s": 55472, "text": "public interface Order {\n void execute();\n}" }, { "code": null, "e": 55542, "s": 55518, "text": "Create a request class." }, { "code": null, "e": 55553, "s": 55542, "text": "Stock.java" }, { "code": null, "e": 55890, "s": 55553, "text": "public class Stock {\n\t\n private String name = \"ABC\";\n private int quantity = 10;\n\n public void buy(){\n System.out.println(\"Stock [ Name: \"+name+\", \n Quantity: \" + quantity +\" ] bought\");\n }\n public void sell(){\n System.out.println(\"Stock [ Name: \"+name+\", \n Quantity: \" + quantity +\" ] sold\");\n }\n}" }, { "code": null, "e": 55948, "s": 55890, "text": "Create concrete classes implementing the Order interface." }, { "code": null, "e": 55962, "s": 55948, "text": "BuyStock.java" }, { "code": null, "e": 56161, "s": 55962, "text": "public class BuyStock implements Order {\n private Stock abcStock;\n\n public BuyStock(Stock abcStock){\n this.abcStock = abcStock;\n }\n\n public void execute() {\n abcStock.buy();\n }\n}" }, { "code": null, "e": 56176, "s": 56161, "text": "SellStock.java" }, { "code": null, "e": 56378, "s": 56176, "text": "public class SellStock implements Order {\n private Stock abcStock;\n\n public SellStock(Stock abcStock){\n this.abcStock = abcStock;\n }\n\n public void execute() {\n abcStock.sell();\n }\n}" }, { "code": null, "e": 56408, "s": 56378, "text": "Create command invoker class." }, { "code": null, "e": 56420, "s": 56408, "text": "Broker.java" }, { "code": null, "e": 56767, "s": 56420, "text": "import java.util.ArrayList;\nimport java.util.List;\n\n public class Broker {\n private List<Order> orderList = new ArrayList<Order>(); \n\n public void takeOrder(Order order){\n orderList.add(order);\t\t\n }\n\n public void placeOrders(){\n for (Order order : orderList) {\n order.execute();\n }\n orderList.clear();\n }\n}" }, { "code": null, "e": 56818, "s": 56767, "text": "Use the Broker class to take and execute commands." }, { "code": null, "e": 56842, "s": 56818, "text": "CommandPatternDemo.java" }, { "code": null, "e": 57222, "s": 56842, "text": "public class CommandPatternDemo {\n public static void main(String[] args) {\n Stock abcStock = new Stock();\n\n BuyStock buyStockOrder = new BuyStock(abcStock);\n SellStock sellStockOrder = new SellStock(abcStock);\n\n Broker broker = new Broker();\n broker.takeOrder(buyStockOrder);\n broker.takeOrder(sellStockOrder);\n\n broker.placeOrders();\n }\n}" }, { "code": null, "e": 57241, "s": 57222, "text": "Verify the output." }, { "code": null, "e": 57322, "s": 57241, "text": "Stock [ Name: ABC, Quantity: 10 ] bought\nStock [ Name: ABC, Quantity: 10 ] sold\n" }, { "code": null, "e": 57625, "s": 57322, "text": "Interpreter pattern provides way to evaluate language grammar or expression. This type of pattern comes under behavioral patterns. This pattern involves implementing a expression interface which tells to interpret a particular context. This pattern is used in SQL parsing, symbol processing engine etc." }, { "code": null, "e": 57916, "s": 57625, "text": "We're going to create an interface Expression and concrete classes implementing the Expression interface. A class TerminalExpression is defined which acts as a main interpreter of context in question. Other classes OrExpression, AndExpression are used to create combinational expressions." }, { "code": null, "e": 58037, "s": 57916, "text": "InterpreterPatternDemo, our demo class will use Expression class to create rules and demonstrate parsing of expressions." }, { "code": null, "e": 58069, "s": 58037, "text": "Create an expression interface." }, { "code": null, "e": 58085, "s": 58069, "text": "Expression.java" }, { "code": null, "e": 58162, "s": 58085, "text": "public interface Expression {\n public boolean interpret(String context);\n}" }, { "code": null, "e": 58220, "s": 58162, "text": "Create concrete classes implementing the above interface." }, { "code": null, "e": 58244, "s": 58220, "text": "TerminalExpression.java" }, { "code": null, "e": 58551, "s": 58244, "text": "public class TerminalExpression implements Expression {\n\t\n private String data;\n\n public TerminalExpression(String data){\n this.data = data; \n }\n\n @Override\n public boolean interpret(String context) {\n if(context.contains(data)){\n return true;\n }\n return false;\n }\n}" }, { "code": null, "e": 58569, "s": 58551, "text": "OrExpression.java" }, { "code": null, "e": 58950, "s": 58569, "text": "public class OrExpression implements Expression {\n\t \n private Expression expr1 = null;\n private Expression expr2 = null;\n\n public OrExpression(Expression expr1, Expression expr2) { \n this.expr1 = expr1;\n this.expr2 = expr2;\n }\n\n @Override\n public boolean interpret(String context) {\t\t\n return expr1.interpret(context) || expr2.interpret(context);\n }\n}" }, { "code": null, "e": 58969, "s": 58950, "text": "AndExpression.java" }, { "code": null, "e": 59352, "s": 58969, "text": "public class AndExpression implements Expression {\n\t \n private Expression expr1 = null;\n private Expression expr2 = null;\n\n public AndExpression(Expression expr1, Expression expr2) { \n this.expr1 = expr1;\n this.expr2 = expr2;\n }\n\n @Override\n public boolean interpret(String context) {\t\t\n return expr1.interpret(context) && expr2.interpret(context);\n }\n}" }, { "code": null, "e": 59434, "s": 59352, "text": "InterpreterPatternDemo uses Expression class to create rules and then parse them." }, { "code": null, "e": 59462, "s": 59434, "text": "InterpreterPatternDemo.java" }, { "code": null, "e": 60364, "s": 59462, "text": "public class InterpreterPatternDemo {\n\n //Rule: Robert and John are male\n public static Expression getMaleExpression(){\n Expression robert = new TerminalExpression(\"Robert\");\n Expression john = new TerminalExpression(\"John\");\n return new OrExpression(robert, john);\t\t\n }\n\n //Rule: Julie is a married women\n public static Expression getMarriedWomanExpression(){\n Expression julie = new TerminalExpression(\"Julie\");\n Expression married = new TerminalExpression(\"Married\");\n return new AndExpression(julie, married);\t\t\n }\n\n public static void main(String[] args) {\n Expression isMale = getMaleExpression();\n Expression isMarriedWoman = getMarriedWomanExpression();\n\n System.out.println(\"John is male? \" + isMale.interpret(\"John\"));\n System.out.println(\"Julie is a married women? \" \n + isMarriedWoman.interpret(\"Married Julie\"));\n }\n}" }, { "code": null, "e": 60383, "s": 60364, "text": "Verify the output." }, { "code": null, "e": 60434, "s": 60383, "text": "John is male? true\nJulie is a married women? true\n" }, { "code": null, "e": 60688, "s": 60434, "text": "Iterator pattern is very commonly used design pattern in Java and .Net programming environment. This pattern is used to get a way to access the elements of a collection object in sequential manner without any need to know its underlying representation. " }, { "code": null, "e": 60746, "s": 60688, "text": "Iterator pattern falls under behavioral pattern category." }, { "code": null, "e": 60995, "s": 60746, "text": "We're going to create a Iterator interface which narrates navigation method and a Container interface which retruns the iterator . Concrete classes implementing the Container interface will be responsible to implement Iterator interface and use it " }, { "code": null, "e": 61149, "s": 60995, "text": "IteratorPatternDemo, our demo class will use NamesRepository, a concrete class implementation to print a Names stored as a collection in NamesRepository." }, { "code": null, "e": 61168, "s": 61149, "text": "Create interfaces." }, { "code": null, "e": 61182, "s": 61168, "text": "Iterator.java" }, { "code": null, "e": 61266, "s": 61182, "text": "public interface Iterator {\n public boolean hasNext();\n public Object next();\n}" }, { "code": null, "e": 61281, "s": 61266, "text": "Container.java" }, { "code": null, "e": 61346, "s": 61281, "text": "public interface Container {\n public Iterator getIterator();\n}" }, { "code": null, "e": 61483, "s": 61346, "text": "Create concrete class implementing the Container interface. This class has inner class NameIterator implementing the Iterator interface." }, { "code": null, "e": 61503, "s": 61483, "text": "NameRepository.java" }, { "code": null, "e": 62090, "s": 61503, "text": "public class NameRepository implements Container {\n public String names[] = {\"Robert\" , \"John\" ,\"Julie\" , \"Lora\"};\n\n @Override\n public Iterator getIterator() {\n return new NameIterator();\n }\n\n private class NameIterator implements Iterator {\n\n int index;\n\n @Override\n public boolean hasNext() {\n if(index < names.length){\n return true;\n }\n return false;\n }\n\n @Override\n public Object next() {\n if(this.hasNext()){\n return names[index++];\n }\n return null;\n }\t\t\n }\n}" }, { "code": null, "e": 62146, "s": 62090, "text": "Use the NameRepository to get iterator and print names." }, { "code": null, "e": 62171, "s": 62146, "text": "IteratorPatternDemo.java" }, { "code": null, "e": 62497, "s": 62171, "text": "public class IteratorPatternDemo {\n\t\n public static void main(String[] args) {\n NameRepository namesRepository = new NameRepository();\n\n for(Iterator iter = namesRepository.getIterator(); iter.hasNext();){\n String name = (String)iter.next();\n System.out.println(\"Name : \" + name);\n } \t\n }\n}" }, { "code": null, "e": 62516, "s": 62497, "text": "Verify the output." }, { "code": null, "e": 62568, "s": 62516, "text": "Name : Robert\nName : John\nName : Julie\nName : Lora\n" }, { "code": null, "e": 62899, "s": 62568, "text": "Mediator pattern is used to reduce communication complexity between multiple objects or classes. This pattern provides a mediator class which normally handles all the communications between different classes and supports easy maintainability of the code by loose coupling. Mediator pattern falls under behavioral pattern category." }, { "code": null, "e": 63198, "s": 62899, "text": "We're demonstrating mediator pattern by example of a Chat Room where multiple users can send message to Chat Room and it is the responsibility of Chat Room to show the messages to all users. We've created two classes ChatRoom and User. User objects will use ChatRoom method to share their messages." }, { "code": null, "e": 63292, "s": 63198, "text": "MediatorPatternDemo, our demo class will use User objects to show communication between them." }, { "code": null, "e": 63315, "s": 63292, "text": "Create mediator class." }, { "code": null, "e": 63329, "s": 63315, "text": "ChatRoom.java" }, { "code": null, "e": 63546, "s": 63329, "text": "import java.util.Date;\n\npublic class ChatRoom {\n public static void showMessage(User user, String message){\n System.out.println(new Date().toString()\n + \" [\" + user.getName() +\"] : \" + message);\n }\n}" }, { "code": null, "e": 63564, "s": 63546, "text": "Create user class" }, { "code": null, "e": 63574, "s": 63564, "text": "User.java" }, { "code": null, "e": 63894, "s": 63574, "text": "public class User {\n private String name;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public User(String name){\n this.name = name;\n }\n\n public void sendMessage(String message){\n ChatRoom.showMessage(this,message);\n }\n}" }, { "code": null, "e": 63951, "s": 63894, "text": "Use the User object to show communications between them." }, { "code": null, "e": 63976, "s": 63951, "text": "MediatorPatternDemo.java" }, { "code": null, "e": 64220, "s": 63976, "text": "public class MediatorPatternDemo {\n public static void main(String[] args) {\n User robert = new User(\"Robert\");\n User john = new User(\"John\");\n\n robert.sendMessage(\"Hi! John!\");\n john.sendMessage(\"Hello! Robert!\");\n }\n}" }, { "code": null, "e": 64239, "s": 64220, "text": "Verify the output." }, { "code": null, "e": 64343, "s": 64239, "text": "Thu Jan 31 16:05:46 IST 2013 [Robert] : Hi! John!\nThu Jan 31 16:05:46 IST 2013 [John] : Hello! Robert!\n" }, { "code": null, "e": 64499, "s": 64343, "text": "Memento pattern is used to reduce where we want to restore state of an object to a previous state. Memento pattern falls under behavioral pattern category." }, { "code": null, "e": 64789, "s": 64499, "text": "Memento pattern uses three actor classes. Memento contains state of an object to be restored. Originator creates and stores states in Memento objects and Caretaker object which is responsible to restore object state from Memento. We've created classes Memento, Originator and CareTaker. \n" }, { "code": null, "e": 64904, "s": 64789, "text": "MementoPatternDemo, our demo class will use CareTaker and Originator objects to show restoration of object states." }, { "code": null, "e": 64926, "s": 64904, "text": "Create Memento class." }, { "code": null, "e": 64939, "s": 64926, "text": "Memento.java" }, { "code": null, "e": 65110, "s": 64939, "text": "public class Memento {\n private String state;\n\n public Memento(String state){\n this.state = state;\n }\n\n public String getState(){\n return state;\n }\t\n}" }, { "code": null, "e": 65134, "s": 65110, "text": "Create Originator class" }, { "code": null, "e": 65150, "s": 65134, "text": "Originator.java" }, { "code": null, "e": 65501, "s": 65150, "text": "public class Originator {\n private String state;\n\n public void setState(String state){\n this.state = state;\n }\n\n public String getState(){\n return state;\n }\n\n public Memento saveStateToMemento(){\n return new Memento(state);\n }\n\n public void getStateFromMemento(Memento Memento){\n state = memento.getState();\n }\n}" }, { "code": null, "e": 65524, "s": 65501, "text": "Create CareTaker class" }, { "code": null, "e": 65539, "s": 65524, "text": "CareTaker.java" }, { "code": null, "e": 65831, "s": 65539, "text": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class CareTaker {\n private List<Memento> mementoList = new ArrayList<Memento>();\n\n public void add(Memento state){\n mementoList.add(state);\n }\n\n public Memento get(int index){\n return mementoList.get(index);\n }\n}" }, { "code": null, "e": 65869, "s": 65831, "text": "Use CareTaker and Originator objects." }, { "code": null, "e": 65893, "s": 65869, "text": "MementoPatternDemo.java" }, { "code": null, "e": 66666, "s": 65893, "text": "public class MementoPatternDemo {\n public static void main(String[] args) {\n Originator originator = new Originator();\n CareTaker careTaker = new CareTaker();\n originator.setState(\"State #1\");\n originator.setState(\"State #2\");\n careTaker.add(originator.saveStateToMemento());\n originator.setState(\"State #3\");\n careTaker.add(originator.saveStateToMemento());\n originator.setState(\"State #4\");\n\n System.out.println(\"Current State: \" + originator.getState());\t\t\n originator.getStateFromMemento(careTaker.get(0));\n System.out.println(\"First saved State: \" + originator.getState());\n originator.getStateFromMemento(careTaker.get(1));\n System.out.println(\"Second saved State: \" + originator.getState());\n }\n}" }, { "code": null, "e": 66685, "s": 66666, "text": "Verify the output." }, { "code": null, "e": 66767, "s": 66685, "text": "Current State: State #4\nFirst saved State: State #2\nSecond saved State: State #3\n" }, { "code": null, "e": 66997, "s": 66767, "text": "Observer pattern is used when there is one to many relationship between objects such as if one object is modified, its depenedent objects are to be notified automatically. Observer pattern falls under behavioral pattern category." }, { "code": null, "e": 67279, "s": 66997, "text": "Observer pattern uses three actor classes. Subject, Observer and Client. Subject, an object having methods to attach and de-attach observers to a client object. We've created classes Subject, Observer abstract class and concrete classes extending the abstract class the Observer. \n" }, { "code": null, "e": 67395, "s": 67279, "text": "ObserverPatternDemo, our demo class will use Subject and concrete class objects to show observer pattern in action." }, { "code": null, "e": 67417, "s": 67395, "text": "Create Subject class." }, { "code": null, "e": 67430, "s": 67417, "text": "Subject.java" }, { "code": null, "e": 67959, "s": 67430, "text": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class Subject {\n\t\n private List<Observer> observers \n = new ArrayList<Observer>();\n private int state;\n\n public int getState() {\n return state;\n }\n\n public void setState(int state) {\n this.state = state;\n notifyAllObservers();\n }\n\n public void attach(Observer observer){\n observers.add(observer);\t\t\n }\n\n public void notifyAllObservers(){\n for (Observer observer : observers) {\n observer.update();\n }\n } \t\n}" }, { "code": null, "e": 67982, "s": 67959, "text": "Create Observer class." }, { "code": null, "e": 67996, "s": 67982, "text": "Observer.java" }, { "code": null, "e": 68095, "s": 67996, "text": "public abstract class Observer {\n protected Subject subject;\n public abstract void update();\n}" }, { "code": null, "e": 68128, "s": 68095, "text": "Create concrete observer classes" }, { "code": null, "e": 68148, "s": 68128, "text": "BinaryObserver.java" }, { "code": null, "e": 68455, "s": 68148, "text": "public class BinaryObserver extends Observer{\n\n public BinaryObserver(Subject subject){\n this.subject = subject;\n this.subject.attach(this);\n }\n\n @Override\n public void update() {\n System.out.println( \"Binary String: \" \n + Integer.toBinaryString( subject.getState() ) ); \n }\n}" }, { "code": null, "e": 68474, "s": 68455, "text": "OctalObserver.java" }, { "code": null, "e": 68775, "s": 68474, "text": "public class OctalObserver extends Observer{\n\n public OctalObserver(Subject subject){\n this.subject = subject;\n this.subject.attach(this);\n }\n\n @Override\n public void update() {\n System.out.println( \"Octal String: \" \n + Integer.toOctalString( subject.getState() ) ); \n }\n}" }, { "code": null, "e": 68793, "s": 68775, "text": "HexaObserver.java" }, { "code": null, "e": 69104, "s": 68793, "text": "public class HexaObserver extends Observer{\n\n public HexaObserver(Subject subject){\n this.subject = subject;\n this.subject.attach(this);\n }\n\n @Override\n public void update() {\n System.out.println( \"Hex String: \" \n + Integer.toHexString( subject.getState() ).toUpperCase() ); \n }\n}" }, { "code": null, "e": 69147, "s": 69104, "text": "Use Subject and concrete observer objects." }, { "code": null, "e": 69172, "s": 69147, "text": "ObserverPatternDemo.java" }, { "code": null, "e": 69564, "s": 69172, "text": "public class ObserverPatternDemo {\n public static void main(String[] args) {\n Subject subject = new Subject();\n\n new HexaObserver(subject);\n new OctalObserver(subject);\n new BinaryObserver(subject);\n\n System.out.println(\"First state change: 15\");\t\n subject.setState(15);\n System.out.println(\"Second state change: 10\");\t\n subject.setState(10);\n }\n}" }, { "code": null, "e": 69583, "s": 69564, "text": "Verify the output." }, { "code": null, "e": 69733, "s": 69583, "text": "First state change: 15\nHex String: F\nOctal String: 17\nBinary String: 1111\nSecond state change: 10\nHex String: A\nOctal String: 12\nBinary String: 1010\n" }, { "code": null, "e": 69853, "s": 69733, "text": "In State pattern a class behavior changes based on its state. This type of design pattern comes under behavior pattern." }, { "code": null, "e": 69992, "s": 69853, "text": "In State pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes." }, { "code": null, "e": 70153, "s": 69992, "text": "We're going to create a State interface defining a action and concrete state classes implementing the State interface. Context is a class which carries a State." }, { "code": null, "e": 70296, "s": 70153, "text": "StaePatternDemo, our demo class will use Context and state objects to demonstrate change in Context behavior based on type of state it is in." }, { "code": null, "e": 70317, "s": 70296, "text": "Create an interface." }, { "code": null, "e": 70328, "s": 70317, "text": "Image.java" }, { "code": null, "e": 70397, "s": 70328, "text": "public interface State {\n public void doAction(Context context);\n}" }, { "code": null, "e": 70454, "s": 70397, "text": "Create concrete classes implementing the same interface." }, { "code": null, "e": 70470, "s": 70454, "text": "StartState.java" }, { "code": null, "e": 70712, "s": 70470, "text": "public class StartState implements State {\n\n public void doAction(Context context) {\n System.out.println(\"Player is in start state\");\n context.setState(this);\t\n }\n\n public String toString(){\n return \"Start State\";\n }\n}" }, { "code": null, "e": 70727, "s": 70712, "text": "StopState.java" }, { "code": null, "e": 70966, "s": 70727, "text": "public class StopState implements State {\n\n public void doAction(Context context) {\n System.out.println(\"Player is in stop state\");\n context.setState(this);\t\n }\n\n public String toString(){\n return \"Stop State\";\n }\n}" }, { "code": null, "e": 70988, "s": 70966, "text": "Create Context Class." }, { "code": null, "e": 71001, "s": 70988, "text": "Context.java" }, { "code": null, "e": 71223, "s": 71001, "text": "public class Context {\n private State state;\n\n public Context(){\n state = null;\n }\n\n public void setState(State state){\n this.state = state;\t\t\n }\n\n public State getState(){\n return state;\n }\n}" }, { "code": null, "e": 71286, "s": 71223, "text": "Use the Context to see change in behaviour when State changes." }, { "code": null, "e": 71308, "s": 71286, "text": "StatePatternDemo.java" }, { "code": null, "e": 71712, "s": 71308, "text": "public class StatePatternDemo {\n public static void main(String[] args) {\n Context context = new Context();\n\n StartState startState = new StartState();\n startState.doAction(context);\n\n System.out.println(context.getState().toString());\n\n StopState stopState = new StopState();\n stopState.doAction(context);\n\n System.out.println(context.getState().toString());\n }\n}" }, { "code": null, "e": 71731, "s": 71712, "text": "Verify the output." }, { "code": null, "e": 71804, "s": 71731, "text": "Player is in start state\nStart State\nPlayer is in stop state\nStop State\n" }, { "code": null, "e": 72070, "s": 71804, "text": "In Null Object pattern, a null object replaces check of NULL object instance. Instead of putting if check for a null value, Null Object reflects a do nothing relationship. Such Null object can also be used to provide default behaviour in case data is not available." }, { "code": null, "e": 72341, "s": 72070, "text": "In Null Object pattern, we create a abstract class specifying the various operations to be done, concreate classes extending this class and a null object class providing do nothing implemention of this class and will be used seemlessly where we need to check null value." }, { "code": null, "e": 72649, "s": 72341, "text": "We're going to create a AbstractCustomer abstract class defining opearations, here the name of the customer and concrete classes extending the AbstractCustomer class. A factory class CustomerFactory is created to return either RealCustomer or NullCustomer objects based on the name of customer passed to it." }, { "code": null, "e": 72749, "s": 72649, "text": "NullPatternDemo, our demo class will use CustomerFactory to demonstrate use of Null Object pattern." }, { "code": null, "e": 72775, "s": 72749, "text": "Create an abstract class." }, { "code": null, "e": 72797, "s": 72775, "text": "AbstractCustomer.java" }, { "code": null, "e": 72939, "s": 72797, "text": "public abstract class AbstractCustomer {\n protected String name;\n public abstract boolean isNil();\n public abstract String getName();\n}" }, { "code": null, "e": 72990, "s": 72939, "text": "Create concrete classes extending the above class." }, { "code": null, "e": 73008, "s": 72990, "text": "RealCustomer.java" }, { "code": null, "e": 73273, "s": 73008, "text": "public class RealCustomer extends AbstractCustomer {\n\n public RealCustomer(String name) {\n this.name = name;\t\t\n }\n \n @Override\n public String getName() {\n return name;\n }\n \n @Override\n public boolean isNil() {\n return false;\n }\n}" }, { "code": null, "e": 73291, "s": 73273, "text": "NullCustomer.java" }, { "code": null, "e": 73511, "s": 73291, "text": "public class NullCustomer extends AbstractCustomer {\n\n @Override\n public String getName() {\n return \"Not Available in Customer Database\";\n }\n\n @Override\n public boolean isNil() {\n return true;\n }\n}" }, { "code": null, "e": 73541, "s": 73511, "text": "Create CustomerFactory Class." }, { "code": null, "e": 73562, "s": 73541, "text": "CustomerFactory.java" }, { "code": null, "e": 73917, "s": 73562, "text": "public class CustomerFactory {\n\t\n public static final String[] names = {\"Rob\", \"Joe\", \"Julie\"};\n\n public static AbstractCustomer getCustomer(String name){\n for (int i = 0; i < names.length; i++) {\n if (names[i].equalsIgnoreCase(name)){\n return new RealCustomer(name);\n }\n }\n return new NullCustomer();\n }\n}" }, { "code": null, "e": 74033, "s": 73917, "text": "Use the CustomerFactory get either RealCustomer or NullCustomer objects based on the name of customer passed to it." }, { "code": null, "e": 74054, "s": 74033, "text": "NullPatternDemo.java" }, { "code": null, "e": 74653, "s": 74054, "text": "public class NullPatternDemo {\n public static void main(String[] args) {\n\n AbstractCustomer customer1 = CustomerFactory.getCustomer(\"Rob\");\n AbstractCustomer customer2 = CustomerFactory.getCustomer(\"Bob\");\n AbstractCustomer customer3 = CustomerFactory.getCustomer(\"Julie\");\n AbstractCustomer customer4 = CustomerFactory.getCustomer(\"Laura\");\n\n System.out.println(\"Customers\");\n System.out.println(customer1.getName());\n System.out.println(customer2.getName());\n System.out.println(customer3.getName());\n System.out.println(customer4.getName());\n }\n}" }, { "code": null, "e": 74672, "s": 74653, "text": "Verify the output." }, { "code": null, "e": 74763, "s": 74672, "text": "Customers\nRob\nNot Available in Customer Database\nJulie\nNot Available in Customer Database\n" }, { "code": null, "e": 74904, "s": 74763, "text": "In Strategy pattern, a class behavior or its algorithm can be changed at run time. This type of design pattern comes under behavior pattern." }, { "code": null, "e": 75124, "s": 74904, "text": "In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object. The strategy object changes the executing algorithm of the context object." }, { "code": null, "e": 75294, "s": 75124, "text": "We're going to create a Strategy interface defining a action and concrete strategy classes implementing the Strategy interface. Context is a class which uses a Strategy." }, { "code": null, "e": 75449, "s": 75294, "text": "StrategyPatternDemo, our demo class will use Context and strategy objects to demonstrate change in Context behaviour based on strategy it deploys or uses." }, { "code": null, "e": 75470, "s": 75449, "text": "Create an interface." }, { "code": null, "e": 75484, "s": 75470, "text": "Strategy.java" }, { "code": null, "e": 75561, "s": 75484, "text": "public interface Strategy {\n public int doOperation(int num1, int num2);\n}" }, { "code": null, "e": 75618, "s": 75561, "text": "Create concrete classes implementing the same interface." }, { "code": null, "e": 75636, "s": 75618, "text": "OperationAdd.java" }, { "code": null, "e": 75777, "s": 75636, "text": "public class OperationAdd implements Strategy{\n @Override\n public int doOperation(int num1, int num2) {\n return num1 + num2;\n }\n}" }, { "code": null, "e": 75801, "s": 75777, "text": "OperationSubstract.java" }, { "code": null, "e": 75948, "s": 75801, "text": "public class OperationSubstract implements Strategy{\n @Override\n public int doOperation(int num1, int num2) {\n return num1 - num2;\n }\n}" }, { "code": null, "e": 75971, "s": 75948, "text": "OperationMultiply.java" }, { "code": null, "e": 76117, "s": 75971, "text": "public class OperationMultiply implements Strategy{\n @Override\n public int doOperation(int num1, int num2) {\n return num1 * num2;\n }\n}" }, { "code": null, "e": 76139, "s": 76117, "text": "Create Context Class." }, { "code": null, "e": 76152, "s": 76139, "text": "Context.java" }, { "code": null, "e": 76387, "s": 76152, "text": "public class Context {\n private Strategy strategy;\n\n public Context(Strategy strategy){\n this.strategy = strategy;\n }\n\n public int executeStrategy(int num1, int num2){\n return strategy.doOperation(num1, num2);\n }\n}" }, { "code": null, "e": 76460, "s": 76387, "text": "Use the Context to see change in behaviour when it changes its Strategy." }, { "code": null, "e": 76482, "s": 76460, "text": "StatePatternDemo.java" }, { "code": null, "e": 76958, "s": 76482, "text": "public class StrategyPatternDemo {\n public static void main(String[] args) {\n Context context = new Context(new OperationAdd());\t\t\n System.out.println(\"10 + 5 = \" + context.executeStrategy(10, 5));\n\n context = new Context(new OperationSubstract());\t\t\n System.out.println(\"10 - 5 = \" + context.executeStrategy(10, 5));\n\n context = new Context(new OperationMultiply());\t\t\n System.out.println(\"10 * 5 = \" + context.executeStrategy(10, 5));\n }\n}" }, { "code": null, "e": 76977, "s": 76958, "text": "Verify the output." }, { "code": null, "e": 77013, "s": 76977, "text": "10 + 5 = 15\n10 - 5 = 5\n10 * 5 = 50\n" }, { "code": null, "e": 77315, "s": 77013, "text": "In Template pattern, an abstract class exposes defined way(s)/template(s) to execute its methods. Its subclasses can overrides the method implementations as per need basis but the invocation is to be in the same way as defined by an abstract class. This pattern comes under behavior pattern category." }, { "code": null, "e": 77531, "s": 77315, "text": "We're going to create a Game abstract class defining operations with a template method set to be final so that it cannot be overridden. Cricket and Football are concrete classes extend Game and override its methods." }, { "code": null, "e": 77621, "s": 77531, "text": "TemplatePatternDemo, our demo class will use Game to demonstrate use of template pattern." }, { "code": null, "e": 77682, "s": 77621, "text": "Create an abstract class with a template method being final." }, { "code": null, "e": 77692, "s": 77682, "text": "Game.java" }, { "code": null, "e": 77991, "s": 77692, "text": "public abstract class Game {\n abstract void initialize();\n abstract void startPlay();\n abstract void endPlay();\n\n //template method\n public final void play(){\n\n //initialize the game\n initialize();\n\n //start game\n startPlay();\n\n //end game\n endPlay();\n }\n}" }, { "code": null, "e": 78042, "s": 77991, "text": "Create concrete classes extending the above class." }, { "code": null, "e": 78055, "s": 78042, "text": "Cricket.java" }, { "code": null, "e": 78404, "s": 78055, "text": "public class Cricket extends Game {\n\n @Override\n void endPlay() {\n System.out.println(\"Cricket Game Finished!\");\n }\n\n @Override\n void initialize() {\n System.out.println(\"Cricket Game Initialized! Start playing.\");\n }\n\n @Override\n void startPlay() {\n System.out.println(\"Cricket Game Started. Enjoy the game!\");\n }\n}" }, { "code": null, "e": 78418, "s": 78404, "text": "Football.java" }, { "code": null, "e": 78770, "s": 78418, "text": "public class Football extends Game {\n @Override\n void endPlay() {\n System.out.println(\"Football Game Finished!\");\n }\n\n @Override\n void initialize() {\n System.out.println(\"Football Game Initialized! Start playing.\");\n }\n\n @Override\n void startPlay() {\n System.out.println(\"Football Game Started. Enjoy the game!\");\n }\n}" }, { "code": null, "e": 78855, "s": 78770, "text": "Use the Game's template method play() to demonstrate a defined way of playing game." }, { "code": null, "e": 78880, "s": 78855, "text": "TemplatePatternDemo.java" }, { "code": null, "e": 79097, "s": 78880, "text": "public class TemplatePatternDemo {\n public static void main(String[] args) {\n\n Game game = new Cricket();\n game.play();\n System.out.println();\n game = new Football();\n game.play();\t\t\n }\n}" }, { "code": null, "e": 79116, "s": 79097, "text": "Verify the output." }, { "code": null, "e": 79325, "s": 79116, "text": "Cricket Game Initialized! Start playing.\nCricket Game Started. Enjoy the game!\nCricket Game Finished!\n\nFootball Game Initialized! Start playing.\nFootball Game Started. Enjoy the game!\nFootball Game Finished!\n" }, { "code": null, "e": 79691, "s": 79325, "text": "In Visitor pattern, we use a visitor class which changes the executing algorithm of an element class. By this way, execution algorithm of element can varies as visitor varies. This pattern comes under behavior pattern category. As per the pattern, element object has to accept the visitor object so that visitor object handles the operation on the element object. " }, { "code": null, "e": 80017, "s": 79691, "text": "We're going to create a ComputerPart interface defining accept opearation.Keyboard, Mouse, Monitor and Computer are concrete classes implementing ComputerPart interface. We'll define another interface ComputerPartVisitor which will define a visitor class operations. Computer uses concrete visitor to do corresponding action." }, { "code": null, "e": 80139, "s": 80017, "text": "VisitorPatternDemo, our demo class will use Computer, ComputerPartVisitor classes to demonstrate use of visitor pattern." }, { "code": null, "e": 80181, "s": 80139, "text": "Define an interface to represent element." }, { "code": null, "e": 80199, "s": 80181, "text": "ComputerPart.java" }, { "code": null, "e": 80303, "s": 80199, "text": "public interface class ComputerPart {\n public void accept(ComputerPartVisitor computerPartVisitor);\n}" }, { "code": null, "e": 80354, "s": 80303, "text": "Create concrete classes extending the above class." }, { "code": null, "e": 80368, "s": 80354, "text": "Keyboard.java" }, { "code": null, "e": 80542, "s": 80368, "text": "public class Keyboard implements ComputerPart {\n\n @Override\n public void accept(ComputerPartVisitor computerPartVisitor) {\n computerPartVisitor.visit(this);\n }\n}" }, { "code": null, "e": 80555, "s": 80542, "text": "Monitor.java" }, { "code": null, "e": 80728, "s": 80555, "text": "public class Monitor implements ComputerPart {\n\n @Override\n public void accept(ComputerPartVisitor computerPartVisitor) {\n computerPartVisitor.visit(this);\n }\n}" }, { "code": null, "e": 80739, "s": 80728, "text": "Mouse.java" }, { "code": null, "e": 80910, "s": 80739, "text": "public class Mouse implements ComputerPart {\n\n @Override\n public void accept(ComputerPartVisitor computerPartVisitor) {\n computerPartVisitor.visit(this);\n }\n}" }, { "code": null, "e": 80924, "s": 80910, "text": "Computer.java" }, { "code": null, "e": 81337, "s": 80924, "text": "public class Computer implements ComputerPart {\n\t\n ComputerPart[] parts;\n\n public Computer(){\n parts = new ComputerPart[] {new Mouse(), new Keyboard(), new Monitor()};\t\t\n } \n\n\n @Override\n public void accept(ComputerPartVisitor computerPartVisitor) {\n for (int i = 0; i < parts.length; i++) {\n parts[i].accept(computerPartVisitor);\n }\n computerPartVisitor.visit(this);\n }\n}" }, { "code": null, "e": 81379, "s": 81337, "text": "Define an interface to represent visitor." }, { "code": null, "e": 81404, "s": 81379, "text": "ComputerPartVisitor.java" }, { "code": null, "e": 81593, "s": 81404, "text": "public interface ComputerPartVisitor {\n\tpublic void visit(Computer computer);\n\tpublic void visit(Mouse mouse);\n\tpublic void visit(Keyboard keyboard);\n\tpublic void visit(Monitor monitor);\n}" }, { "code": null, "e": 81647, "s": 81593, "text": "Create concrete visitor implementing the above class." }, { "code": null, "e": 81679, "s": 81647, "text": "ComputerPartDisplayVisitor.java" }, { "code": null, "e": 82186, "s": 81679, "text": "public class ComputerPartDisplayVisitor implements ComputerPartVisitor {\n\n @Override\n public void visit(Computer computer) {\n System.out.println(\"Displaying Computer.\");\n }\n\n @Override\n public void visit(Mouse mouse) {\n System.out.println(\"Displaying Mouse.\");\n }\n\n @Override\n public void visit(Keyboard keyboard) {\n System.out.println(\"Displaying Keyboard.\");\n }\n\n @Override\n public void visit(Monitor monitor) {\n System.out.println(\"Displaying Monitor.\");\n }\n}" }, { "code": null, "e": 82251, "s": 82186, "text": "Use the ComputerPartDisplayVisitor to display parts of Computer." }, { "code": null, "e": 82275, "s": 82251, "text": "VisitorPatternDemo.java" }, { "code": null, "e": 82464, "s": 82275, "text": "public class VisitorPatternDemo {\n public static void main(String[] args) {\n\n ComputerPart computer = new Computer();\n computer.accept(new ComputerPartDisplayVisitor());\n }\n}" }, { "code": null, "e": 82483, "s": 82464, "text": "Verify the output." }, { "code": null, "e": 82564, "s": 82483, "text": "Displaying Mouse.\nDisplaying Keyboard.\nDisplaying Monitor.\nDisplaying Computer.\n" }, { "code": null, "e": 82675, "s": 82564, "text": "MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate application's concerns." }, { "code": null, "e": 82803, "s": 82675, "text": "Model - Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data changes." }, { "code": null, "e": 82931, "s": 82803, "text": "Model - Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data changes." }, { "code": null, "e": 83005, "s": 82931, "text": "View - View represents the visualization of the data that model contains." }, { "code": null, "e": 83079, "s": 83005, "text": "View - View represents the visualization of the data that model contains." }, { "code": null, "e": 83254, "s": 83079, "text": "Controller - Controller acts on both Model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps View and Model separate." }, { "code": null, "e": 83429, "s": 83254, "text": "Controller - Controller acts on both Model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps View and Model separate." }, { "code": null, "e": 83693, "s": 83429, "text": "We're going to create a Student object acting as a model.StudentView will be a view class which can print student details on console and StudentController is the controller class responsible to store data in Student object and update view StudentView accordingly." }, { "code": null, "e": 83786, "s": 83693, "text": "MVCPatternDemo, our demo class will use StudentController to demonstrate use of MVC pattern." }, { "code": null, "e": 83800, "s": 83786, "text": "Create Model." }, { "code": null, "e": 83813, "s": 83800, "text": "Student.java" }, { "code": null, "e": 84140, "s": 83813, "text": "public class Student {\n private String rollNo;\n private String name;\n public String getRollNo() {\n return rollNo;\n }\n public void setRollNo(String rollNo) {\n this.rollNo = rollNo;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n}" }, { "code": null, "e": 84153, "s": 84140, "text": "Create View." }, { "code": null, "e": 84170, "s": 84153, "text": "StudentView.java" }, { "code": null, "e": 84426, "s": 84170, "text": "public class StudentView {\n public void printStudentDetails(String studentName, String studentRollNo){\n System.out.println(\"Student: \");\n System.out.println(\"Name: \" + studentName);\n System.out.println(\"Roll No: \" + studentRollNo);\n }\n}" }, { "code": null, "e": 84445, "s": 84426, "text": "Create Controller." }, { "code": null, "e": 84468, "s": 84445, "text": "StudentController.java" }, { "code": null, "e": 85100, "s": 84468, "text": "public class StudentController {\n private Student model;\n private StudentView view;\n\n public StudentController(Student model, StudentView view){\n this.model = model;\n this.view = view;\n }\n\n public void setStudentName(String name){\n model.setName(name);\t\t\n }\n\n public String getStudentName(){\n return model.getName();\t\t\n }\n\n public void setStudentRollNo(String rollNo){\n model.setRollNo(rollNo);\t\t\n }\n\n public String getStudentRollNo(){\n return model.getRollNo();\t\t\n }\n\n public void updateView(){\t\t\t\t\n view.printStudentDetails(model.getName(), model.getRollNo());\n }\t\n}" }, { "code": null, "e": 85175, "s": 85100, "text": "Use the StudentController methods to demonstrate MVC design pattern usage." }, { "code": null, "e": 85195, "s": 85175, "text": "MVCPatternDemo.java" }, { "code": null, "e": 85896, "s": 85195, "text": "public class MVCPatternDemo {\n public static void main(String[] args) {\n\n //fetch student record based on his roll no from the database\n Student model = retriveStudentFromDatabase();\n\n //Create a view : to write student details on console\n StudentView view = new StudentView();\n\n StudentController controller = new StudentController(model, view);\n\n controller.updateView();\n\n //update model data\n controller.setStudentName(\"John\");\n\n controller.updateView();\n }\n\n private static Student retriveStudentFromDatabase(){\n Student student = new Student();\n student.setName(\"Robert\");\n student.setRollNo(\"10\");\n return student;\n }\n}" }, { "code": null, "e": 85915, "s": 85896, "text": "Verify the output." }, { "code": null, "e": 85985, "s": 85915, "text": "Student: \nName: Robert\nRoll No: 10\nStudent: \nName: Julie\nRoll No: 10\n" }, { "code": null, "e": 86235, "s": 85985, "text": "Business Delegate Pattern is used to decouple presentation tier and business tier. It is basically use to reduce communication or remote lookup functionality to business tier code in presentation tier code. In business tier we've following entities." }, { "code": null, "e": 86304, "s": 86235, "text": "Client - Presentation tier code may be JSP, servlet or UI java code." }, { "code": null, "e": 86373, "s": 86304, "text": "Client - Presentation tier code may be JSP, servlet or UI java code." }, { "code": null, "e": 86487, "s": 86373, "text": "Business Delegate - A single entry point class for client entities to provide access to Business Service methods." }, { "code": null, "e": 86601, "s": 86487, "text": "Business Delegate - A single entry point class for client entities to provide access to Business Service methods." }, { "code": null, "e": 86759, "s": 86601, "text": "LookUp Service - Lookup service object is responsible to get relative business implementation and provide business object access to business delegate object." }, { "code": null, "e": 86917, "s": 86759, "text": "LookUp Service - Lookup service object is responsible to get relative business implementation and provide business object access to business delegate object." }, { "code": null, "e": 87063, "s": 86917, "text": "Business Service - Business Service interface. Concrete classes implements this business service to provide actual business implementation logic." }, { "code": null, "e": 87209, "s": 87063, "text": "Business Service - Business Service interface. Concrete classes implements this business service to provide actual business implementation logic." }, { "code": null, "e": 87378, "s": 87209, "text": "We're going to create a Client, BusinessDelegate, BusinessService, LookUpService, JMSService and EJBService representing various entities of Business Delegate pattern. " }, { "code": null, "e": 87508, "s": 87378, "text": "BusinessDelegatePatternDemo, our demo class will use BusinessDelegate and Client to demonstrate use of Business Delegate pattern." }, { "code": null, "e": 87542, "s": 87508, "text": "Create BusinessService Interface." }, { "code": null, "e": 87563, "s": 87542, "text": "BusinessService.java" }, { "code": null, "e": 87631, "s": 87563, "text": "public interface BusinessService {\n public void doProcessing();\n}" }, { "code": null, "e": 87665, "s": 87631, "text": "Create Concreate Service Classes." }, { "code": null, "e": 87681, "s": 87665, "text": "EJBService.java" }, { "code": null, "e": 87856, "s": 87681, "text": "public class EJBService implements BusinessService {\n\n @Override\n public void doProcessing() {\n System.out.println(\"Processing task by invoking EJB Service\");\n }\n}" }, { "code": null, "e": 87872, "s": 87856, "text": "JMSService.java" }, { "code": null, "e": 88047, "s": 87872, "text": "public class JMSService implements BusinessService {\n\n @Override\n public void doProcessing() {\n System.out.println(\"Processing task by invoking JMS Service\");\n }\n}" }, { "code": null, "e": 88079, "s": 88047, "text": "Create Business Lookup Service." }, { "code": null, "e": 88099, "s": 88079, "text": "BusinessLookUp.java" }, { "code": null, "e": 88339, "s": 88099, "text": "public class BusinessLookUp {\n public BusinessService getBusinessService(String serviceType){\n if(serviceType.equalsIgnoreCase(\"EJB\")){\n return new EJBService();\n }else {\n return new JMSService();\n }\n }\n}" }, { "code": null, "e": 88365, "s": 88339, "text": "Create Business Delegate." }, { "code": null, "e": 88385, "s": 88365, "text": "BusinessLookUp.java" }, { "code": null, "e": 88795, "s": 88385, "text": "public class BusinessDelegate {\n private BusinessLookUp lookupService = new BusinessLookUp();\n private BusinessService businessService;\n private String serviceType;\n\n public void setServiceType(String serviceType){\n this.serviceType = serviceType;\n }\n\n public void doTask(){\n businessService = lookupService.getBusinessService(serviceType);\n businessService.doProcessing();\t\t\n }\n}" }, { "code": null, "e": 88810, "s": 88795, "text": "Create Client." }, { "code": null, "e": 88823, "s": 88810, "text": "Student.java" }, { "code": null, "e": 89056, "s": 88823, "text": "public class Client {\n\t\n BusinessDelegate businessService;\n\n public Client(BusinessDelegate businessService){\n this.businessService = businessService;\n }\n\n public void doTask(){\t\t\n businessService.doTask();\n }\n}" }, { "code": null, "e": 89138, "s": 89056, "text": "Use BusinessDelegate and Client classes to demonstrate Business Delegate pattern." }, { "code": null, "e": 89171, "s": 89138, "text": "BusinessDelegatePatternDemo.java" }, { "code": null, "e": 89526, "s": 89171, "text": "public class BusinessDelegatePatternDemo {\n\t\n public static void main(String[] args) {\n\n BusinessDelegate businessDelegate = new BusinessDelegate();\n businessDelegate.setServiceType(\"EJB\");\n\n Client client = new Client(businessDelegate);\n client.doTask();\n\n businessDelegate.setServiceType(\"JMS\");\n client.doTask();\n }\n}" }, { "code": null, "e": 89545, "s": 89526, "text": "Verify the output." }, { "code": null, "e": 89626, "s": 89545, "text": "Processing task by invoking EJB Service\nProcessing task by invoking JMS Service\n" }, { "code": null, "e": 89958, "s": 89626, "text": "Composite Entity pattern is used in EJB persistence mechanism. A Composite entity is an EJB entity bean which represents a graph of objects. When a composite entity is updated, internally dependent objects beans get updated automatically as being managed by EJB entity bean. Following are the participants in Composite Entity Bean." }, { "code": null, "e": 90103, "s": 89958, "text": "Composite Entity - It is primary entity bean.It can be coarse grained or can contain a coarse grained object to be used for persistence purpose." }, { "code": null, "e": 90248, "s": 90103, "text": "Composite Entity - It is primary entity bean.It can be coarse grained or can contain a coarse grained object to be used for persistence purpose." }, { "code": null, "e": 90387, "s": 90248, "text": "Coarse-Grained Object -This object contains dependent objects. It has its own life cycle and also manages life cycle of dependent objects." }, { "code": null, "e": 90526, "s": 90387, "text": "Coarse-Grained Object -This object contains dependent objects. It has its own life cycle and also manages life cycle of dependent objects." }, { "code": null, "e": 90646, "s": 90526, "text": "Dependent Object - Dependent objects is an object which depends on Coarse-Grained object for its persistence lifecycle." }, { "code": null, "e": 90766, "s": 90646, "text": "Dependent Object - Dependent objects is an object which depends on Coarse-Grained object for its persistence lifecycle." }, { "code": null, "e": 90838, "s": 90766, "text": "Strategies - Strategies represents how to implement a Composite Entity." }, { "code": null, "e": 90910, "s": 90838, "text": "Strategies - Strategies represents how to implement a Composite Entity." }, { "code": null, "e": 91165, "s": 90910, "text": "We're going to create CompositeEntity object acting as CompositeEntity. CoarseGrainedObject will be a class which contains dependent objects. CompositeEntityPatternDemo, our demo class will use Client class to demonstrate use of Composite Entity pattern." }, { "code": null, "e": 91191, "s": 91165, "text": "Create Dependent Objects." }, { "code": null, "e": 91213, "s": 91191, "text": "DependentObject1.java" }, { "code": null, "e": 91395, "s": 91213, "text": "public class DependentObject1 {\n\t\n private String data;\n\n public void setData(String data){\n this.data = data; \n } \n\n public String getData(){\n return data;\n }\n}" }, { "code": null, "e": 91417, "s": 91395, "text": "DependentObject2.java" }, { "code": null, "e": 91599, "s": 91417, "text": "public class DependentObject2 {\n\t\n private String data;\n\n public void setData(String data){\n this.data = data; \n } \n\n public String getData(){\n return data;\n }\n}" }, { "code": null, "e": 91629, "s": 91599, "text": "Create Coarse Grained Object." }, { "code": null, "e": 91654, "s": 91629, "text": "CoarseGrainedObject.java" }, { "code": null, "e": 91994, "s": 91654, "text": "public class CoarseGrainedObject {\n DependentObject1 do1 = new DependentObject1();\n DependentObject2 do2 = new DependentObject2();\n\n public void setData(String data1, String data2){\n do1.setData(data1);\n do2.setData(data2);\n }\n\n public String[] getData(){\n return new String[] {do1.getData(),do2.getData()};\n }\n}" }, { "code": null, "e": 92019, "s": 91994, "text": "Create Composite Entity." }, { "code": null, "e": 92040, "s": 92019, "text": "CompositeEntity.java" }, { "code": null, "e": 92292, "s": 92040, "text": "public class CompositeEntity {\n private CoarseGrainedObject cgo = new CoarseGrainedObject();\n\n public void setData(String data1, String data2){\n cgo.setData(data1, data2);\n }\n\n public String[] getData(){\n return cgo.getData();\n }\n}" }, { "code": null, "e": 92337, "s": 92292, "text": "Create Client class to use Composite Entity." }, { "code": null, "e": 92349, "s": 92337, "text": "Client.java" }, { "code": null, "e": 92723, "s": 92349, "text": "public class Client {\n private CompositeEntity compositeEntity = new CompositeEntity();\n\n public void printData(){\n for (int i = 0; i < compositeEntity.getData().length; i++) {\n System.out.println(\"Data: \" + compositeEntity.getData()[i]);\n }\n }\n\n public void setData(String data1, String data2){\n compositeEntity.setData(data1, data2);\n }\n}" }, { "code": null, "e": 92792, "s": 92723, "text": "Use the Client to demonstrate Composite Entity design pattern usage." }, { "code": null, "e": 92824, "s": 92792, "text": "CompositeEntityPatternDemo.java" }, { "code": null, "e": 93094, "s": 92824, "text": "public class CompositeEntityPatternDemo {\n public static void main(String[] args) {\n Client client = new Client();\n client.setData(\"Test\", \"Data\");\n client.printData();\n client.setData(\"Second Test\", \"Data1\");\n client.printData();\n }\n}" }, { "code": null, "e": 93113, "s": 93094, "text": "Verify the output." }, { "code": null, "e": 93166, "s": 93113, "text": "Data: Test\nData: Data\nData: Second Test\nData: Data1\n" }, { "code": null, "e": 93368, "s": 93166, "text": "Data Access Object Pattern or DAO pattern is used to separate low level data accessing API or operations from high level business services. Following are the participants in Data Access Object Pattern." }, { "code": null, "e": 93484, "s": 93368, "text": "Data Access Object Interface - This interface defines the standard operations to be performed on a model object(s)." }, { "code": null, "e": 93600, "s": 93484, "text": "Data Access Object Interface - This interface defines the standard operations to be performed on a model object(s)." }, { "code": null, "e": 93790, "s": 93600, "text": "Data Access Object concrete class -This class implements above interface. This class is responsible to get data from a datasource which can be database / xml or any other storage mechanism." }, { "code": null, "e": 93980, "s": 93790, "text": "Data Access Object concrete class -This class implements above interface. This class is responsible to get data from a datasource which can be database / xml or any other storage mechanism." }, { "code": null, "e": 94107, "s": 93980, "text": "Model Object or Value Object - This object is simple POJO containing get/set methods to store data retrieved using DAO class." }, { "code": null, "e": 94234, "s": 94107, "text": "Model Object or Value Object - This object is simple POJO containing get/set methods to store data retrieved using DAO class." }, { "code": null, "e": 94525, "s": 94234, "text": "We're going to create a Student object acting as a Model or Value Object.StudentDao is Data Access Object Interface.StudentDaoImpl is concrete class implementing Data Access Object Interface. DaoPatternDemo, our demo class will use StudentDao demonstrate use of Data Access Object pattern." }, { "code": null, "e": 94546, "s": 94525, "text": "Create Value Object." }, { "code": null, "e": 94559, "s": 94546, "text": "Student.java" }, { "code": null, "e": 94976, "s": 94559, "text": "public class Student {\n private String name;\n private int rollNo;\n\n Student(String name, int rollNo){\n this.name = name;\n this.rollNo = rollNo;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public int getRollNo() {\n return rollNo;\n }\n\n public void setRollNo(int rollNo) {\n this.rollNo = rollNo;\n }\n}" }, { "code": null, "e": 95013, "s": 94976, "text": "Create Data Access Object Interface." }, { "code": null, "e": 95029, "s": 95013, "text": "StudentDao.java" }, { "code": null, "e": 95263, "s": 95029, "text": "import java.util.List;\n\npublic interface StudentDao {\n public List<Student> getAllStudents();\n public Student getStudent(int rollNo);\n public void updateStudent(Student student);\n public void deleteStudent(Student student);\n}" }, { "code": null, "e": 95316, "s": 95263, "text": "Create concreate class implementing above interface." }, { "code": null, "e": 95336, "s": 95316, "text": "StudentDaoImpl.java" }, { "code": null, "e": 96432, "s": 95336, "text": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class StudentDaoImpl implements StudentDao {\n\t\n //list is working as a database\n List<Student> students;\n\n public StudentDaoImpl(){\n students = new ArrayList<Student>();\n Student student1 = new Student(\"Robert\",0);\n Student student2 = new Student(\"John\",1);\n students.add(student1);\n students.add(student2);\t\t\n }\n @Override\n public void deleteStudent(Student student) {\n students.remove(student.getRollNo());\n System.out.println(\"Student: Roll No \" + student.getRollNo() \n +\", deleted from database\");\n }\n\n //retrive list of students from the database\n @Override\n public List<Student> getAllStudents() {\n return students;\n }\n\n @Override\n public Student getStudent(int rollNo) {\n return students.get(rollNo);\n }\n\n @Override\n public void updateStudent(Student student) {\n students.get(student.getRollNo()).setName(student.getName());\n System.out.println(\"Student: Roll No \" + student.getRollNo() \n +\", updated in the database\");\n }\n}" }, { "code": null, "e": 96500, "s": 96432, "text": "Use the StudentDao to demonstrate Data Access Object pattern usage." }, { "code": null, "e": 96532, "s": 96500, "text": "CompositeEntityPatternDemo.java" }, { "code": null, "e": 97213, "s": 96532, "text": "public class DaoPatternDemo {\n public static void main(String[] args) {\n StudentDao studentDao = new StudentDaoImpl();\n\n //print all students\n for (Student student : studentDao.getAllStudents()) {\n System.out.println(\"Student: [RollNo : \"\n +student.getRollNo()+\", Name : \"+student.getName()+\" ]\");\n }\n\n\n //update student\n Student student =studentDao.getAllStudents().get(0);\n student.setName(\"Michael\");\n studentDao.updateStudent(student);\n\n //get the student\n studentDao.getStudent(0);\n System.out.println(\"Student: [RollNo : \"\n +student.getRollNo()+\", Name : \"+student.getName()+\" ]\");\t\t\n }\n}" }, { "code": null, "e": 97232, "s": 97213, "text": "Verify the output." }, { "code": null, "e": 97390, "s": 97232, "text": "Student: [RollNo : 0, Name : Robert ]\nStudent: [RollNo : 1, Name : John ]\nStudent: Roll No 0, updated in the database\nStudent: [RollNo : 0, Name : Michael ]\n" }, { "code": null, "e": 97743, "s": 97390, "text": "The front controller design pattern is used to provide a centralized request handling mechanism so that all requests will be handled by a single handler. This handler can do the authentication/ authorization/ logging or tracking of request and then pass the requests to corresponding handlers. Following are the entities of this type of design pattern." }, { "code": null, "e": 97862, "s": 97743, "text": "Front Controller - Single handler for all kind of request coming to the application (either web based/ desktop based)." }, { "code": null, "e": 97981, "s": 97862, "text": "Front Controller - Single handler for all kind of request coming to the application (either web based/ desktop based)." }, { "code": null, "e": 98105, "s": 97981, "text": "Dispatcher - Front Controller may use a dispatcher object which can dispatch the request to corresponding specific handler." }, { "code": null, "e": 98229, "s": 98105, "text": "Dispatcher - Front Controller may use a dispatcher object which can dispatch the request to corresponding specific handler." }, { "code": null, "e": 98290, "s": 98229, "text": "View - Views are the object for which the requests are made." }, { "code": null, "e": 98351, "s": 98290, "text": "View - Views are the object for which the requests are made." }, { "code": null, "e": 98561, "s": 98351, "text": "We're going to create a FrontController,Dispatcher to act as Front Controller and Dispatcher correspondingly. HomeView and StudentView represent various views for which requests can come to front controller. " }, { "code": null, "e": 98678, "s": 98561, "text": "FrontControllerPatternDemo, our demo class will use FrontController ato demonstrate Front Controller Design Pattern." }, { "code": null, "e": 98692, "s": 98678, "text": "Create Views." }, { "code": null, "e": 98706, "s": 98692, "text": "HomeView.java" }, { "code": null, "e": 98810, "s": 98706, "text": "public class HomeView {\n public void show(){\n System.out.println(\"Displaying Home Page\");\n }\n}" }, { "code": null, "e": 98827, "s": 98810, "text": "StudentView.java" }, { "code": null, "e": 98937, "s": 98827, "text": "public class StudentView {\n public void show(){\n System.out.println(\"Displaying Student Page\");\n }\n}" }, { "code": null, "e": 98956, "s": 98937, "text": "Create Dispatcher." }, { "code": null, "e": 98972, "s": 98956, "text": "Dispatcher.java" }, { "code": null, "e": 99338, "s": 98972, "text": "public class Dispatcher {\n private StudentView studentView;\n private HomeView homeView;\n public Dispatcher(){\n studentView = new StudentView();\n homeView = new HomeView();\n }\n\n public void dispatch(String request){\n if(request.equalsIgnoreCase(\"STUDENT\")){\n studentView.show();\n }else{\n homeView.show();\n }\t\n }\n}" }, { "code": null, "e": 99361, "s": 99338, "text": "Create FrontController" }, { "code": null, "e": 99374, "s": 99361, "text": "Context.java" }, { "code": null, "e": 99966, "s": 99374, "text": "public class FrontController {\n\t\n private Dispatcher dispatcher;\n\n public FrontController(){\n dispatcher = new Dispatcher();\n }\n\n private boolean isAuthenticUser(){\n System.out.println(\"User is authenticated successfully.\");\n return true;\n }\n\n private void trackRequest(String request){\n System.out.println(\"Page requested: \" + request);\n }\n\n public void dispatchRequest(String request){\n //log each request\n trackRequest(request);\n //authenticate the user\n if(isAuthenticUser()){\n dispatcher.dispatch(request);\n }\t\n }\n}" }, { "code": null, "e": 100038, "s": 99966, "text": "Use the FrontController to demonstrate Front Controller Design Pattern." }, { "code": null, "e": 100070, "s": 100038, "text": "FrontControllerPatternDemo.java" }, { "code": null, "e": 100323, "s": 100070, "text": "public class FrontControllerPatternDemo {\n public static void main(String[] args) {\n FrontController frontController = new FrontController();\n frontController.dispatchRequest(\"HOME\");\n frontController.dispatchRequest(\"STUDENT\");\n }\n}" }, { "code": null, "e": 100342, "s": 100323, "text": "Verify the output." }, { "code": null, "e": 100505, "s": 100342, "text": "Page requested: HOME\nUser is authenticated successfully.\nDisplaying Home Page\nPage requested: STUDENT\nUser is authenticated successfully.\nDisplaying Student Page\n" }, { "code": null, "e": 100952, "s": 100505, "text": "The intercepting filter design pattern is used when we want to do some pre-processing / post-processing with request or response of the application. Filters are defined and applied on the request before passing the request to actual target application. Filters can do the authentication/ authorization/ logging or tracking of request and then pass the requests to corresponding handlers. Following are the entities of this type of design pattern." }, { "code": null, "e": 101056, "s": 100952, "text": "Filter - Filter which will perform certain task prior or after execution of request by request handler." }, { "code": null, "e": 101160, "s": 101056, "text": "Filter - Filter which will perform certain task prior or after execution of request by request handler." }, { "code": null, "e": 101266, "s": 101160, "text": "Filter Chain - Filter Chain carries multiple filters and help to execute them in defined order on target." }, { "code": null, "e": 101372, "s": 101266, "text": "Filter Chain - Filter Chain carries multiple filters and help to execute them in defined order on target." }, { "code": null, "e": 101418, "s": 101372, "text": "Target - Target object is the request handler" }, { "code": null, "e": 101464, "s": 101418, "text": "Target - Target object is the request handler" }, { "code": null, "e": 101534, "s": 101464, "text": "Filter Manager - Filter Manager manages the filters and Filter Chain." }, { "code": null, "e": 101604, "s": 101534, "text": "Filter Manager - Filter Manager manages the filters and Filter Chain." }, { "code": null, "e": 101674, "s": 101604, "text": "Client - Client is the object who sends request to the Target object." }, { "code": null, "e": 101744, "s": 101674, "text": "Client - Client is the object who sends request to the Target object." }, { "code": null, "e": 101922, "s": 101744, "text": "We're going to create a FilterChain,FilterManager, Target, Client as various objects representing our entities.AuthenticationFilter and DebugFilter represents concrete filters." }, { "code": null, "e": 102028, "s": 101922, "text": "InterceptingFilterDemo, our demo class will use Client to demonstrate Intercepting Filter Design Pattern." }, { "code": null, "e": 102053, "s": 102028, "text": "Create Filter interface." }, { "code": null, "e": 102065, "s": 102053, "text": "Filter.java" }, { "code": null, "e": 102133, "s": 102065, "text": "public interface Filter {\n public void execute(String request);\n}" }, { "code": null, "e": 102158, "s": 102133, "text": "Create concrete filters." }, { "code": null, "e": 102184, "s": 102158, "text": "AuthenticationFilter.java" }, { "code": null, "e": 102349, "s": 102184, "text": "public class AuthenticationFilter implements Filter {\n public void execute(String request){\n System.out.println(\"Authenticating request: \" + request);\n }\n}" }, { "code": null, "e": 102366, "s": 102349, "text": "DebugFilter.java" }, { "code": null, "e": 102511, "s": 102366, "text": "public class DebugFilter implements Filter {\n public void execute(String request){\n System.out.println(\"request log: \" + request);\n }\n}" }, { "code": null, "e": 102525, "s": 102511, "text": "Create Target" }, { "code": null, "e": 102537, "s": 102525, "text": "Target.java" }, { "code": null, "e": 102665, "s": 102537, "text": "public class Target {\n public void execute(String request){\n System.out.println(\"Executing request: \" + request);\n }\n}" }, { "code": null, "e": 102685, "s": 102665, "text": "Create Filter Chain" }, { "code": null, "e": 102702, "s": 102685, "text": "FilterChain.java" }, { "code": null, "e": 103174, "s": 102702, "text": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class FilterChain {\n private List<Filter> filters = new ArrayList<Filter>();\n private Target target;\n\n public void addFilter(Filter filter){\n filters.add(filter);\n }\n\n public void execute(String request){\n for (Filter filter : filters) {\n filter.execute(request);\n }\n target.execute(request);\n }\n\n public void setTarget(Target target){\n this.target = target;\n }\n}" }, { "code": null, "e": 103196, "s": 103174, "text": "Create Filter Manager" }, { "code": null, "e": 103215, "s": 103196, "text": "FilterManager.java" }, { "code": null, "e": 103567, "s": 103215, "text": "public class FilterManager {\n FilterChain filterChain;\n\n public FilterManager(Target target){\n filterChain = new FilterChain();\n filterChain.setTarget(target);\n }\n public void setFilter(Filter filter){\n filterChain.addFilter(filter);\n }\n\n public void filterRequest(String request){\n filterChain.execute(request);\n }\n}" }, { "code": null, "e": 103581, "s": 103567, "text": "Create Client" }, { "code": null, "e": 103593, "s": 103581, "text": "Client.java" }, { "code": null, "e": 103853, "s": 103593, "text": "public class Client {\n FilterManager filterManager;\n\n public void setFilterManager(FilterManager filterManager){\n this.filterManager = filterManager;\n }\n\n public void sendRequest(String request){\n filterManager.filterRequest(request);\n }\n}" }, { "code": null, "e": 103919, "s": 103853, "text": "Use the Client to demonstrate Intercepting Filter Design Pattern." }, { "code": null, "e": 103951, "s": 103919, "text": "FrontControllerPatternDemo.java" }, { "code": null, "e": 104335, "s": 103951, "text": "public class InterceptingFilterDemo {\n public static void main(String[] args) {\n FilterManager filterManager = new FilterManager(new Target());\n filterManager.setFilter(new AuthenticationFilter());\n filterManager.setFilter(new DebugFilter());\n\n Client client = new Client();\n client.setFilterManager(filterManager);\n client.sendRequest(\"HOME\");\n }\n}" }, { "code": null, "e": 104354, "s": 104335, "text": "Verify the output." }, { "code": null, "e": 104426, "s": 104354, "text": "Authenticating request: HOME\nrequest log: HOME\nExecuting request: HOME\n" }, { "code": null, "e": 104940, "s": 104426, "text": "The service locator design pattern is used when we want to locate various services using JNDI lookup. Considering high cost of looking up JNDI for a service, Service Locator pattern makes use of caching technique. For the first time a service is required, Service Locator looks up in JNDI and caches the service object. Further lookup or same service via Service Locator is done in its cache which improves the performance of application to great extent. Following are the entities of this type of design pattern." }, { "code": null, "e": 105060, "s": 104940, "text": "Service - Actual Service which will process the request. Reference of such service is to be looked upon in JNDI server." }, { "code": null, "e": 105180, "s": 105060, "text": "Service - Actual Service which will process the request. Reference of such service is to be looked upon in JNDI server." }, { "code": null, "e": 105280, "s": 105180, "text": "Context / Initial Context -JNDI Context, carries the reference to service used for lookup purpose. " }, { "code": null, "e": 105380, "s": 105280, "text": "Context / Initial Context -JNDI Context, carries the reference to service used for lookup purpose. " }, { "code": null, "e": 105497, "s": 105380, "text": "Service Locator - Service Locator is a single point of contact to get services by JNDI lookup, caching the services." }, { "code": null, "e": 105614, "s": 105497, "text": "Service Locator - Service Locator is a single point of contact to get services by JNDI lookup, caching the services." }, { "code": null, "e": 105674, "s": 105614, "text": "Cache - Cache to store references of services to reuse them" }, { "code": null, "e": 105734, "s": 105674, "text": "Cache - Cache to store references of services to reuse them" }, { "code": null, "e": 105809, "s": 105734, "text": "Client - Client is the object who invokes the services via ServiceLocator." }, { "code": null, "e": 105884, "s": 105809, "text": "Client - Client is the object who invokes the services via ServiceLocator." }, { "code": null, "e": 106052, "s": 105884, "text": "We're going to create a ServiceLocator,InitialContext, Cache, Service as various objects representing our entities.Service1 and Service2 represents concrete services." }, { "code": null, "e": 106196, "s": 106052, "text": "ServiceLocatorPatternDemo, our demo class is acting as a client here and will use ServiceLocator to demonstrate Service Locator Design Pattern." }, { "code": null, "e": 106222, "s": 106196, "text": "Create Service interface." }, { "code": null, "e": 106235, "s": 106222, "text": "Service.java" }, { "code": null, "e": 106318, "s": 106235, "text": "public interface Service {\n public String getName();\n public void execute();\n}" }, { "code": null, "e": 106344, "s": 106318, "text": "Create concrete services." }, { "code": null, "e": 106358, "s": 106344, "text": "Service1.java" }, { "code": null, "e": 106555, "s": 106358, "text": "public class Service1 implements Service {\n public void execute(){\n System.out.println(\"Executing Service1\");\n }\n\n @Override\n public String getName() {\n return \"Service1\";\n }\n}" }, { "code": null, "e": 106569, "s": 106555, "text": "Service2.java" }, { "code": null, "e": 106766, "s": 106569, "text": "public class Service2 implements Service {\n public void execute(){\n System.out.println(\"Executing Service2\");\n }\n\n @Override\n public String getName() {\n return \"Service2\";\n }\n}" }, { "code": null, "e": 106804, "s": 106766, "text": "Create InitialContext for JNDI lookup" }, { "code": null, "e": 106824, "s": 106804, "text": "InitialContext.java" }, { "code": null, "e": 107257, "s": 106824, "text": "public class InitialContext {\n public Object lookup(String jndiName){\n if(jndiName.equalsIgnoreCase(\"SERVICE1\")){\n System.out.println(\"Looking up and creating a new Service1 object\");\n return new Service1();\n }else if (jndiName.equalsIgnoreCase(\"SERVICE2\")){\n System.out.println(\"Looking up and creating a new Service2 object\");\n return new Service2();\n }\n return null;\t\t\n }\n}" }, { "code": null, "e": 107270, "s": 107257, "text": "Create Cache" }, { "code": null, "e": 107281, "s": 107270, "text": "Cache.java" }, { "code": null, "e": 108064, "s": 107281, "text": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class Cache {\n\n private List<Service> services;\n\n public Cache(){\n services = new ArrayList<Service>();\n }\n\n public Service getService(String serviceName){\n for (Service service : services) {\n if(service.getName().equalsIgnoreCase(serviceName)){\n System.out.println(\"Returning cached \"+serviceName+\" object\");\n return service;\n }\n }\n return null;\n }\n\n public void addService(Service newService){\n boolean exists = false;\n for (Service service : services) {\n if(service.getName().equalsIgnoreCase(newService.getName())){\n exists = true;\n }\n }\n if(!exists){\n services.add(newService);\n }\n }\n}" }, { "code": null, "e": 108087, "s": 108064, "text": "Create Service Locator" }, { "code": null, "e": 108107, "s": 108087, "text": "ServiceLocator.java" }, { "code": null, "e": 108562, "s": 108107, "text": "public class ServiceLocator {\n private static Cache cache;\n\n static {\n cache = new Cache();\t\t\n }\n\n public static Service getService(String jndiName){\n\n Service service = cache.getService(jndiName);\n\n if(service != null){\n return service;\n }\n\n InitialContext context = new InitialContext();\n Service service1 = (Service)context.lookup(jndiName);\n cache.addService(service1);\n return service1;\n }\n}" }, { "code": null, "e": 108632, "s": 108562, "text": "Use the ServiceLocator to demonstrate Service Locator Design Pattern." }, { "code": null, "e": 108663, "s": 108632, "text": "ServiceLocatorPatternDemo.java" }, { "code": null, "e": 109085, "s": 108663, "text": "public class ServiceLocatorPatternDemo {\n public static void main(String[] args) {\n Service service = ServiceLocator.getService(\"Service1\");\n service.execute();\n service = ServiceLocator.getService(\"Service2\");\n service.execute();\n service = ServiceLocator.getService(\"Service1\");\n service.execute();\n service = ServiceLocator.getService(\"Service2\");\n service.execute();\t\t\n }\n}" }, { "code": null, "e": 109104, "s": 109085, "text": "Verify the output." }, { "code": null, "e": 109341, "s": 109104, "text": "Looking up and creating a new Service1 object\nExecuting Service1\nLooking up and creating a new Service2 object\nExecuting Service2\nReturning cached Service1 object\nExecuting Service1\nReturning cached Service2 object\nExecuting Service2\n" }, { "code": null, "e": 110015, "s": 109341, "text": "The Transfer Object pattern is used when we want to pass data with multiple attributes in one shot from client to server. Transfer object is also known as Value Object. Transfer Object is a simple POJO class having getter/setter methods and is serializable so that it can be transferred over the network. It do not have any behavior. Server Side business class normally fetches data from the database and fills the POJO and send it to the client or pass it by value. For client, transfer object is read-only. Client can create its own transfer object and pass it to server to update values in database in one shot. Following are the entities of this type of design pattern." }, { "code": null, "e": 110093, "s": 110015, "text": "Business Object - Business Service which fills the Transfer Object with data." }, { "code": null, "e": 110171, "s": 110093, "text": "Business Object - Business Service which fills the Transfer Object with data." }, { "code": null, "e": 110244, "s": 110171, "text": "Transfer Object -Simple POJO, having methods to set/get attributes only." }, { "code": null, "e": 110317, "s": 110244, "text": "Transfer Object -Simple POJO, having methods to set/get attributes only." }, { "code": null, "e": 110398, "s": 110317, "text": "Client - Client either requests or sends the Transfer Object to Business Object." }, { "code": null, "e": 110479, "s": 110398, "text": "Client - Client either requests or sends the Transfer Object to Business Object." }, { "code": null, "e": 110587, "s": 110479, "text": "We're going to create a StudentBO as Business Object,Student as Transfer Object representing our entities.\n" }, { "code": null, "e": 110739, "s": 110587, "text": "TransferObjectPatternDemo, our demo class is acting as a client here and will use StudentBO and Student to demonstrate Transfer Object Design Pattern." }, { "code": null, "e": 110763, "s": 110739, "text": "Create Transfer Object." }, { "code": null, "e": 110778, "s": 110763, "text": "StudentVO.java" }, { "code": null, "e": 111199, "s": 110778, "text": "public class StudentVO {\n private String name;\n private int rollNo;\n\n StudentVO(String name, int rollNo){\n this.name = name;\n this.rollNo = rollNo;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public int getRollNo() {\n return rollNo;\n }\n\n public void setRollNo(int rollNo) {\n this.rollNo = rollNo;\n }\n}" }, { "code": null, "e": 111223, "s": 111199, "text": "Create Business Object." }, { "code": null, "e": 111238, "s": 111223, "text": "StudentBO.java" }, { "code": null, "e": 112264, "s": 111238, "text": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class StudentBO {\n\t\n //list is working as a database\n List<StudentVO> students;\n\n public StudentBO(){\n students = new ArrayList<StudentVO>();\n StudentVO student1 = new StudentVO(\"Robert\",0);\n StudentVO student2 = new StudentVO(\"John\",1);\n students.add(student1);\n students.add(student2);\t\t\n }\n public void deleteStudent(StudentVO student) {\n students.remove(student.getRollNo());\n System.out.println(\"Student: Roll No \" \n + student.getRollNo() +\", deleted from database\");\n }\n\n //retrive list of students from the database\n public List<StudentVO> getAllStudents() {\n return students;\n }\n\n public StudentVO getStudent(int rollNo) {\n return students.get(rollNo);\n }\n\n public void updateStudent(StudentVO student) {\n students.get(student.getRollNo()).setName(student.getName());\n System.out.println(\"Student: Roll No \" \n + student.getRollNo() +\", updated in the database\");\n }\n}" }, { "code": null, "e": 112329, "s": 112264, "text": "Use the StudentBO to demonstrate Transfer Object Design Pattern." }, { "code": null, "e": 112360, "s": 112329, "text": "TransferObjectPatternDemo.java" }, { "code": null, "e": 113096, "s": 112360, "text": "public class TransferObjectPatternDemo {\n public static void main(String[] args) {\n StudentBO studentBusinessObject = new StudentBO();\n\n //print all students\n for (StudentVO student : studentBusinessObject.getAllStudents()) {\n System.out.println(\"Student: [RollNo : \"\n +student.getRollNo()+\", Name : \"+student.getName()+\" ]\");\n }\n\n //update student\n StudentVO student =studentBusinessObject.getAllStudents().get(0);\n student.setName(\"Michael\");\n studentBusinessObject.updateStudent(student);\n\n //get the student\n studentBusinessObject.getStudent(0);\n System.out.println(\"Student: [RollNo : \"\n +student.getRollNo()+\", Name : \"+student.getName()+\" ]\");\n }\n}" }, { "code": null, "e": 113115, "s": 113096, "text": "Verify the output." }, { "code": null, "e": 113273, "s": 113115, "text": "Student: [RollNo : 0, Name : Robert ]\nStudent: [RollNo : 1, Name : John ]\nStudent: Roll No 0, updated in the database\nStudent: [RollNo : 0, Name : Michael ]\n" }, { "code": null, "e": 113308, "s": 113273, "text": "\n 102 Lectures \n 10 hours \n" }, { "code": null, "e": 113327, "s": 113308, "text": " Arnab Chakraborty" }, { "code": null, "e": 113360, "s": 113327, "text": "\n 30 Lectures \n 3 hours \n" }, { "code": null, "e": 113379, "s": 113360, "text": " Arnab Chakraborty" }, { "code": null, "e": 113412, "s": 113379, "text": "\n 31 Lectures \n 4 hours \n" }, { "code": null, "e": 113431, "s": 113412, "text": " Arnab Chakraborty" }, { "code": null, "e": 113466, "s": 113431, "text": "\n 43 Lectures \n 1.5 hours \n" }, { "code": null, "e": 113479, "s": 113466, "text": " Manoj Kumar" }, { "code": null, "e": 113511, "s": 113479, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 113524, "s": 113511, "text": " Zach Miller" }, { "code": null, "e": 113557, "s": 113524, "text": "\n 54 Lectures \n 4 hours \n" }, { "code": null, "e": 113571, "s": 113557, "text": " Sasha Miller" }, { "code": null, "e": 113578, "s": 113571, "text": " Print" }, { "code": null, "e": 113589, "s": 113578, "text": " Add Notes" } ]
List View - Function based Views Django - GeeksforGeeks
27 Aug, 2021 List View refers to a view (logic) to list all or particular instances of a table from the database in a particular order. It is used to display multiple types of data on a single page or view, for example, products on an eCommerce page. Django provides extra-ordinary support for List Views but let’s check how it is done manually through a function-based view. This article revolves around list View which involves concepts such as Django Forms, Django Models. For List View, we need a project with some models and multiple instances which will be displayed. Illustration of How to create and use List view 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 ? After you have a project and an app, let’s create a model of which we will be creating instances through our view. In geeks/models.py, Python3 # import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name "GeeksModel"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title After creating this model, we need to run two commands in order to create Database for the same. Python manage.py makemigrations Python manage.py migrate Now let’s create some instances of this model using shell, run form bash, Python manage.py shell Enter following commands >>> from geeks.models import GeeksModel >>> GeeksModel.objects.create( title="title1", description="description1").save() >>> GeeksModel.objects.create( title="title2", description="description2").save() >>> GeeksModel.objects.create( title="title2", description="description2").save() Now we have everything ready for back end. Verify that instances have been created from http://localhost:8000/admin/geeks/geeksmodel/ Let’s create a view and template for the same. In geeks/views.py, Python3 from django.shortcuts import render # relative import of formsfrom .models import GeeksModel def list_view(request): # dictionary for initial data with # field names as keys context ={} # add the dictionary during initialization context["dataset"] = GeeksModel.objects.all() return render(request, "list_view.html", context) Create a template in templates/list_view.html, html <div class="main"> {% for data in dataset %}. {{ data.title }}<br/> {{ data.description }}<br/> <hr/> {% endfor %} </div> Let’s check what is there on http://localhost:8000/ Bingo..!! list view is working fine. One can also display filtered items or order them in different orders based on various features. Let’s order the items in reverse manner. In geeks/views.py, Python3 from django.shortcuts import render # relative import of modelsfrom .models import GeeksModel def list_view(request): # dictionary for initial data with # field names as keys context ={} # add the dictionary during initialization context["dataset"] = GeeksModel.objects.all().order_by("-id") return render(request, "list_view.html", context) Now visit http://localhost:8000/ Let’s create a different instance to show how filter works. Run Python manage.py shell Now, create another instance, from geeks.models import GeeksModel GeeksModel.objects.create(title = "Naveen", description = "GFG is Best").save() Now visit http://localhost:8000/ Let’s filter this data to those containing word “title” in their title. In geeks/views.py, Python3 from django.shortcuts import render # relative import of formsfrom .models import GeeksModel def list_view(request): # dictionary for initial data with # field names as keys context ={} # add the dictionary during initialization context["dataset"] = GeeksModel.objects.all().filter( title__icontains = "title" ) return render(request, "list_view.html", context) Now visit http://localhost:8000/ again, sumitgumber28 sagar0719kumar Django-views Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Create a Pandas DataFrame from Lists Python String | replace() *args and **kwargs in Python How to drop one or multiple columns in Pandas Dataframe sum() function in Python Python OOPs Concepts
[ { "code": null, "e": 24292, "s": 24264, "text": "\n27 Aug, 2021" }, { "code": null, "e": 24854, "s": 24292, "text": "List View refers to a view (logic) to list all or particular instances of a table from the database in a particular order. It is used to display multiple types of data on a single page or view, for example, products on an eCommerce page. Django provides extra-ordinary support for List Views but let’s check how it is done manually through a function-based view. This article revolves around list View which involves concepts such as Django Forms, Django Models. For List View, we need a project with some models and multiple instances which will be displayed. " }, { "code": null, "e": 24988, "s": 24854, "text": "Illustration of How to create and use List view using an Example. Consider a project named geeksforgeeks having an app named geeks. " }, { "code": null, "e": 25077, "s": 24988, "text": "Refer to the following articles to check how to create a project and an app in Django. " }, { "code": null, "e": 25128, "s": 25077, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 25161, "s": 25128, "text": "How to Create an App in Django ?" }, { "code": null, "e": 25298, "s": 25161, "text": "After you have a project and an app, let’s create a model of which we will be creating instances through our view. In geeks/models.py, " }, { "code": null, "e": 25306, "s": 25298, "text": "Python3" }, { "code": "# import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name \"GeeksModel\"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title", "e": 25694, "s": 25306, "text": null }, { "code": null, "e": 25793, "s": 25694, "text": "After creating this model, we need to run two commands in order to create Database for the same. " }, { "code": null, "e": 25850, "s": 25793, "text": "Python manage.py makemigrations\nPython manage.py migrate" }, { "code": null, "e": 25926, "s": 25850, "text": "Now let’s create some instances of this model using shell, run form bash, " }, { "code": null, "e": 25949, "s": 25926, "text": "Python manage.py shell" }, { "code": null, "e": 25976, "s": 25949, "text": "Enter following commands " }, { "code": null, "e": 26400, "s": 25976, "text": ">>> from geeks.models import GeeksModel\n>>> GeeksModel.objects.create(\n title=\"title1\",\n description=\"description1\").save()\n>>> GeeksModel.objects.create(\n title=\"title2\",\n description=\"description2\").save()\n>>> GeeksModel.objects.create(\n title=\"title2\",\n description=\"description2\").save()" }, { "code": null, "e": 26536, "s": 26400, "text": "Now we have everything ready for back end. Verify that instances have been created from http://localhost:8000/admin/geeks/geeksmodel/ " }, { "code": null, "e": 26603, "s": 26536, "text": "Let’s create a view and template for the same. In geeks/views.py, " }, { "code": null, "e": 26611, "s": 26603, "text": "Python3" }, { "code": "from django.shortcuts import render # relative import of formsfrom .models import GeeksModel def list_view(request): # dictionary for initial data with # field names as keys context ={} # add the dictionary during initialization context[\"dataset\"] = GeeksModel.objects.all() return render(request, \"list_view.html\", context)", "e": 26965, "s": 26611, "text": null }, { "code": null, "e": 27014, "s": 26965, "text": "Create a template in templates/list_view.html, " }, { "code": null, "e": 27019, "s": 27014, "text": "html" }, { "code": "<div class=\"main\"> {% for data in dataset %}. {{ data.title }}<br/> {{ data.description }}<br/> <hr/> {% endfor %} </div>", "e": 27159, "s": 27019, "text": null }, { "code": null, "e": 27213, "s": 27159, "text": "Let’s check what is there on http://localhost:8000/ " }, { "code": null, "e": 27409, "s": 27213, "text": "Bingo..!! list view is working fine. One can also display filtered items or order them in different orders based on various features. Let’s order the items in reverse manner. In geeks/views.py, " }, { "code": null, "e": 27417, "s": 27409, "text": "Python3" }, { "code": "from django.shortcuts import render # relative import of modelsfrom .models import GeeksModel def list_view(request): # dictionary for initial data with # field names as keys context ={} # add the dictionary during initialization context[\"dataset\"] = GeeksModel.objects.all().order_by(\"-id\") return render(request, \"list_view.html\", context)", "e": 27788, "s": 27417, "text": null }, { "code": null, "e": 27823, "s": 27788, "text": "Now visit http://localhost:8000/ " }, { "code": null, "e": 27891, "s": 27825, "text": "Let’s create a different instance to show how filter works. Run " }, { "code": null, "e": 27914, "s": 27891, "text": "Python manage.py shell" }, { "code": null, "e": 27946, "s": 27914, "text": "Now, create another instance, " }, { "code": null, "e": 28062, "s": 27946, "text": "from geeks.models import GeeksModel\nGeeksModel.objects.create(title = \"Naveen\", description = \"GFG is Best\").save()" }, { "code": null, "e": 28097, "s": 28062, "text": "Now visit http://localhost:8000/ " }, { "code": null, "e": 28190, "s": 28097, "text": "Let’s filter this data to those containing word “title” in their title. In geeks/views.py, " }, { "code": null, "e": 28198, "s": 28190, "text": "Python3" }, { "code": "from django.shortcuts import render # relative import of formsfrom .models import GeeksModel def list_view(request): # dictionary for initial data with # field names as keys context ={} # add the dictionary during initialization context[\"dataset\"] = GeeksModel.objects.all().filter( title__icontains = \"title\" ) return render(request, \"list_view.html\", context)", "e": 28599, "s": 28198, "text": null }, { "code": null, "e": 28641, "s": 28599, "text": "Now visit http://localhost:8000/ again, " }, { "code": null, "e": 28657, "s": 28643, "text": "sumitgumber28" }, { "code": null, "e": 28672, "s": 28657, "text": "sagar0719kumar" }, { "code": null, "e": 28685, "s": 28672, "text": "Django-views" }, { "code": null, "e": 28699, "s": 28685, "text": "Python Django" }, { "code": null, "e": 28706, "s": 28699, "text": "Python" }, { "code": null, "e": 28804, "s": 28706, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28813, "s": 28804, "text": "Comments" }, { "code": null, "e": 28826, "s": 28813, "text": "Old Comments" }, { "code": null, "e": 28844, "s": 28826, "text": "Python Dictionary" }, { "code": null, "e": 28876, "s": 28844, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28898, "s": 28876, "text": "Enumerate() in Python" }, { "code": null, "e": 28940, "s": 28898, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28977, "s": 28940, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29003, "s": 28977, "text": "Python String | replace()" }, { "code": null, "e": 29032, "s": 29003, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29088, "s": 29032, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29113, "s": 29088, "text": "sum() function in Python" } ]
Batch Script - Printing
Printing can also be controlled from within Batch Script via the NET PRINT command. PRINT [/D:device] [[drive:][path]filename[...]] Where /D:device - Specifies a print device. print c:\example.txt /c /d:lpt1 The above command will print the example.txt file to the parallel port lpt1. As of Windows 2000, many, but not all, printer settings can be configured from Windows's command line using PRINTUI.DLL and RUNDLL32.EXE RUNDLL32.EXE PRINTUI.DLL,PrintUIEntry [ options ] [ @commandfile ] Where some of the options available are the following − /dl − Delete local printer. /dl − Delete local printer. /dn − Delete network printer connection. /dn − Delete network printer connection. /dd − Delete printer driver. /dd − Delete printer driver. /e − Display printing preferences. /e − Display printing preferences. /f[file] − Either inf file or output file. /f[file] − Either inf file or output file. /F[file] − Location of an INF file that the INF file specified with /f may depend on. /F[file] − Location of an INF file that the INF file specified with /f may depend on. /ia − Install printer driver using inf file. /ia − Install printer driver using inf file. /id − Install printer driver using add printer driver wizard. /id − Install printer driver using add printer driver wizard. /if − Install printer using inf file. /if − Install printer using inf file. /ii − Install printer using add printer wizard with an inf file. /ii − Install printer using add printer wizard with an inf file. /il − Install printer using add printer wizard. /il − Install printer using add printer wizard. /in − Add network printer connection. /in − Add network printer connection. /ip − Install printer using network printer installation wizard. /ip − Install printer using network printer installation wizard. /k − Print test page to specified printer, cannot be combined with command when installing a printer. /k − Print test page to specified printer, cannot be combined with command when installing a printer. /l[path] − Printer driver source path. /l[path] − Printer driver source path. /m[model] − Printer driver model name. /m[model] − Printer driver model name. /n[name] − Printer name. /n[name] − Printer name. /o − Display printer queue view. /o − Display printer queue view. /p − Display printer properties. /p − Display printer properties. /Ss − Store printer settings into a file. /Ss − Store printer settings into a file. /Sr − Restore printer settings from a file. /Sr − Restore printer settings from a file. /y − Set printer as the default. /y − Set printer as the default. /Xg − Get printer settings. /Xg − Get printer settings. /Xs − Set printer settings. /Xs − Set printer settings. There can be cases wherein you might be connected to a network printer instead of a local printer. In such cases, it is always beneficial to check if a printer exists in the first place before printing. The existence of a printer can be evaluated with the help of the RUNDLL32.EXE PRINTUI.DLL which is used to control most of the printer settings. SET PrinterName = Test Printer SET file=%TEMP%\Prt.txt RUNDLL32.EXE PRINTUI.DLL,PrintUIEntry /Xg /n "%PrinterName%" /f "%file%" /q IF EXIST "%file%" ( ECHO %PrinterName% printer exists ) ELSE ( ECHO %PrinterName% printer does NOT exists ) The above command will do the following − It will first set the printer name and set a file name which will hold the settings of the printer. It will first set the printer name and set a file name which will hold the settings of the printer. The RUNDLL32.EXE PRINTUI.DLL commands will be used to check if the printer actually exists by sending the configuration settings of the file to the file Prt.txt The RUNDLL32.EXE PRINTUI.DLL commands will be used to check if the printer actually exists by sending the configuration settings of the file to the file Prt.txt Print Add Notes Bookmark this page
[ { "code": null, "e": 2253, "s": 2169, "text": "Printing can also be controlled from within Batch Script via the NET PRINT command." }, { "code": null, "e": 2302, "s": 2253, "text": "PRINT [/D:device] [[drive:][path]filename[...]]\n" }, { "code": null, "e": 2346, "s": 2302, "text": "Where /D:device - Specifies a print device." }, { "code": null, "e": 2378, "s": 2346, "text": "print c:\\example.txt /c /d:lpt1" }, { "code": null, "e": 2455, "s": 2378, "text": "The above command will print the example.txt file to the parallel port lpt1." }, { "code": null, "e": 2592, "s": 2455, "text": "As of Windows 2000, many, but not all, printer settings can be configured from Windows's command line using PRINTUI.DLL and RUNDLL32.EXE" }, { "code": null, "e": 2660, "s": 2592, "text": "RUNDLL32.EXE PRINTUI.DLL,PrintUIEntry [ options ] [ @commandfile ]\n" }, { "code": null, "e": 2716, "s": 2660, "text": "Where some of the options available are the following −" }, { "code": null, "e": 2744, "s": 2716, "text": "/dl − Delete local printer." }, { "code": null, "e": 2772, "s": 2744, "text": "/dl − Delete local printer." }, { "code": null, "e": 2813, "s": 2772, "text": "/dn − Delete network printer connection." }, { "code": null, "e": 2854, "s": 2813, "text": "/dn − Delete network printer connection." }, { "code": null, "e": 2883, "s": 2854, "text": "/dd − Delete printer driver." }, { "code": null, "e": 2912, "s": 2883, "text": "/dd − Delete printer driver." }, { "code": null, "e": 2947, "s": 2912, "text": "/e − Display printing preferences." }, { "code": null, "e": 2982, "s": 2947, "text": "/e − Display printing preferences." }, { "code": null, "e": 3025, "s": 2982, "text": "/f[file] − Either inf file or output file." }, { "code": null, "e": 3068, "s": 3025, "text": "/f[file] − Either inf file or output file." }, { "code": null, "e": 3154, "s": 3068, "text": "/F[file] − Location of an INF file that the INF file specified with /f may depend on." }, { "code": null, "e": 3240, "s": 3154, "text": "/F[file] − Location of an INF file that the INF file specified with /f may depend on." }, { "code": null, "e": 3285, "s": 3240, "text": "/ia − Install printer driver using inf file." }, { "code": null, "e": 3330, "s": 3285, "text": "/ia − Install printer driver using inf file." }, { "code": null, "e": 3392, "s": 3330, "text": "/id − Install printer driver using add printer driver wizard." }, { "code": null, "e": 3454, "s": 3392, "text": "/id − Install printer driver using add printer driver wizard." }, { "code": null, "e": 3492, "s": 3454, "text": "/if − Install printer using inf file." }, { "code": null, "e": 3530, "s": 3492, "text": "/if − Install printer using inf file." }, { "code": null, "e": 3595, "s": 3530, "text": "/ii − Install printer using add printer wizard with an inf file." }, { "code": null, "e": 3660, "s": 3595, "text": "/ii − Install printer using add printer wizard with an inf file." }, { "code": null, "e": 3708, "s": 3660, "text": "/il − Install printer using add printer wizard." }, { "code": null, "e": 3756, "s": 3708, "text": "/il − Install printer using add printer wizard." }, { "code": null, "e": 3794, "s": 3756, "text": "/in − Add network printer connection." }, { "code": null, "e": 3832, "s": 3794, "text": "/in − Add network printer connection." }, { "code": null, "e": 3897, "s": 3832, "text": "/ip − Install printer using network printer installation wizard." }, { "code": null, "e": 3962, "s": 3897, "text": "/ip − Install printer using network printer installation wizard." }, { "code": null, "e": 4064, "s": 3962, "text": "/k − Print test page to specified printer, cannot be combined with command when installing a printer." }, { "code": null, "e": 4166, "s": 4064, "text": "/k − Print test page to specified printer, cannot be combined with command when installing a printer." }, { "code": null, "e": 4205, "s": 4166, "text": "/l[path] − Printer driver source path." }, { "code": null, "e": 4244, "s": 4205, "text": "/l[path] − Printer driver source path." }, { "code": null, "e": 4283, "s": 4244, "text": "/m[model] − Printer driver model name." }, { "code": null, "e": 4322, "s": 4283, "text": "/m[model] − Printer driver model name." }, { "code": null, "e": 4347, "s": 4322, "text": "/n[name] − Printer name." }, { "code": null, "e": 4372, "s": 4347, "text": "/n[name] − Printer name." }, { "code": null, "e": 4405, "s": 4372, "text": "/o − Display printer queue view." }, { "code": null, "e": 4438, "s": 4405, "text": "/o − Display printer queue view." }, { "code": null, "e": 4471, "s": 4438, "text": "/p − Display printer properties." }, { "code": null, "e": 4504, "s": 4471, "text": "/p − Display printer properties." }, { "code": null, "e": 4546, "s": 4504, "text": "/Ss − Store printer settings into a file." }, { "code": null, "e": 4588, "s": 4546, "text": "/Ss − Store printer settings into a file." }, { "code": null, "e": 4632, "s": 4588, "text": "/Sr − Restore printer settings from a file." }, { "code": null, "e": 4676, "s": 4632, "text": "/Sr − Restore printer settings from a file." }, { "code": null, "e": 4709, "s": 4676, "text": "/y − Set printer as the default." }, { "code": null, "e": 4742, "s": 4709, "text": "/y − Set printer as the default." }, { "code": null, "e": 4770, "s": 4742, "text": "/Xg − Get printer settings." }, { "code": null, "e": 4798, "s": 4770, "text": "/Xg − Get printer settings." }, { "code": null, "e": 4826, "s": 4798, "text": "/Xs − Set printer settings." }, { "code": null, "e": 4854, "s": 4826, "text": "/Xs − Set printer settings." }, { "code": null, "e": 5057, "s": 4854, "text": "There can be cases wherein you might be connected to a network printer instead of a local printer. In such cases, it is always beneficial to check if a printer exists in the first place before printing." }, { "code": null, "e": 5202, "s": 5057, "text": "The existence of a printer can be evaluated with the help of the RUNDLL32.EXE PRINTUI.DLL which is used to control most of the printer settings." }, { "code": null, "e": 5448, "s": 5202, "text": "SET PrinterName = Test Printer\nSET file=%TEMP%\\Prt.txt\nRUNDLL32.EXE PRINTUI.DLL,PrintUIEntry /Xg /n \"%PrinterName%\" /f \"%file%\" /q\n\nIF EXIST \"%file%\" (\n ECHO %PrinterName% printer exists\n) ELSE (\n ECHO %PrinterName% printer does NOT exists\n)" }, { "code": null, "e": 5490, "s": 5448, "text": "The above command will do the following −" }, { "code": null, "e": 5590, "s": 5490, "text": "It will first set the printer name and set a file name which will hold the settings of the printer." }, { "code": null, "e": 5690, "s": 5590, "text": "It will first set the printer name and set a file name which will hold the settings of the printer." }, { "code": null, "e": 5851, "s": 5690, "text": "The RUNDLL32.EXE PRINTUI.DLL commands will be used to check if the printer actually exists by sending the configuration settings of the file to the file Prt.txt" }, { "code": null, "e": 6012, "s": 5851, "text": "The RUNDLL32.EXE PRINTUI.DLL commands will be used to check if the printer actually exists by sending the configuration settings of the file to the file Prt.txt" }, { "code": null, "e": 6019, "s": 6012, "text": " Print" }, { "code": null, "e": 6030, "s": 6019, "text": " Add Notes" } ]
Find average of each array within an array JavaScript
We are required to write a function getAverage() that accepts an array of arrays of numbers and we are required to return a new array of numbers that contains the average of corresponding subarrays. Let’s write the code for this. We will map over the original array, reducing the subarray to their averages like this − const arr = [[1,54,65,432,7,43,43, 54], [2,3], [4,5,6,7]]; const secondArr = [[545,65,5,7], [0,0,0,0], []]; const getAverage = (arr) => { const averageArray = arr.map(sub => { const { length } = sub; return sub.reduce((acc, val) => acc + (val/length), 0); }); return averageArray; } console.log(getAverage(arr)); console.log(getAverage(secondArr)); The output in the console will be − [ 87.375, 2.5, 5.5 ] [ 155.5, 0, 0 ]
[ { "code": null, "e": 1261, "s": 1062, "text": "We are required to write a function getAverage() that accepts an array of arrays of numbers and\nwe are required to return a new array of numbers that contains the average of corresponding\nsubarrays." }, { "code": null, "e": 1381, "s": 1261, "text": "Let’s write the code for this. We will map over the original array, reducing the subarray to their\naverages like this −" }, { "code": null, "e": 1751, "s": 1381, "text": "const arr = [[1,54,65,432,7,43,43, 54], [2,3], [4,5,6,7]];\nconst secondArr = [[545,65,5,7], [0,0,0,0], []];\nconst getAverage = (arr) => {\n const averageArray = arr.map(sub => {\n const { length } = sub;\n return sub.reduce((acc, val) => acc + (val/length), 0);\n });\n return averageArray;\n}\nconsole.log(getAverage(arr));\nconsole.log(getAverage(secondArr));" }, { "code": null, "e": 1787, "s": 1751, "text": "The output in the console will be −" }, { "code": null, "e": 1824, "s": 1787, "text": "[ 87.375, 2.5, 5.5 ]\n[ 155.5, 0, 0 ]" } ]
How to Use Poisson Distribution like You Know What You Are Doing | Towards Data Science
You have been freelancing for 10 years now. So far, your average annual income was about 80,000$. This year, you feel like you are stuck in a rut and decide to hit 6 figures. To do that, you want to start by calculating the probability of this exciting achievement happening but you don’t know how to do so. Turns out, you are not alone. In the world, there are many scenarios where there is a known rate of some random event and businesses want to find the chance of the event happening more or less than this rate in the future. For example, retailer owners who already know their average sales would try to guess how much more they would make on special days such as on Black Fridays or Cyber Mondays. This would help them to store more products and manage their staff accordingly. In this post, we will talk about the intuition behind the Poisson distribution which is used to model situations like above, how to understand and use its formula, and how to simulate it using Python code. This post assumes you have a basic understanding of probability. If not, please check out this great article. Before we get to the real meat of the post, we will build some understanding of discrete probability distributions. First, let’s define what we mean by discrete. In descriptive statistics, discrete data is any data that is recorded or collected by counting, i. e. integers. Examples are test scores, the number of cars in a parking lot, the number of childbirths in a hospital, etc. Then, there are random experiments that have discrete outcomes. For example, a coin flip has two outcomes: heads and tails (1 and 0), rolling a die has 6 discrete outcomes, and so on. If a random variable X is used to store possible outcomes of a discrete experiment, it will have a discrete probability distribution. Probability distribution records all possible outcomes of a random experiment. As a trivial example, let’s build the distribution of a single coin flip: That was easy. If we want to record the distribution programmatically, it would be in the form of a Python list or Numpy array: However, you can imagine that for large experiments that have many possible outcomes, building the distribution and finding the probabilities in this way becomes impossible. Thankfully, every probability distribution ever invented comes with its own formula to calculate any outcome’s probability. For discrete probability distributions, these functions are called Probability Mass Functions (PMF). For a more detailed explanation, read my previous post on discrete distributions. We will start understanding the Poisson distribution using a case study. Say you really love watching new-born babies in a hospital. From your observations and reports, you know the hospital observes 6 new-born babies every hour on average. You find out that you have to go on a business trip tomorrow, so before leaving for the airport, you want to visit the hospital for the last time. Since you will be gone for months, you want to see as many new babies as possible so you wonder about the chance of seeing 10 babies or more an hour before your flight. If we consider observing new-born babies as a random experiment, the outcomes would follow a classic Poisson distribution. The reason is that it holds all the conditions required for a Poisson distribution: There is a known rate of events: 6 new babies every hour on average Events occur independently: 1 baby being born does not affect the timing of the next The known rate is constant over time: the average number of babies per hour does not change over time Two events do not happen at exactly the same instant (Reminder: each outcome is discrete) Poisson distribution has many important business implications. Businesses often use it to make forecasts about the number of sales or customers occurring on a particular day given that they know the average daily rate. Making such forecasts helps businesses to make better decisions about production, scheduling, or staffing. For example, overstocking means losses for low activity in sales or not having enough goods means lost business opportunity. In short, Poisson distribution helps find the probability of an event happening more or less than the already recorded rate (often notated as λ (lambda)) in a fixed time interval. Its Probability Mass Function is given by this formula: where k is the number of successes (the number of times a desired even happening) λ is the given rate e is Euler’s number: e = 2.71828... k! is the factorial of k If you are still uncomfortable with PMFs, read my previous post. Using this formula, we can find the probability of seeing 10 new-born babies knowing that the average rate is 6: Unfortunately, there is only ~4% percent chance of seeing 10 babies. We won’t go into the detail of how the formula is derived but if you are curious, watch this video by Khan Academy. There are still some points you have to keep in mind. Even though there is a known rate, it is just an average, so the timing of the events can be completely random. For example, you can observe 2 babies born back-to-back or you may end up waiting for half an hour for the next. Also, in practice, the rate λ may not always be constant. This can even be true for our new-born babies experiment. Even though this condition fails, we can still consider the distribution as Poisson because Poisson distribution is close enough to model the situation’s behavior. Simulating or drawing samples from Poisson distribution is very easy using numpy. We first import it and use its random module for simulation: import numpy as np To draw samples from a Poisson distribution, we only need the rate parameter λ. We will plug it into np.random.poisson function and specify the number of samples: poisson = np.random.poisson(lam=10, size=10000) Here, we are simulating a distribution with a rate of 10 and has 10k data points. To see this distribution, we will plot the results of its PMF. Though we could do it by hand, there is already a very good library called empiricaldist, written by Allen B. Downey - author of well-known books such as ThinkPython and ThinkStats. We will install and import its Pmf function into our environment: from empiricaldist import Pmf # pip install empiricaldist Pmf has a function called from_seq which takes any distribution and computes the PMF: poisson = np.random.poisson(lam=10, size=10000)pmf_poisson = Pmf.from_seq(poisson)pmf_poisson Recall that PMF shows the probabilities of each unique outcome, so in the above result, the outcomes are given as index and probabilities under probs. Let's plot it using matplotlib: As expected, the highest probability is for the mean (rate parameter, λ). Now, let’s assume that we forgot the formula for the PMF of Poisson distribution. If we were doing our experiment of observing new-born babies, how would we find the probability of seeing 10 new babies with a rate of 6? Well, to start off, we simulate the perfect Poisson distribution with our given rate as a parameter. Also, we make sure to draw a lot of samples for better accuracy: We are sampling a distribution with a rate of 6 and a length of 1 million. Next, we find how many of them got 10 babies: So, we observed 10 babies in 41114 trials (each hour can be considered to have one trial). Then, we divide this number by the total amount of samples: >>> births_10 / 1e60.041114 If you recall, using the PMF formula, the result was 0.0413 and we can see that our hand-coded solution is a pretty close match. There is still much to be said about Poisson distribution. We covered the basic usage and its implications in the business world. There are still interesting parts of Poisson distribution such as how it relates to Binomial distribution. For a full understanding, I would recommend reading these high-quality articles which also helped in my understanding of the topic: Article by Brilliant.org Post by one of my favorite authors on Medium, Will Koehrsen Article by Statisticshowto.com As always😊, the Wikipedia page Numpy documentation of np.random.poisson
[ { "code": null, "e": 480, "s": 172, "text": "You have been freelancing for 10 years now. So far, your average annual income was about 80,000$. This year, you feel like you are stuck in a rut and decide to hit 6 figures. To do that, you want to start by calculating the probability of this exciting achievement happening but you don’t know how to do so." }, { "code": null, "e": 703, "s": 480, "text": "Turns out, you are not alone. In the world, there are many scenarios where there is a known rate of some random event and businesses want to find the chance of the event happening more or less than this rate in the future." }, { "code": null, "e": 957, "s": 703, "text": "For example, retailer owners who already know their average sales would try to guess how much more they would make on special days such as on Black Fridays or Cyber Mondays. This would help them to store more products and manage their staff accordingly." }, { "code": null, "e": 1163, "s": 957, "text": "In this post, we will talk about the intuition behind the Poisson distribution which is used to model situations like above, how to understand and use its formula, and how to simulate it using Python code." }, { "code": null, "e": 1273, "s": 1163, "text": "This post assumes you have a basic understanding of probability. If not, please check out this great article." }, { "code": null, "e": 1389, "s": 1273, "text": "Before we get to the real meat of the post, we will build some understanding of discrete probability distributions." }, { "code": null, "e": 1656, "s": 1389, "text": "First, let’s define what we mean by discrete. In descriptive statistics, discrete data is any data that is recorded or collected by counting, i. e. integers. Examples are test scores, the number of cars in a parking lot, the number of childbirths in a hospital, etc." }, { "code": null, "e": 1974, "s": 1656, "text": "Then, there are random experiments that have discrete outcomes. For example, a coin flip has two outcomes: heads and tails (1 and 0), rolling a die has 6 discrete outcomes, and so on. If a random variable X is used to store possible outcomes of a discrete experiment, it will have a discrete probability distribution." }, { "code": null, "e": 2053, "s": 1974, "text": "Probability distribution records all possible outcomes of a random experiment." }, { "code": null, "e": 2127, "s": 2053, "text": "As a trivial example, let’s build the distribution of a single coin flip:" }, { "code": null, "e": 2255, "s": 2127, "text": "That was easy. If we want to record the distribution programmatically, it would be in the form of a Python list or Numpy array:" }, { "code": null, "e": 2736, "s": 2255, "text": "However, you can imagine that for large experiments that have many possible outcomes, building the distribution and finding the probabilities in this way becomes impossible. Thankfully, every probability distribution ever invented comes with its own formula to calculate any outcome’s probability. For discrete probability distributions, these functions are called Probability Mass Functions (PMF). For a more detailed explanation, read my previous post on discrete distributions." }, { "code": null, "e": 2977, "s": 2736, "text": "We will start understanding the Poisson distribution using a case study. Say you really love watching new-born babies in a hospital. From your observations and reports, you know the hospital observes 6 new-born babies every hour on average." }, { "code": null, "e": 3293, "s": 2977, "text": "You find out that you have to go on a business trip tomorrow, so before leaving for the airport, you want to visit the hospital for the last time. Since you will be gone for months, you want to see as many new babies as possible so you wonder about the chance of seeing 10 babies or more an hour before your flight." }, { "code": null, "e": 3500, "s": 3293, "text": "If we consider observing new-born babies as a random experiment, the outcomes would follow a classic Poisson distribution. The reason is that it holds all the conditions required for a Poisson distribution:" }, { "code": null, "e": 3568, "s": 3500, "text": "There is a known rate of events: 6 new babies every hour on average" }, { "code": null, "e": 3653, "s": 3568, "text": "Events occur independently: 1 baby being born does not affect the timing of the next" }, { "code": null, "e": 3755, "s": 3653, "text": "The known rate is constant over time: the average number of babies per hour does not change over time" }, { "code": null, "e": 3808, "s": 3755, "text": "Two events do not happen at exactly the same instant" }, { "code": null, "e": 3845, "s": 3808, "text": "(Reminder: each outcome is discrete)" }, { "code": null, "e": 4296, "s": 3845, "text": "Poisson distribution has many important business implications. Businesses often use it to make forecasts about the number of sales or customers occurring on a particular day given that they know the average daily rate. Making such forecasts helps businesses to make better decisions about production, scheduling, or staffing. For example, overstocking means losses for low activity in sales or not having enough goods means lost business opportunity." }, { "code": null, "e": 4476, "s": 4296, "text": "In short, Poisson distribution helps find the probability of an event happening more or less than the already recorded rate (often notated as λ (lambda)) in a fixed time interval." }, { "code": null, "e": 4532, "s": 4476, "text": "Its Probability Mass Function is given by this formula:" }, { "code": null, "e": 4538, "s": 4532, "text": "where" }, { "code": null, "e": 4614, "s": 4538, "text": "k is the number of successes (the number of times a desired even happening)" }, { "code": null, "e": 4634, "s": 4614, "text": "λ is the given rate" }, { "code": null, "e": 4670, "s": 4634, "text": "e is Euler’s number: e = 2.71828..." }, { "code": null, "e": 4695, "s": 4670, "text": "k! is the factorial of k" }, { "code": null, "e": 4760, "s": 4695, "text": "If you are still uncomfortable with PMFs, read my previous post." }, { "code": null, "e": 4873, "s": 4760, "text": "Using this formula, we can find the probability of seeing 10 new-born babies knowing that the average rate is 6:" }, { "code": null, "e": 4942, "s": 4873, "text": "Unfortunately, there is only ~4% percent chance of seeing 10 babies." }, { "code": null, "e": 5058, "s": 4942, "text": "We won’t go into the detail of how the formula is derived but if you are curious, watch this video by Khan Academy." }, { "code": null, "e": 5337, "s": 5058, "text": "There are still some points you have to keep in mind. Even though there is a known rate, it is just an average, so the timing of the events can be completely random. For example, you can observe 2 babies born back-to-back or you may end up waiting for half an hour for the next." }, { "code": null, "e": 5617, "s": 5337, "text": "Also, in practice, the rate λ may not always be constant. This can even be true for our new-born babies experiment. Even though this condition fails, we can still consider the distribution as Poisson because Poisson distribution is close enough to model the situation’s behavior." }, { "code": null, "e": 5760, "s": 5617, "text": "Simulating or drawing samples from Poisson distribution is very easy using numpy. We first import it and use its random module for simulation:" }, { "code": null, "e": 5779, "s": 5760, "text": "import numpy as np" }, { "code": null, "e": 5942, "s": 5779, "text": "To draw samples from a Poisson distribution, we only need the rate parameter λ. We will plug it into np.random.poisson function and specify the number of samples:" }, { "code": null, "e": 5990, "s": 5942, "text": "poisson = np.random.poisson(lam=10, size=10000)" }, { "code": null, "e": 6383, "s": 5990, "text": "Here, we are simulating a distribution with a rate of 10 and has 10k data points. To see this distribution, we will plot the results of its PMF. Though we could do it by hand, there is already a very good library called empiricaldist, written by Allen B. Downey - author of well-known books such as ThinkPython and ThinkStats. We will install and import its Pmf function into our environment:" }, { "code": null, "e": 6442, "s": 6383, "text": "from empiricaldist import Pmf # pip install empiricaldist" }, { "code": null, "e": 6528, "s": 6442, "text": "Pmf has a function called from_seq which takes any distribution and computes the PMF:" }, { "code": null, "e": 6622, "s": 6528, "text": "poisson = np.random.poisson(lam=10, size=10000)pmf_poisson = Pmf.from_seq(poisson)pmf_poisson" }, { "code": null, "e": 6805, "s": 6622, "text": "Recall that PMF shows the probabilities of each unique outcome, so in the above result, the outcomes are given as index and probabilities under probs. Let's plot it using matplotlib:" }, { "code": null, "e": 6879, "s": 6805, "text": "As expected, the highest probability is for the mean (rate parameter, λ)." }, { "code": null, "e": 7099, "s": 6879, "text": "Now, let’s assume that we forgot the formula for the PMF of Poisson distribution. If we were doing our experiment of observing new-born babies, how would we find the probability of seeing 10 new babies with a rate of 6?" }, { "code": null, "e": 7265, "s": 7099, "text": "Well, to start off, we simulate the perfect Poisson distribution with our given rate as a parameter. Also, we make sure to draw a lot of samples for better accuracy:" }, { "code": null, "e": 7386, "s": 7265, "text": "We are sampling a distribution with a rate of 6 and a length of 1 million. Next, we find how many of them got 10 babies:" }, { "code": null, "e": 7537, "s": 7386, "text": "So, we observed 10 babies in 41114 trials (each hour can be considered to have one trial). Then, we divide this number by the total amount of samples:" }, { "code": null, "e": 7565, "s": 7537, "text": ">>> births_10 / 1e60.041114" }, { "code": null, "e": 7694, "s": 7565, "text": "If you recall, using the PMF formula, the result was 0.0413 and we can see that our hand-coded solution is a pretty close match." }, { "code": null, "e": 8063, "s": 7694, "text": "There is still much to be said about Poisson distribution. We covered the basic usage and its implications in the business world. There are still interesting parts of Poisson distribution such as how it relates to Binomial distribution. For a full understanding, I would recommend reading these high-quality articles which also helped in my understanding of the topic:" }, { "code": null, "e": 8088, "s": 8063, "text": "Article by Brilliant.org" }, { "code": null, "e": 8148, "s": 8088, "text": "Post by one of my favorite authors on Medium, Will Koehrsen" }, { "code": null, "e": 8179, "s": 8148, "text": "Article by Statisticshowto.com" }, { "code": null, "e": 8210, "s": 8179, "text": "As always😊, the Wikipedia page" } ]
Count of Leap Years in a given year range
09 Nov, 2021 Given two years L and R, the task is to find the total number of leap years possible in the range (L, R) inclusive.Examples: Input: L = 1, R = 400 Output: 97Input: L = 400, R = 2000 Output: 389 Naive Approach: The idea is to iterate through L to R and check if the year is a leap year or not using this approach. Time complexity: O(N)Efficient Approach: A year is a leap year if the following conditions are satisfied: Year is multiple of 400.Year is multiple of 4 and not multiple of 100.So calculate the numbers which satisfy above condition in range (1, L) and (1, R) by A year is a leap year if the following conditions are satisfied: Year is multiple of 400.Year is multiple of 4 and not multiple of 100. Year is multiple of 400. Year is multiple of 4 and not multiple of 100. So calculate the numbers which satisfy above condition in range (1, L) and (1, R) by Number of Leap years in (1, year) = (year / 4) – (year / 100) + (year / 400) Difference of the number of Leap years in range (1, R) with the number of leap years in range (1, L) will be the desired output. Difference of the number of Leap years in range (1, R) with the number of leap years in range (1, L) will be the desired output. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ implementation to find the // count of leap years in given// range of the year #include <bits/stdc++.h> using namespace std; // Function to calculate the number// of leap years in range of (1, year)int calNum(int year){ return (year / 4) - (year / 100) + (year / 400);} // Function to calculate the number// of leap years in given rangevoid leapNum(int l, int r){ l--; int num1 = calNum(r); int num2 = calNum(l); cout << num1 - num2 << endl;} // Driver Codeint main(){ int l1 = 1, r1 = 400; leapNum(l1, r1); int l2 = 400, r2 = 2000; leapNum(l2, r2); return 0;} // Java implementation to find the // count of leap years in given// range of the year class GFG{ // Function to calculate the number// of leap years in range of (1, year)static int calNum(int year){ return (year / 4) - (year / 100) + (year / 400);} // Function to calculate the number// of leap years in given rangestatic void leapNum(int l, int r){ l--; int num1 = calNum(r); int num2 = calNum(l); System.out.print(num1 - num2 +"\n");} // Driver Codepublic static void main(String[] args){ int l1 = 1, r1 = 400; leapNum(l1, r1); int l2 = 400, r2 = 2000; leapNum(l2, r2);}} // This code is contributed by PrinciRaj1992 # Python3 implementation to find the # count of leap years in given # range of the year # Function to calculate the number # of leap years in range of (1, year) def calNum(year) : return (year // 4) - (year // 100) + (year // 400) # Function to calculate the number # of leap years in given range def leapNum(l, r) : l -= 1 num1 = calNum(r) num2 = calNum(l) print(num1 - num2) # Driver Code if __name__ == "__main__" : l1 = 1 r1 = 400 leapNum(l1, r1) l2 = 400 r2 = 2000 leapNum(l2, r2) # This code is contributed by AnkitRai01 // C# implementation to find the // count of leap years in given// range of the year using System; class GFG{ // Function to calculate the number// of leap years in range of (1, year)static int calNum(int year){ return (year / 4) - (year / 100) + (year / 400);} // Function to calculate the number// of leap years in given rangestatic void leapNum(int l, int r){ l--; int num1 = calNum(r); int num2 = calNum(l); Console.Write(num1 - num2 +"\n");} // Driver Codepublic static void Main(String[] args){ int l1 = 1, r1 = 400; leapNum(l1, r1); int l2 = 400, r2 = 2000; leapNum(l2, r2);}} // This code is contributed by PrinciRaj1992 <script> // Javascript implementation to find the // count of leap years in given // range of the year // Function to calculate the number // of leap years in range of (1, year) function calNum(year) { return parseInt(year / 4, 10) - parseInt(year / 100, 10) + parseInt(year / 400, 10); } // Function to calculate the number // of leap years in given range function leapNum(l, r) { l--; let num1 = calNum(r); let num2 = calNum(l); document.write((num1 - num2) +"</br>"); } let l1 = 1, r1 = 400; leapNum(l1, r1); let l2 = 400, r2 = 2000; leapNum(l2, r2); // This code is contributed by divyeh072019.</script> 97 389 Time Complexity: O(1) princiraj1992 ankthon nidhi_biet divyesh072019 diyaroy22 Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n09 Nov, 2021" }, { "code": null, "e": 180, "s": 53, "text": "Given two years L and R, the task is to find the total number of leap years possible in the range (L, R) inclusive.Examples: " }, { "code": null, "e": 251, "s": 180, "text": "Input: L = 1, R = 400 Output: 97Input: L = 400, R = 2000 Output: 389 " }, { "code": null, "e": 415, "s": 253, "text": "Naive Approach: The idea is to iterate through L to R and check if the year is a leap year or not using this approach. Time complexity: O(N)Efficient Approach: " }, { "code": null, "e": 637, "s": 415, "text": "A year is a leap year if the following conditions are satisfied: Year is multiple of 400.Year is multiple of 4 and not multiple of 100.So calculate the numbers which satisfy above condition in range (1, L) and (1, R) by " }, { "code": null, "e": 773, "s": 637, "text": "A year is a leap year if the following conditions are satisfied: Year is multiple of 400.Year is multiple of 4 and not multiple of 100." }, { "code": null, "e": 798, "s": 773, "text": "Year is multiple of 400." }, { "code": null, "e": 845, "s": 798, "text": "Year is multiple of 4 and not multiple of 100." }, { "code": null, "e": 932, "s": 845, "text": "So calculate the numbers which satisfy above condition in range (1, L) and (1, R) by " }, { "code": null, "e": 1011, "s": 932, "text": "Number of Leap years in (1, year) = (year / 4) – (year / 100) + (year / 400) " }, { "code": null, "e": 1141, "s": 1011, "text": " Difference of the number of Leap years in range (1, R) with the number of leap years in range (1, L) will be the desired output." }, { "code": null, "e": 1272, "s": 1143, "text": "Difference of the number of Leap years in range (1, R) with the number of leap years in range (1, L) will be the desired output." }, { "code": null, "e": 1324, "s": 1272, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 1328, "s": 1324, "text": "C++" }, { "code": null, "e": 1333, "s": 1328, "text": "Java" }, { "code": null, "e": 1341, "s": 1333, "text": "Python3" }, { "code": null, "e": 1344, "s": 1341, "text": "C#" }, { "code": null, "e": 1355, "s": 1344, "text": "Javascript" }, { "code": "// C++ implementation to find the // count of leap years in given// range of the year #include <bits/stdc++.h> using namespace std; // Function to calculate the number// of leap years in range of (1, year)int calNum(int year){ return (year / 4) - (year / 100) + (year / 400);} // Function to calculate the number// of leap years in given rangevoid leapNum(int l, int r){ l--; int num1 = calNum(r); int num2 = calNum(l); cout << num1 - num2 << endl;} // Driver Codeint main(){ int l1 = 1, r1 = 400; leapNum(l1, r1); int l2 = 400, r2 = 2000; leapNum(l2, r2); return 0;}", "e": 1986, "s": 1355, "text": null }, { "code": "// Java implementation to find the // count of leap years in given// range of the year class GFG{ // Function to calculate the number// of leap years in range of (1, year)static int calNum(int year){ return (year / 4) - (year / 100) + (year / 400);} // Function to calculate the number// of leap years in given rangestatic void leapNum(int l, int r){ l--; int num1 = calNum(r); int num2 = calNum(l); System.out.print(num1 - num2 +\"\\n\");} // Driver Codepublic static void main(String[] args){ int l1 = 1, r1 = 400; leapNum(l1, r1); int l2 = 400, r2 = 2000; leapNum(l2, r2);}} // This code is contributed by PrinciRaj1992", "e": 2662, "s": 1986, "text": null }, { "code": "# Python3 implementation to find the # count of leap years in given # range of the year # Function to calculate the number # of leap years in range of (1, year) def calNum(year) : return (year // 4) - (year // 100) + (year // 400) # Function to calculate the number # of leap years in given range def leapNum(l, r) : l -= 1 num1 = calNum(r) num2 = calNum(l) print(num1 - num2) # Driver Code if __name__ == \"__main__\" : l1 = 1 r1 = 400 leapNum(l1, r1) l2 = 400 r2 = 2000 leapNum(l2, r2) # This code is contributed by AnkitRai01", "e": 3241, "s": 2662, "text": null }, { "code": "// C# implementation to find the // count of leap years in given// range of the year using System; class GFG{ // Function to calculate the number// of leap years in range of (1, year)static int calNum(int year){ return (year / 4) - (year / 100) + (year / 400);} // Function to calculate the number// of leap years in given rangestatic void leapNum(int l, int r){ l--; int num1 = calNum(r); int num2 = calNum(l); Console.Write(num1 - num2 +\"\\n\");} // Driver Codepublic static void Main(String[] args){ int l1 = 1, r1 = 400; leapNum(l1, r1); int l2 = 400, r2 = 2000; leapNum(l2, r2);}} // This code is contributed by PrinciRaj1992", "e": 3927, "s": 3241, "text": null }, { "code": "<script> // Javascript implementation to find the // count of leap years in given // range of the year // Function to calculate the number // of leap years in range of (1, year) function calNum(year) { return parseInt(year / 4, 10) - parseInt(year / 100, 10) + parseInt(year / 400, 10); } // Function to calculate the number // of leap years in given range function leapNum(l, r) { l--; let num1 = calNum(r); let num2 = calNum(l); document.write((num1 - num2) +\"</br>\"); } let l1 = 1, r1 = 400; leapNum(l1, r1); let l2 = 400, r2 = 2000; leapNum(l2, r2); // This code is contributed by divyeh072019.</script>", "e": 4642, "s": 3927, "text": null }, { "code": null, "e": 4649, "s": 4642, "text": "97\n389" }, { "code": null, "e": 4674, "s": 4651, "text": "Time Complexity: O(1) " }, { "code": null, "e": 4688, "s": 4674, "text": "princiraj1992" }, { "code": null, "e": 4696, "s": 4688, "text": "ankthon" }, { "code": null, "e": 4707, "s": 4696, "text": "nidhi_biet" }, { "code": null, "e": 4721, "s": 4707, "text": "divyesh072019" }, { "code": null, "e": 4731, "s": 4721, "text": "diyaroy22" }, { "code": null, "e": 4744, "s": 4731, "text": "Mathematical" }, { "code": null, "e": 4757, "s": 4744, "text": "Mathematical" } ]
Rotate the matrix right by K times
14 Jun, 2022 Given a matrix of size N*M, and a number K. We have to rotate the matrix K times to the right side. Examples: Input : N = 3, M = 3, K = 2 12 23 34 45 56 67 78 89 91 Output : 23 34 12 56 67 45 89 91 78 Input : N = 2, M = 2, K = 2 1 2 3 4 Output : 1 2 3 4 A simple yet effective approach is to consider each row of the matrix as an array and perform an array rotation. This can be done by copying the elements from K to end of array to starting of array using temporary array. And then the remaining elements from start to K-1 to end of the array.Lets take an example: C++ C Java Python3 C# PHP Javascript // CPP program to rotate a matrix right by k times#include <iostream> // size of matrix#define M 3#define N 3 using namespace std; // function to rotate matrix by k timesvoid rotateMatrix(int matrix[][M], int k) { // temporary array of size M int temp[M]; // within the size of matrix k = k % M; for (int i = 0; i < N; i++) { // copy first M-k elements to temporary array for (int t = 0; t < M - k; t++) temp[t] = matrix[i][t]; // copy the elements from k to end to starting for (int j = M - k; j < M; j++) matrix[i][j - M + k] = matrix[i][j]; // copy elements from temporary array to end for (int j = k; j < M; j++) matrix[i][j] = temp[j - k]; }} // function to display the matrixvoid displayMatrix(int matrix[][M]) { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) cout << matrix[i][j] << " "; cout << endl; }} // Driver's codeint main() { int matrix[N][M] = {{12, 23, 34}, {45, 56, 67}, {78, 89, 91}}; int k = 2; // rotate matrix by k rotateMatrix(matrix, k); // display rotated matrix displayMatrix(matrix); return 0;} // C program to rotate a matrix right by k times#include <stdio.h> // size of matrix#define M 3#define N 3 // function to rotate matrix by k timesvoid rotateMatrix(int matrix[][M], int k){ // temporary array of size M int temp[M]; // within the size of matrix k = k % M; for (int i = 0; i < N; i++) { // copy first M-k elements to temporary array for (int t = 0; t < M - k; t++) temp[t] = matrix[i][t]; // copy the elements from k to end to starting for (int j = M - k; j < M; j++) matrix[i][j - M + k] = matrix[i][j]; // copy elements from temporary array to end for (int j = k; j < M; j++) matrix[i][j] = temp[j - k]; }} // function to display the matrixvoid displayMatrix(int matrix[][M]) { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) printf("%d ",matrix[i][j]); printf("\n"); }} // Driver's codeint main() { int matrix[N][M] = {{12, 23, 34}, {45, 56, 67}, {78, 89, 91}}; int k = 2; // rotate matrix by k rotateMatrix(matrix, k); // display rotated matrix displayMatrix(matrix); return 0;} // This code is contributed by kothavvsaakash. // Java program to rotate a matrix// right by k times class GFG{ // size of matrix static final int M=3; static final int N=3; // function to rotate matrix by k times static void rotateMatrix(int matrix[][], int k) { // temporary array of size M int temp[]=new int[M]; // within the size of matrix k = k % M; for (int i = 0; i < N; i++) { // copy first M-k elements // to temporary array for (int t = 0; t < M - k; t++) temp[t] = matrix[i][t]; // copy the elements from k // to end to starting for (int j = M - k; j < M; j++) matrix[i][j - M + k] = matrix[i][j]; // copy elements from // temporary array to end for (int j = k; j < M; j++) matrix[i][j] = temp[j - k]; } } // function to display the matrix static void displayMatrix(int matrix[][]) { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) System.out.print(matrix[i][j] + " "); System.out.println(); } } // Driver code public static void main (String[] args) { int matrix[][] = {{12, 23, 34}, {45, 56, 67}, {78, 89, 91}}; int k = 2; // rotate matrix by k rotateMatrix(matrix, k); // display rotated matrix displayMatrix(matrix); }} // This code is contributed by Anant Agarwal. # Python program to rotate# a matrix right by k times # size of matrixM = 3N = 3matrix = [[12, 23, 34], [45, 56, 67], [78, 89, 91]] # function to rotate# matrix by k timesdef rotateMatrix(k) : global M, N, matrix # temporary array # of size M temp = [0] * M # within the size # of matrix k = k % M for i in range(0, N) : # copy first M-k elements # to temporary array for t in range(0, M - k) : temp[t] = matrix[i][t] # copy the elements from # k to end to starting for j in range(M - k, M) : matrix[i][j - M + k] = matrix[i][j] # copy elements from # temporary array to end for j in range(k, M) : matrix[i][j] = temp[j - k] # function to display# the matrixdef displayMatrix() : global M, N, matrix for i in range(0, N) : for j in range(0, M) : print ("{} " . format(matrix[i][j]), end = "") print () # Driver codek = 2 # rotate matrix by krotateMatrix(k) # display rotated matrixdisplayMatrix() # This code is contributed by# Manish Shaw(manishshaw1) // C# program to rotate a // matrix right by k timesusing System; class GFG { // size of matrix static int M=3; static int N=3; // function to rotate matrix by k times static void rotateMatrix(int [,] matrix, int k) { // temporary array of size M int [] temp=new int[M]; // within the size of matrix k = k % M; for (int i = 0; i < N; i++) { // copy first M-k elements // to temporary array for (int t = 0; t < M - k; t++) temp[t] = matrix[i, t]; // copy the elements from k // to end to starting for (int j = M - k; j < M; j++) matrix[i, j - M + k] = matrix[i, j]; // copy elements from // temporary array to end for (int j = k; j < M; j++) matrix[i, j] = temp[j - k]; } } // function to display the matrix static void displayMatrix(int [,] matrix) { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) Console.Write(matrix[i, j] + " "); Console.WriteLine(); } } // Driver code public static void Main () { int [,] matrix = {{12, 23, 34}, {45, 56, 67}, {78, 89, 91}}; int k = 2; // rotate matrix by k rotateMatrix(matrix, k); // display rotated matrix displayMatrix(matrix); }} // This code is contributed by KRV. <?php// PHP program to rotate// a matrix right by k times // size of matrix$M = 3;$N = 3; // function to rotate// matrix by k timesfunction rotateMatrix(&$matrix, $k){ global $M, $N; // temporary array // of size M $temp = array(); // within the size // of matrix $k = $k % $M; for ($i = 0; $i < $N; $i++) { // copy first M-k elements // to temporary array for ($t = 0; $t < $M - $k; $t++) $temp[$t] = $matrix[$i][$t]; // copy the elements from // k to end to starting for ($j = $M - $k; $j < $M; $j++) $matrix[$i][$j - $M + $k] = $matrix[$i][$j]; // copy elements from // temporary array to end for ($j = $k; $j < $M; $j++) $matrix[$i][$j] = $temp[$j - $k]; }} // function to display// the matrixfunction displayMatrix(&$matrix){ global $M, $N; for ($i = 0; $i < $N; $i++) { for ($j = 0; $j < $M; $j++) echo ($matrix[$i][$j]." "); echo ("\n"); }} // Driver code$matrix = array(array(12, 23, 34), array(45, 56, 67), array(78, 89, 91));$k = 2; // rotate matrix by krotateMatrix($matrix, $k); // display rotated matrixdisplayMatrix($matrix); // This code is contributed by// Manish Shaw(manishshaw1)?> <script> // Javascript program to rotate a matrix// right by k times // size of matrix var M = 3; var N = 3; // function to rotate matrix by k times function rotateMatrix(matrix , k) { // temporary array of size M var temp = Array(M).fill(0); // within the size of matrix k = k % M; for (i = 0; i < N; i++) { // copy first M-k elements // to temporary array for (t = 0; t < M - k; t++) temp[t] = matrix[i][t]; // copy the elements from k // to end to starting for (j = M - k; j < M; j++) matrix[i][j - M + k] = matrix[i][j]; // copy elements from // temporary array to end for (j = k; j < M; j++) matrix[i][j] = temp[j - k]; } } // function to display the matrix function displayMatrix(matrix) { for (i = 0; i < N; i++) { for (j = 0; j < M; j++) document.write(matrix[i][j] + " "); document.write("<br/>"); } } // Driver code var matrix = [ [ 12, 23, 34 ], [ 45, 56, 67 ], [ 78, 89, 91 ] ]; var k = 2; // rotate matrix by k rotateMatrix(matrix, k); // display rotated matrix displayMatrix(matrix); // This code contributed by umadevi9616 </script> 23 34 12 56 67 45 89 91 78 Time Complexity: O(n*m)Auxiliary Space: O(m) KRV manishshaw1 umadevi9616 kothavvsaakash adi1212 rotation Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Jun, 2022" }, { "code": null, "e": 166, "s": 54, "text": "Given a matrix of size N*M, and a number K. We have to rotate the matrix K times to the right side. Examples: " }, { "code": null, "e": 399, "s": 166, "text": "Input : N = 3, M = 3, K = 2\n 12 23 34\n 45 56 67\n 78 89 91 \n\nOutput : 23 34 12\n 56 67 45\n 89 91 78 \n\n\nInput : N = 2, M = 2, K = 2\n 1 2\n 3 4\n \nOutput : 1 2\n 3 4" }, { "code": null, "e": 716, "s": 401, "text": "A simple yet effective approach is to consider each row of the matrix as an array and perform an array rotation. This can be done by copying the elements from K to end of array to starting of array using temporary array. And then the remaining elements from start to K-1 to end of the array.Lets take an example: " }, { "code": null, "e": 722, "s": 718, "text": "C++" }, { "code": null, "e": 724, "s": 722, "text": "C" }, { "code": null, "e": 729, "s": 724, "text": "Java" }, { "code": null, "e": 737, "s": 729, "text": "Python3" }, { "code": null, "e": 740, "s": 737, "text": "C#" }, { "code": null, "e": 744, "s": 740, "text": "PHP" }, { "code": null, "e": 755, "s": 744, "text": "Javascript" }, { "code": "// CPP program to rotate a matrix right by k times#include <iostream> // size of matrix#define M 3#define N 3 using namespace std; // function to rotate matrix by k timesvoid rotateMatrix(int matrix[][M], int k) { // temporary array of size M int temp[M]; // within the size of matrix k = k % M; for (int i = 0; i < N; i++) { // copy first M-k elements to temporary array for (int t = 0; t < M - k; t++) temp[t] = matrix[i][t]; // copy the elements from k to end to starting for (int j = M - k; j < M; j++) matrix[i][j - M + k] = matrix[i][j]; // copy elements from temporary array to end for (int j = k; j < M; j++) matrix[i][j] = temp[j - k]; }} // function to display the matrixvoid displayMatrix(int matrix[][M]) { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) cout << matrix[i][j] << \" \"; cout << endl; }} // Driver's codeint main() { int matrix[N][M] = {{12, 23, 34}, {45, 56, 67}, {78, 89, 91}}; int k = 2; // rotate matrix by k rotateMatrix(matrix, k); // display rotated matrix displayMatrix(matrix); return 0;}", "e": 1895, "s": 755, "text": null }, { "code": "// C program to rotate a matrix right by k times#include <stdio.h> // size of matrix#define M 3#define N 3 // function to rotate matrix by k timesvoid rotateMatrix(int matrix[][M], int k){ // temporary array of size M int temp[M]; // within the size of matrix k = k % M; for (int i = 0; i < N; i++) { // copy first M-k elements to temporary array for (int t = 0; t < M - k; t++) temp[t] = matrix[i][t]; // copy the elements from k to end to starting for (int j = M - k; j < M; j++) matrix[i][j - M + k] = matrix[i][j]; // copy elements from temporary array to end for (int j = k; j < M; j++) matrix[i][j] = temp[j - k]; }} // function to display the matrixvoid displayMatrix(int matrix[][M]) { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) printf(\"%d \",matrix[i][j]); printf(\"\\n\"); }} // Driver's codeint main() { int matrix[N][M] = {{12, 23, 34}, {45, 56, 67}, {78, 89, 91}}; int k = 2; // rotate matrix by k rotateMatrix(matrix, k); // display rotated matrix displayMatrix(matrix); return 0;} // This code is contributed by kothavvsaakash.", "e": 3059, "s": 1895, "text": null }, { "code": "// Java program to rotate a matrix// right by k times class GFG{ // size of matrix static final int M=3; static final int N=3; // function to rotate matrix by k times static void rotateMatrix(int matrix[][], int k) { // temporary array of size M int temp[]=new int[M]; // within the size of matrix k = k % M; for (int i = 0; i < N; i++) { // copy first M-k elements // to temporary array for (int t = 0; t < M - k; t++) temp[t] = matrix[i][t]; // copy the elements from k // to end to starting for (int j = M - k; j < M; j++) matrix[i][j - M + k] = matrix[i][j]; // copy elements from // temporary array to end for (int j = k; j < M; j++) matrix[i][j] = temp[j - k]; } } // function to display the matrix static void displayMatrix(int matrix[][]) { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) System.out.print(matrix[i][j] + \" \"); System.out.println(); } } // Driver code public static void main (String[] args) { int matrix[][] = {{12, 23, 34}, {45, 56, 67}, {78, 89, 91}}; int k = 2; // rotate matrix by k rotateMatrix(matrix, k); // display rotated matrix displayMatrix(matrix); }} // This code is contributed by Anant Agarwal.", "e": 4622, "s": 3059, "text": null }, { "code": "# Python program to rotate# a matrix right by k times # size of matrixM = 3N = 3matrix = [[12, 23, 34], [45, 56, 67], [78, 89, 91]] # function to rotate# matrix by k timesdef rotateMatrix(k) : global M, N, matrix # temporary array # of size M temp = [0] * M # within the size # of matrix k = k % M for i in range(0, N) : # copy first M-k elements # to temporary array for t in range(0, M - k) : temp[t] = matrix[i][t] # copy the elements from # k to end to starting for j in range(M - k, M) : matrix[i][j - M + k] = matrix[i][j] # copy elements from # temporary array to end for j in range(k, M) : matrix[i][j] = temp[j - k] # function to display# the matrixdef displayMatrix() : global M, N, matrix for i in range(0, N) : for j in range(0, M) : print (\"{} \" . format(matrix[i][j]), end = \"\") print () # Driver codek = 2 # rotate matrix by krotateMatrix(k) # display rotated matrixdisplayMatrix() # This code is contributed by# Manish Shaw(manishshaw1)", "e": 5803, "s": 4622, "text": null }, { "code": "// C# program to rotate a // matrix right by k timesusing System; class GFG { // size of matrix static int M=3; static int N=3; // function to rotate matrix by k times static void rotateMatrix(int [,] matrix, int k) { // temporary array of size M int [] temp=new int[M]; // within the size of matrix k = k % M; for (int i = 0; i < N; i++) { // copy first M-k elements // to temporary array for (int t = 0; t < M - k; t++) temp[t] = matrix[i, t]; // copy the elements from k // to end to starting for (int j = M - k; j < M; j++) matrix[i, j - M + k] = matrix[i, j]; // copy elements from // temporary array to end for (int j = k; j < M; j++) matrix[i, j] = temp[j - k]; } } // function to display the matrix static void displayMatrix(int [,] matrix) { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) Console.Write(matrix[i, j] + \" \"); Console.WriteLine(); } } // Driver code public static void Main () { int [,] matrix = {{12, 23, 34}, {45, 56, 67}, {78, 89, 91}}; int k = 2; // rotate matrix by k rotateMatrix(matrix, k); // display rotated matrix displayMatrix(matrix); }} // This code is contributed by KRV.", "e": 7415, "s": 5803, "text": null }, { "code": "<?php// PHP program to rotate// a matrix right by k times // size of matrix$M = 3;$N = 3; // function to rotate// matrix by k timesfunction rotateMatrix(&$matrix, $k){ global $M, $N; // temporary array // of size M $temp = array(); // within the size // of matrix $k = $k % $M; for ($i = 0; $i < $N; $i++) { // copy first M-k elements // to temporary array for ($t = 0; $t < $M - $k; $t++) $temp[$t] = $matrix[$i][$t]; // copy the elements from // k to end to starting for ($j = $M - $k; $j < $M; $j++) $matrix[$i][$j - $M + $k] = $matrix[$i][$j]; // copy elements from // temporary array to end for ($j = $k; $j < $M; $j++) $matrix[$i][$j] = $temp[$j - $k]; }} // function to display// the matrixfunction displayMatrix(&$matrix){ global $M, $N; for ($i = 0; $i < $N; $i++) { for ($j = 0; $j < $M; $j++) echo ($matrix[$i][$j].\" \"); echo (\"\\n\"); }} // Driver code$matrix = array(array(12, 23, 34), array(45, 56, 67), array(78, 89, 91));$k = 2; // rotate matrix by krotateMatrix($matrix, $k); // display rotated matrixdisplayMatrix($matrix); // This code is contributed by// Manish Shaw(manishshaw1)?>", "e": 8765, "s": 7415, "text": null }, { "code": "<script> // Javascript program to rotate a matrix// right by k times // size of matrix var M = 3; var N = 3; // function to rotate matrix by k times function rotateMatrix(matrix , k) { // temporary array of size M var temp = Array(M).fill(0); // within the size of matrix k = k % M; for (i = 0; i < N; i++) { // copy first M-k elements // to temporary array for (t = 0; t < M - k; t++) temp[t] = matrix[i][t]; // copy the elements from k // to end to starting for (j = M - k; j < M; j++) matrix[i][j - M + k] = matrix[i][j]; // copy elements from // temporary array to end for (j = k; j < M; j++) matrix[i][j] = temp[j - k]; } } // function to display the matrix function displayMatrix(matrix) { for (i = 0; i < N; i++) { for (j = 0; j < M; j++) document.write(matrix[i][j] + \" \"); document.write(\"<br/>\"); } } // Driver code var matrix = [ [ 12, 23, 34 ], [ 45, 56, 67 ], [ 78, 89, 91 ] ]; var k = 2; // rotate matrix by k rotateMatrix(matrix, k); // display rotated matrix displayMatrix(matrix); // This code contributed by umadevi9616 </script>", "e": 10163, "s": 8765, "text": null }, { "code": null, "e": 10192, "s": 10163, "text": "23 34 12 \n56 67 45 \n89 91 78" }, { "code": null, "e": 10239, "s": 10194, "text": "Time Complexity: O(n*m)Auxiliary Space: O(m)" }, { "code": null, "e": 10243, "s": 10239, "text": "KRV" }, { "code": null, "e": 10255, "s": 10243, "text": "manishshaw1" }, { "code": null, "e": 10267, "s": 10255, "text": "umadevi9616" }, { "code": null, "e": 10282, "s": 10267, "text": "kothavvsaakash" }, { "code": null, "e": 10290, "s": 10282, "text": "adi1212" }, { "code": null, "e": 10299, "s": 10290, "text": "rotation" }, { "code": null, "e": 10306, "s": 10299, "text": "Matrix" }, { "code": null, "e": 10313, "s": 10306, "text": "Matrix" } ]
How to define attributes of a class in Python?
Everything, almost everything in Python is an object. Every object has attributes and methods. Thus attributes are very fundamental in Python. A class is a construct which is a collection of similar objects. A class also has attributes. There will be a difference between the class attributes and instance attributes. The class attributes are shared by the instances of the class but it not true vice versa. We can get a list of the attributes of an object using the built-in “dir” function. For example − >>> s = 'abc' >>> len(dir(s)) 71 >>> dir(s)[:5] ['__add__', '__class__', '__contains__', '__delattr__', '__doc__'] >>> i = 123 >>> len(dir(i)) 64 >>> dir(i)[:5] ['__abs__', '__add__', '__and__', '__class__', '__cmp__'] >>> t = (1,2,3) >>> len(dir(t)) 32 >>> dir(t)[:5] ['__add__', '__class__', '__contains__', '__delattr__', '__doc__'] As we can see, even the basic data types in Python have many attributes. We can see the first five attributes by limiting the output from “dir”;
[ { "code": null, "e": 1470, "s": 1062, "text": "Everything, almost everything in Python is an object. Every object has attributes and methods. Thus attributes are very fundamental in Python. A class is a construct which is a collection of similar objects. A class also has attributes. There will be a difference between the class attributes and instance attributes. The class attributes are shared by the instances of the class but it not true vice versa." }, { "code": null, "e": 1568, "s": 1470, "text": "We can get a list of the attributes of an object using the built-in “dir” function. For example −" }, { "code": null, "e": 1904, "s": 1568, "text": ">>> s = 'abc'\n>>> len(dir(s))\n71\n>>> dir(s)[:5]\n['__add__', '__class__', '__contains__', '__delattr__', '__doc__']\n>>> i = 123\n>>> len(dir(i))\n64\n>>> dir(i)[:5]\n['__abs__', '__add__', '__and__', '__class__', '__cmp__']\n>>> t = (1,2,3)\n>>> len(dir(t))\n32\n>>> dir(t)[:5]\n['__add__', '__class__', '__contains__', '__delattr__', '__doc__']" }, { "code": null, "e": 2050, "s": 1904, "text": "As we can see, even the basic data types in Python have many attributes. We can see the first five attributes by limiting the output from “dir”; " } ]
10 Minutes to Building a Binary Image Classifier By Applying Transfer Learning to MobileNet in TensorFlow | by Binh Phan | Towards Data Science
This is a short introduction to computer vision — namely, how to build a binary image classifier using transfer learning on the MobileNet model, geared mainly towards new users. This easy-to-follow tutorial is broken down into 3 sections: The dataThe model architectureThe accuracy, ROC curve, and AUC The data The model architecture The accuracy, ROC curve, and AUC Requirements: Nothing! All you need to follow this tutorial is this Google Colab notebook containing the data and code. Google Colab allows you to write and run Python code in-browser without any setup, and includes free GPU access! To run this code, simply go to File -> Make a copy to create a copy of the notebook that you can run and edit. We’re going to build a dandelion and grass image classifier. I’ve created a small image dataset using images from Google Images, which you can download and parse in the first 8 cells of the tutorial. By the end of those 8 lines, visualizing a sample of your image dataset will look something like this: Note how some of the images in the dataset aren’t perfect representations of grass or dandelions. For simplicity’s sake, let’s make this okay and move on to how to easily create our training and validation dataset. The data that we fetched earlier is divided into two folders, train and valid. In those folders, the foldersdandelion and grass contain the images of each class. To create a dataset, let’s use the keras.preprocessing.image.ImageDataGenerator class to create our training and validation dataset and normalize our data. What this class does is create a dataset and automatically does the labeling for us, allowing us to create a dataset in just one line! In the beginning of this section, we first import TensorFlow. Now, let’s add the MobileNet model. Make sure that to include the include_top parameter and set to to False. This will subtract the last layer of the model, so that we can add our own layer that we will train on. This is called transfer learning! We will then add a GlobalAveragePooling2D layer to reduce the size of the output that we will feed into our last layer. For that last layer, we will add a Sigmoid layer for binary classification. This is important: we must set our MobileNet layers’ trainable parameter to False so that we don’t end up training the entire model — we only need to train the last layer! Here is the model that we have built: model = Sequential()model.add(MobileNetV2(include_top = False, weights="imagenet", input_shape=(200, 200, 3)))model.add(tf.keras.layers.GlobalAveragePooling2D())model.add(Dense(1, activation = 'sigmoid'))model.layers[0].trainable = False Let’s see a summary of the model we have built: Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= mobilenetv2_1.00_224 (Model) (None, 7, 7, 1280) 2257984 _________________________________________________________________ global_average_pooling2d (Gl (None, 1280) 0 _________________________________________________________________ dense (Dense) (None, 1) 1281 ================================================================= Total params: 2,259,265 Trainable params: 1,281 Non-trainable params: 2,257,984 Next, we’ll configure the specifications for model training. We will train our model with the binary_crossentropy loss. We will use the RMSProp optimizer. RMSProp is a sensible optimization algorithm because it automates learning-rate tuning for us (alternatively, we could also use Adam or Adagrad for similar results). We will add accuracy to metrics so that the model will monitor accuracy during training. model.compile(optimizer=RMSprop(lr=0.01), loss = 'binary_crossentropy', metrics = 'accuracy') Let’s train for 15 epochs: history = model.fit(train_generator,steps_per_epoch=8,epochs=15,verbose=1,validation_data = validation_generator,validation_steps=8) Let’s evaluate the accuracy of our model: model.evaluate(validation_generator) Now, let’s calculate our ROC curve and plot it. First, let’s make predictions on our validation set. When using generators to make predictions, we must first turn off shuffle (as we did when we created validation_generator) and reset the generator: STEP_SIZE_TEST=validation_generator.n//validation_generator.batch_sizevalidation_generator.reset()preds = model.predict(validation_generator,verbose=1) To create the ROC curve and AUC, we’ll need to compute the false-positive rate and the true-positive rate: fpr, tpr, _ = roc_curve(validation_generator.classes, preds)roc_auc = auc(fpr, tpr)plt.figure()lw = 2plt.plot(fpr, tpr, color='darkorange',lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')plt.xlim([0.0, 1.0])plt.ylim([0.0, 1.05])plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.title('Receiver operating characteristic example')plt.legend(loc="lower right")plt.show() The ROC curve is a probability curve plotting the true-positive rate (TPR) against the false-positive rate (FPR). In this curve, the diagonal line is the curve for random guessing, e.g. coin flipping, so the ROC curve above shows that our model does pretty well on classification! Similarly, the AUC (area under curve), as shown in the legend above, measures how much our model is capable of distinguishing between our two classes, dandelions and grass. The higher the AUC, the better our model is at classification. An AUC of .96 is considered pretty good! Finally, at the end of the notebook, you’ll have a chance to make predictions on your own images! I hope this gives you a gentle introduction to building a simple binary image classifier using transfer learning on the MobileNet model! If you are interested in similar tutorials to this, please check out my other stories.
[ { "code": null, "e": 411, "s": 172, "text": "This is a short introduction to computer vision — namely, how to build a binary image classifier using transfer learning on the MobileNet model, geared mainly towards new users. This easy-to-follow tutorial is broken down into 3 sections:" }, { "code": null, "e": 474, "s": 411, "text": "The dataThe model architectureThe accuracy, ROC curve, and AUC" }, { "code": null, "e": 483, "s": 474, "text": "The data" }, { "code": null, "e": 506, "s": 483, "text": "The model architecture" }, { "code": null, "e": 539, "s": 506, "text": "The accuracy, ROC curve, and AUC" }, { "code": null, "e": 883, "s": 539, "text": "Requirements: Nothing! All you need to follow this tutorial is this Google Colab notebook containing the data and code. Google Colab allows you to write and run Python code in-browser without any setup, and includes free GPU access! To run this code, simply go to File -> Make a copy to create a copy of the notebook that you can run and edit." }, { "code": null, "e": 1083, "s": 883, "text": "We’re going to build a dandelion and grass image classifier. I’ve created a small image dataset using images from Google Images, which you can download and parse in the first 8 cells of the tutorial." }, { "code": null, "e": 1186, "s": 1083, "text": "By the end of those 8 lines, visualizing a sample of your image dataset will look something like this:" }, { "code": null, "e": 1401, "s": 1186, "text": "Note how some of the images in the dataset aren’t perfect representations of grass or dandelions. For simplicity’s sake, let’s make this okay and move on to how to easily create our training and validation dataset." }, { "code": null, "e": 1854, "s": 1401, "text": "The data that we fetched earlier is divided into two folders, train and valid. In those folders, the foldersdandelion and grass contain the images of each class. To create a dataset, let’s use the keras.preprocessing.image.ImageDataGenerator class to create our training and validation dataset and normalize our data. What this class does is create a dataset and automatically does the labeling for us, allowing us to create a dataset in just one line!" }, { "code": null, "e": 1916, "s": 1854, "text": "In the beginning of this section, we first import TensorFlow." }, { "code": null, "e": 2531, "s": 1916, "text": "Now, let’s add the MobileNet model. Make sure that to include the include_top parameter and set to to False. This will subtract the last layer of the model, so that we can add our own layer that we will train on. This is called transfer learning! We will then add a GlobalAveragePooling2D layer to reduce the size of the output that we will feed into our last layer. For that last layer, we will add a Sigmoid layer for binary classification. This is important: we must set our MobileNet layers’ trainable parameter to False so that we don’t end up training the entire model — we only need to train the last layer!" }, { "code": null, "e": 2569, "s": 2531, "text": "Here is the model that we have built:" }, { "code": null, "e": 2807, "s": 2569, "text": "model = Sequential()model.add(MobileNetV2(include_top = False, weights=\"imagenet\", input_shape=(200, 200, 3)))model.add(tf.keras.layers.GlobalAveragePooling2D())model.add(Dense(1, activation = 'sigmoid'))model.layers[0].trainable = False" }, { "code": null, "e": 2855, "s": 2807, "text": "Let’s see a summary of the model we have built:" }, { "code": null, "e": 3549, "s": 2855, "text": "Model: \"sequential\" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= mobilenetv2_1.00_224 (Model) (None, 7, 7, 1280) 2257984 _________________________________________________________________ global_average_pooling2d (Gl (None, 1280) 0 _________________________________________________________________ dense (Dense) (None, 1) 1281 ================================================================= Total params: 2,259,265 Trainable params: 1,281 Non-trainable params: 2,257,984" }, { "code": null, "e": 3959, "s": 3549, "text": "Next, we’ll configure the specifications for model training. We will train our model with the binary_crossentropy loss. We will use the RMSProp optimizer. RMSProp is a sensible optimization algorithm because it automates learning-rate tuning for us (alternatively, we could also use Adam or Adagrad for similar results). We will add accuracy to metrics so that the model will monitor accuracy during training." }, { "code": null, "e": 4053, "s": 3959, "text": "model.compile(optimizer=RMSprop(lr=0.01), loss = 'binary_crossentropy', metrics = 'accuracy')" }, { "code": null, "e": 4080, "s": 4053, "text": "Let’s train for 15 epochs:" }, { "code": null, "e": 4213, "s": 4080, "text": "history = model.fit(train_generator,steps_per_epoch=8,epochs=15,verbose=1,validation_data = validation_generator,validation_steps=8)" }, { "code": null, "e": 4255, "s": 4213, "text": "Let’s evaluate the accuracy of our model:" }, { "code": null, "e": 4292, "s": 4255, "text": "model.evaluate(validation_generator)" }, { "code": null, "e": 4340, "s": 4292, "text": "Now, let’s calculate our ROC curve and plot it." }, { "code": null, "e": 4541, "s": 4340, "text": "First, let’s make predictions on our validation set. When using generators to make predictions, we must first turn off shuffle (as we did when we created validation_generator) and reset the generator:" }, { "code": null, "e": 4693, "s": 4541, "text": "STEP_SIZE_TEST=validation_generator.n//validation_generator.batch_sizevalidation_generator.reset()preds = model.predict(validation_generator,verbose=1)" }, { "code": null, "e": 4800, "s": 4693, "text": "To create the ROC curve and AUC, we’ll need to compute the false-positive rate and the true-positive rate:" }, { "code": null, "e": 5250, "s": 4800, "text": "fpr, tpr, _ = roc_curve(validation_generator.classes, preds)roc_auc = auc(fpr, tpr)plt.figure()lw = 2plt.plot(fpr, tpr, color='darkorange',lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')plt.xlim([0.0, 1.0])plt.ylim([0.0, 1.05])plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.title('Receiver operating characteristic example')plt.legend(loc=\"lower right\")plt.show()" }, { "code": null, "e": 5531, "s": 5250, "text": "The ROC curve is a probability curve plotting the true-positive rate (TPR) against the false-positive rate (FPR). In this curve, the diagonal line is the curve for random guessing, e.g. coin flipping, so the ROC curve above shows that our model does pretty well on classification!" }, { "code": null, "e": 5808, "s": 5531, "text": "Similarly, the AUC (area under curve), as shown in the legend above, measures how much our model is capable of distinguishing between our two classes, dandelions and grass. The higher the AUC, the better our model is at classification. An AUC of .96 is considered pretty good!" }, { "code": null, "e": 5906, "s": 5808, "text": "Finally, at the end of the notebook, you’ll have a chance to make predictions on your own images!" } ]
Java continue Keyword
❮ Java Keywords Skip the iteration if the variable i is 4, but continue with the next iteration: for (int i = 0; i < 10; i++) { if (i == 4) { continue; } System.out.println(i); } Try it Yourself » The continue keyword is used to end the current iteration in a for loop (or a while loop), and continues to the next iteration. Use the continue keyword in a while loop int i = 0;while (i < 10) { if (i == 4) { i++; continue; } System.out.println(i); i++; } Try it Yourself » Use the break keyword to break out of a loop. Read more about for loops in our Java For Loops Tutorial. Read more about while loops in our Java While Loops Tutorial. Read more about break and continue in our Java Break Tutorial. ❮ Java Keywords We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 18, "s": 0, "text": "\n❮ Java Keywords\n" }, { "code": null, "e": 99, "s": 18, "text": "Skip the iteration if the variable i is 4, but continue with the next iteration:" }, { "code": null, "e": 192, "s": 99, "text": "for (int i = 0; i < 10; i++) {\n if (i == 4) {\n continue;\n }\n System.out.println(i);\n}\n" }, { "code": null, "e": 212, "s": 192, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 340, "s": 212, "text": "The continue keyword is used to end the current iteration in a for loop (or a while loop), and continues to the next iteration." }, { "code": null, "e": 381, "s": 340, "text": "Use the continue keyword in a while loop" }, { "code": null, "e": 486, "s": 381, "text": "int i = 0;while (i < 10) {\n if (i == 4) {\n i++;\n continue;\n }\n System.out.println(i);\n i++;\n}\n" }, { "code": null, "e": 506, "s": 486, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 553, "s": 506, "text": "Use the break \nkeyword to break out of a loop." }, { "code": null, "e": 611, "s": 553, "text": "Read more about for loops in our Java For Loops Tutorial." }, { "code": null, "e": 673, "s": 611, "text": "Read more about while loops in our Java While Loops Tutorial." }, { "code": null, "e": 736, "s": 673, "text": "Read more about break and continue in our Java Break Tutorial." }, { "code": null, "e": 754, "s": 736, "text": "\n❮ Java Keywords\n" }, { "code": null, "e": 787, "s": 754, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 829, "s": 787, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 936, "s": 829, "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": 955, "s": 936, "text": "[email protected]" } ]
Boundary Value Analysis : Nature of Roots of a Quadratic equation - GeeksforGeeks
04 Mar, 2020 Consider a problem for the determination of the nature of the roots of a quadratic equation where the inputs are 3 variables (a, b, c) and their values may be from the interval [0, 100]. The output may be one of the following depending on the values of the variables: Not a quadratic equation, Real roots, Imaginary roots, Equal roots Our objective is to design the boundary value test cases. Boundary value analysis is a software testing technique in which tests are designed to include representatives of boundary values in a range. A boundary value analysis has a total of 4*n+1 distinct test cases, where n is the number of variables in a problem. Here we have to consider all the three variables and design all the distinct possible test cases. We will have a total of 13 test cases as n = 3. Roots are real if (b2 – 4ac) > 0 Roots are imaginary if (b2 – 4ac) < 0 Roots are equal if (b2 – 4ac) = 0 Equation is not quadratic if a = 0 How do we design the test cases ?For each variable we consider below 5 cases: amin = 0 amin+1 = 1 anominal = 50 amax-1 = 99 amax = 100 When we are considering these 5 cases for a variable, rest of the variables have the nominal values, like in the above case where the value of ‘a’ is varying from 0 to 100, the value of ‘b’ and ‘c’ will be taken as the nominal or average value. Similarly, when the values of variable ‘b’ are changing from 0 to 100, the values of ‘a’ and ‘c’ will be nominal or average i.e 50. The possible test cases for the nature of roots of a Quadratic Equation in a Boundary Value Analysis can be: Below is the program that verifies the test cases considered in the table shown above. The program takes user-defined inputs so that you can check for any of the test cases mentioned above. C++ Java Python3 C# // C++ program to check the nature of the roots #include <bits/stdc++.h>using namespace std; // BVA for nature of roots of a quadratic equationvoid nature_of_roots(int a, int b, int c){ // If a = 0, D/2a will yield exception // Hence it is not a valid Quadratic Equation if (a == 0) { cout << "Not a Quadratic Equation" << endl; return; } int D = b * b - 4 * a * c; // If D > 0, it will be Real Roots if (D > 0) { cout << "Real Roots" << endl; } // If D == 0, it will be Equal Roots else if (D == 0) { cout << "Equal Roots" << endl; } // If D < 0, it will be Imaginary Roots else { cout << "Imaginary Roots" << endl; }} // Function to check for all testcasesvoid checkForAllTestCase(){ cout << "Testcase" << "\ta\tb\tc\tActual Output" << endl; cout << endl; int a, b, c; int testcase = 1; while (testcase <= 13) { if (testcase == 1) { a = 0; b = 50; c = 50; } else if (testcase == 2) { a = 1; b = 50; c = 50; } else if (testcase == 3) { a = 50; b = 50; c = 50; } else if (testcase == 4) { a = 99; b = 50; c = 50; } else if (testcase == 5) { a = 100; b = 50; c = 50; } else if (testcase == 6) { a = 50; b = 0; c = 50; } else if (testcase == 7) { a = 50; b = 1; c = 50; } else if (testcase == 8) { a = 50; b = 99; c = 50; } else if (testcase == 9) { a = 50; b = 100; c = 50; } else if (testcase == 10) { a = 50; b = 50; c = 0; } else if (testcase == 11) { a = 50; b = 50; c = 1; } else if (testcase == 12) { a = 50; b = 50; c = 99; } else if (testcase == 13) { a = 50; b = 50; c = 100; } cout << "\t" << testcase << "\t" << a << "\t" << b << "\t" << c << "\t"; nature_of_roots(a, b, c); cout << endl; testcase++; }} // Driver Codeint main(){ checkForAllTestCase(); return 0;} // Java program to check the nature of the rootsimport java.util.*; class GFG{ // BVA for nature of roots of a quadratic equationstatic void nature_of_roots(int a, int b, int c){ // If a = 0, D/2a will yield exception // Hence it is not a valid Quadratic Equation if (a == 0) { System.out.print("Not a Quadratic Equation" +"\n"); return; } int D = b * b - 4 * a * c; // If D > 0, it will be Real Roots if (D > 0) { System.out.print("Real Roots" +"\n"); } // If D == 0, it will be Equal Roots else if (D == 0) { System.out.print("Equal Roots" +"\n"); } // If D < 0, it will be Imaginary Roots else { System.out.print("Imaginary Roots" +"\n"); }} // Function to check for all testcasesstatic void checkForAllTestCase(){ System.out.print("Testcase" + "\ta\tb\tc\tActual Output" +"\n"); System.out.println(); int a, b, c; a = b = c = 0; int testcase = 1; while (testcase <= 13) { if (testcase == 1) { a = 0; b = 50; c = 50; } else if (testcase == 2) { a = 1; b = 50; c = 50; } else if (testcase == 3) { a = 50; b = 50; c = 50; } else if (testcase == 4) { a = 99; b = 50; c = 50; } else if (testcase == 5) { a = 100; b = 50; c = 50; } else if (testcase == 6) { a = 50; b = 0; c = 50; } else if (testcase == 7) { a = 50; b = 1; c = 50; } else if (testcase == 8) { a = 50; b = 99; c = 50; } else if (testcase == 9) { a = 50; b = 100; c = 50; } else if (testcase == 10) { a = 50; b = 50; c = 0; } else if (testcase == 11) { a = 50; b = 50; c = 1; } else if (testcase == 12) { a = 50; b = 50; c = 99; } else if (testcase == 13) { a = 50; b = 50; c = 100; } System.out.print("\t" + testcase+ "\t" + a+ "\t" + b+ "\t" + c+ "\t"); nature_of_roots(a, b, c); System.out.println(); testcase++; }} // Driver Codepublic static void main(String[] args){ checkForAllTestCase();}} // This code is contributed by 29AjayKumar # Python3 program to check the nature of the roots # BVA for nature of roots of a quadratic equationdef nature_of_roots(a, b, c): # If a = 0, D/2a will yield exception # Hence it is not a valid Quadratic Equation if (a == 0): print("Not a Quadratic Equation"); return; D = b * b - 4 * a * c; # If D > 0, it will be Real Roots if (D > 0): print("Real Roots"); # If D == 0, it will be Equal Roots elif(D == 0): print("Equal Roots"); # If D < 0, it will be Imaginary Roots else: print("Imaginary Roots"); # Function to check for all testcasesdef checkForAllTestCase(): print("Testcase\ta\tb\tc\tActual Output"); print(); a = b = c = 0; testcase = 1; while (testcase <= 13): if (testcase == 1): a = 0; b = 50; c = 50; elif(testcase == 2): a = 1; b = 50; c = 50; elif(testcase == 3): a = 50; b = 50; c = 50; elif(testcase == 4): a = 99; b = 50; c = 50; elif(testcase == 5): a = 100; b = 50; c = 50; elif(testcase == 6): a = 50; b = 0; c = 50; elif(testcase == 7): a = 50; b = 1; c = 50; elif(testcase == 8): a = 50; b = 99; c = 50; elif(testcase == 9): a = 50; b = 100; c = 50; elif(testcase == 10): a = 50; b = 50; c = 0; elif(testcase == 11): a = 50; b = 50; c = 1; elif(testcase == 12): a = 50; b = 50; c = 99; elif(testcase == 13): a = 50; b = 50; c = 100; print("\t" , testcase , "\t" , a , "\t" , b , "\t" , c , "\t", end=""); nature_of_roots(a, b, c); print(); testcase += 1; # Driver Codeif __name__ == '__main__': checkForAllTestCase(); # This code is contributed by 29AjayKumar // C# program to check the nature of the rootsusing System; class GFG{ // BVA for nature of roots of a quadratic equationstatic void nature_of_roots(int a, int b, int c){ // If a = 0, D/2a will yield exception // Hence it is not a valid Quadratic Equation if (a == 0) { Console.Write("Not a Quadratic Equation" +"\n"); return; } int D = b * b - 4 * a * c; // If D > 0, it will be Real Roots if (D > 0) { Console.Write("Real Roots" +"\n"); } // If D == 0, it will be Equal Roots else if (D == 0) { Console.Write("Equal Roots" +"\n"); } // If D < 0, it will be Imaginary Roots else { Console.Write("Imaginary Roots" +"\n"); }} // Function to check for all testcasesstatic void checkForAllTestCase(){ Console.Write("Testcase" + "\ta\tb\tc\tActual Output" +"\n"); Console.WriteLine(); int a, b, c; a = b = c = 0; int testcase = 1; while (testcase <= 13) { if (testcase == 1) { a = 0; b = 50; c = 50; } else if (testcase == 2) { a = 1; b = 50; c = 50; } else if (testcase == 3) { a = 50; b = 50; c = 50; } else if (testcase == 4) { a = 99; b = 50; c = 50; } else if (testcase == 5) { a = 100; b = 50; c = 50; } else if (testcase == 6) { a = 50; b = 0; c = 50; } else if (testcase == 7) { a = 50; b = 1; c = 50; } else if (testcase == 8) { a = 50; b = 99; c = 50; } else if (testcase == 9) { a = 50; b = 100; c = 50; } else if (testcase == 10) { a = 50; b = 50; c = 0; } else if (testcase == 11) { a = 50; b = 50; c = 1; } else if (testcase == 12) { a = 50; b = 50; c = 99; } else if (testcase == 13) { a = 50; b = 50; c = 100; } Console.Write("\t" + testcase+ "\t" + a+ "\t" + b+ "\t" + c+ "\t"); nature_of_roots(a, b, c); Console.WriteLine(); testcase++; }} // Driver Codepublic static void Main(String[] args){ checkForAllTestCase();}} // This code is contributed by 29AjayKumar Testcase a b c Actual Output 1 0 50 50 Not a Quadratic Equation 2 1 50 50 Real Roots 3 50 50 50 Imaginary Roots 4 99 50 50 Imaginary Roots 5 100 50 50 Imaginary Roots 6 50 0 50 Imaginary Roots 7 50 1 50 Imaginary Roots 8 50 99 50 Imaginary Roots 9 50 100 50 Equal Roots 10 50 50 0 Real Roots 11 50 50 1 Real Roots 12 50 50 99 Imaginary Roots 13 50 50 100 Imaginary Roots 29AjayKumar Software Testing Mathematical Software Engineering Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Find all factors of a natural number | Set 1 Check if a number is Palindrome Program to print prime numbers from 1 to N. Program to add two binary strings Fizz Buzz Implementation Types of Software Testing Software Engineering | COCOMO Model Software Engineering | Spiral Model Differences between Black Box Testing vs White Box Testing Software Engineering | Classical Waterfall Model
[ { "code": null, "e": 24301, "s": 24273, "text": "\n04 Mar, 2020" }, { "code": null, "e": 24569, "s": 24301, "text": "Consider a problem for the determination of the nature of the roots of a quadratic equation where the inputs are 3 variables (a, b, c) and their values may be from the interval [0, 100]. The output may be one of the following depending on the values of the variables:" }, { "code": null, "e": 24595, "s": 24569, "text": "Not a quadratic equation," }, { "code": null, "e": 24607, "s": 24595, "text": "Real roots," }, { "code": null, "e": 24624, "s": 24607, "text": "Imaginary roots," }, { "code": null, "e": 24636, "s": 24624, "text": "Equal roots" }, { "code": null, "e": 24694, "s": 24636, "text": "Our objective is to design the boundary value test cases." }, { "code": null, "e": 24953, "s": 24694, "text": "Boundary value analysis is a software testing technique in which tests are designed to include representatives of boundary values in a range. A boundary value analysis has a total of 4*n+1 distinct test cases, where n is the number of variables in a problem." }, { "code": null, "e": 25099, "s": 24953, "text": "Here we have to consider all the three variables and design all the distinct possible test cases. We will have a total of 13 test cases as n = 3." }, { "code": null, "e": 25132, "s": 25099, "text": "Roots are real if (b2 – 4ac) > 0" }, { "code": null, "e": 25170, "s": 25132, "text": "Roots are imaginary if (b2 – 4ac) < 0" }, { "code": null, "e": 25204, "s": 25170, "text": "Roots are equal if (b2 – 4ac) = 0" }, { "code": null, "e": 25239, "s": 25204, "text": "Equation is not quadratic if a = 0" }, { "code": null, "e": 25317, "s": 25239, "text": "How do we design the test cases ?For each variable we consider below 5 cases:" }, { "code": null, "e": 25326, "s": 25317, "text": "amin = 0" }, { "code": null, "e": 25337, "s": 25326, "text": "amin+1 = 1" }, { "code": null, "e": 25351, "s": 25337, "text": "anominal = 50" }, { "code": null, "e": 25363, "s": 25351, "text": "amax-1 = 99" }, { "code": null, "e": 25374, "s": 25363, "text": "amax = 100" }, { "code": null, "e": 25751, "s": 25374, "text": "When we are considering these 5 cases for a variable, rest of the variables have the nominal values, like in the above case where the value of ‘a’ is varying from 0 to 100, the value of ‘b’ and ‘c’ will be taken as the nominal or average value. Similarly, when the values of variable ‘b’ are changing from 0 to 100, the values of ‘a’ and ‘c’ will be nominal or average i.e 50." }, { "code": null, "e": 25860, "s": 25751, "text": "The possible test cases for the nature of roots of a Quadratic Equation in a Boundary Value Analysis can be:" }, { "code": null, "e": 26050, "s": 25860, "text": "Below is the program that verifies the test cases considered in the table shown above. The program takes user-defined inputs so that you can check for any of the test cases mentioned above." }, { "code": null, "e": 26054, "s": 26050, "text": "C++" }, { "code": null, "e": 26059, "s": 26054, "text": "Java" }, { "code": null, "e": 26067, "s": 26059, "text": "Python3" }, { "code": null, "e": 26070, "s": 26067, "text": "C#" }, { "code": "// C++ program to check the nature of the roots #include <bits/stdc++.h>using namespace std; // BVA for nature of roots of a quadratic equationvoid nature_of_roots(int a, int b, int c){ // If a = 0, D/2a will yield exception // Hence it is not a valid Quadratic Equation if (a == 0) { cout << \"Not a Quadratic Equation\" << endl; return; } int D = b * b - 4 * a * c; // If D > 0, it will be Real Roots if (D > 0) { cout << \"Real Roots\" << endl; } // If D == 0, it will be Equal Roots else if (D == 0) { cout << \"Equal Roots\" << endl; } // If D < 0, it will be Imaginary Roots else { cout << \"Imaginary Roots\" << endl; }} // Function to check for all testcasesvoid checkForAllTestCase(){ cout << \"Testcase\" << \"\\ta\\tb\\tc\\tActual Output\" << endl; cout << endl; int a, b, c; int testcase = 1; while (testcase <= 13) { if (testcase == 1) { a = 0; b = 50; c = 50; } else if (testcase == 2) { a = 1; b = 50; c = 50; } else if (testcase == 3) { a = 50; b = 50; c = 50; } else if (testcase == 4) { a = 99; b = 50; c = 50; } else if (testcase == 5) { a = 100; b = 50; c = 50; } else if (testcase == 6) { a = 50; b = 0; c = 50; } else if (testcase == 7) { a = 50; b = 1; c = 50; } else if (testcase == 8) { a = 50; b = 99; c = 50; } else if (testcase == 9) { a = 50; b = 100; c = 50; } else if (testcase == 10) { a = 50; b = 50; c = 0; } else if (testcase == 11) { a = 50; b = 50; c = 1; } else if (testcase == 12) { a = 50; b = 50; c = 99; } else if (testcase == 13) { a = 50; b = 50; c = 100; } cout << \"\\t\" << testcase << \"\\t\" << a << \"\\t\" << b << \"\\t\" << c << \"\\t\"; nature_of_roots(a, b, c); cout << endl; testcase++; }} // Driver Codeint main(){ checkForAllTestCase(); return 0;}", "e": 28552, "s": 26070, "text": null }, { "code": "// Java program to check the nature of the rootsimport java.util.*; class GFG{ // BVA for nature of roots of a quadratic equationstatic void nature_of_roots(int a, int b, int c){ // If a = 0, D/2a will yield exception // Hence it is not a valid Quadratic Equation if (a == 0) { System.out.print(\"Not a Quadratic Equation\" +\"\\n\"); return; } int D = b * b - 4 * a * c; // If D > 0, it will be Real Roots if (D > 0) { System.out.print(\"Real Roots\" +\"\\n\"); } // If D == 0, it will be Equal Roots else if (D == 0) { System.out.print(\"Equal Roots\" +\"\\n\"); } // If D < 0, it will be Imaginary Roots else { System.out.print(\"Imaginary Roots\" +\"\\n\"); }} // Function to check for all testcasesstatic void checkForAllTestCase(){ System.out.print(\"Testcase\" + \"\\ta\\tb\\tc\\tActual Output\" +\"\\n\"); System.out.println(); int a, b, c; a = b = c = 0; int testcase = 1; while (testcase <= 13) { if (testcase == 1) { a = 0; b = 50; c = 50; } else if (testcase == 2) { a = 1; b = 50; c = 50; } else if (testcase == 3) { a = 50; b = 50; c = 50; } else if (testcase == 4) { a = 99; b = 50; c = 50; } else if (testcase == 5) { a = 100; b = 50; c = 50; } else if (testcase == 6) { a = 50; b = 0; c = 50; } else if (testcase == 7) { a = 50; b = 1; c = 50; } else if (testcase == 8) { a = 50; b = 99; c = 50; } else if (testcase == 9) { a = 50; b = 100; c = 50; } else if (testcase == 10) { a = 50; b = 50; c = 0; } else if (testcase == 11) { a = 50; b = 50; c = 1; } else if (testcase == 12) { a = 50; b = 50; c = 99; } else if (testcase == 13) { a = 50; b = 50; c = 100; } System.out.print(\"\\t\" + testcase+ \"\\t\" + a+ \"\\t\" + b+ \"\\t\" + c+ \"\\t\"); nature_of_roots(a, b, c); System.out.println(); testcase++; }} // Driver Codepublic static void main(String[] args){ checkForAllTestCase();}} // This code is contributed by 29AjayKumar", "e": 31163, "s": 28552, "text": null }, { "code": "# Python3 program to check the nature of the roots # BVA for nature of roots of a quadratic equationdef nature_of_roots(a, b, c): # If a = 0, D/2a will yield exception # Hence it is not a valid Quadratic Equation if (a == 0): print(\"Not a Quadratic Equation\"); return; D = b * b - 4 * a * c; # If D > 0, it will be Real Roots if (D > 0): print(\"Real Roots\"); # If D == 0, it will be Equal Roots elif(D == 0): print(\"Equal Roots\"); # If D < 0, it will be Imaginary Roots else: print(\"Imaginary Roots\"); # Function to check for all testcasesdef checkForAllTestCase(): print(\"Testcase\\ta\\tb\\tc\\tActual Output\"); print(); a = b = c = 0; testcase = 1; while (testcase <= 13): if (testcase == 1): a = 0; b = 50; c = 50; elif(testcase == 2): a = 1; b = 50; c = 50; elif(testcase == 3): a = 50; b = 50; c = 50; elif(testcase == 4): a = 99; b = 50; c = 50; elif(testcase == 5): a = 100; b = 50; c = 50; elif(testcase == 6): a = 50; b = 0; c = 50; elif(testcase == 7): a = 50; b = 1; c = 50; elif(testcase == 8): a = 50; b = 99; c = 50; elif(testcase == 9): a = 50; b = 100; c = 50; elif(testcase == 10): a = 50; b = 50; c = 0; elif(testcase == 11): a = 50; b = 50; c = 1; elif(testcase == 12): a = 50; b = 50; c = 99; elif(testcase == 13): a = 50; b = 50; c = 100; print(\"\\t\" , testcase , \"\\t\" , a , \"\\t\" , b , \"\\t\" , c , \"\\t\", end=\"\"); nature_of_roots(a, b, c); print(); testcase += 1; # Driver Codeif __name__ == '__main__': checkForAllTestCase(); # This code is contributed by 29AjayKumar", "e": 33323, "s": 31163, "text": null }, { "code": "// C# program to check the nature of the rootsusing System; class GFG{ // BVA for nature of roots of a quadratic equationstatic void nature_of_roots(int a, int b, int c){ // If a = 0, D/2a will yield exception // Hence it is not a valid Quadratic Equation if (a == 0) { Console.Write(\"Not a Quadratic Equation\" +\"\\n\"); return; } int D = b * b - 4 * a * c; // If D > 0, it will be Real Roots if (D > 0) { Console.Write(\"Real Roots\" +\"\\n\"); } // If D == 0, it will be Equal Roots else if (D == 0) { Console.Write(\"Equal Roots\" +\"\\n\"); } // If D < 0, it will be Imaginary Roots else { Console.Write(\"Imaginary Roots\" +\"\\n\"); }} // Function to check for all testcasesstatic void checkForAllTestCase(){ Console.Write(\"Testcase\" + \"\\ta\\tb\\tc\\tActual Output\" +\"\\n\"); Console.WriteLine(); int a, b, c; a = b = c = 0; int testcase = 1; while (testcase <= 13) { if (testcase == 1) { a = 0; b = 50; c = 50; } else if (testcase == 2) { a = 1; b = 50; c = 50; } else if (testcase == 3) { a = 50; b = 50; c = 50; } else if (testcase == 4) { a = 99; b = 50; c = 50; } else if (testcase == 5) { a = 100; b = 50; c = 50; } else if (testcase == 6) { a = 50; b = 0; c = 50; } else if (testcase == 7) { a = 50; b = 1; c = 50; } else if (testcase == 8) { a = 50; b = 99; c = 50; } else if (testcase == 9) { a = 50; b = 100; c = 50; } else if (testcase == 10) { a = 50; b = 50; c = 0; } else if (testcase == 11) { a = 50; b = 50; c = 1; } else if (testcase == 12) { a = 50; b = 50; c = 99; } else if (testcase == 13) { a = 50; b = 50; c = 100; } Console.Write(\"\\t\" + testcase+ \"\\t\" + a+ \"\\t\" + b+ \"\\t\" + c+ \"\\t\"); nature_of_roots(a, b, c); Console.WriteLine(); testcase++; }} // Driver Codepublic static void Main(String[] args){ checkForAllTestCase();}} // This code is contributed by 29AjayKumar", "e": 35941, "s": 33323, "text": null }, { "code": null, "e": 36546, "s": 35941, "text": "Testcase a b c Actual Output\n\n 1 0 50 50 Not a Quadratic Equation\n\n 2 1 50 50 Real Roots\n\n 3 50 50 50 Imaginary Roots\n\n 4 99 50 50 Imaginary Roots\n\n 5 100 50 50 Imaginary Roots\n\n 6 50 0 50 Imaginary Roots\n\n 7 50 1 50 Imaginary Roots\n\n 8 50 99 50 Imaginary Roots\n\n 9 50 100 50 Equal Roots\n\n 10 50 50 0 Real Roots\n\n 11 50 50 1 Real Roots\n\n 12 50 50 99 Imaginary Roots\n\n 13 50 50 100 Imaginary Roots\n" }, { "code": null, "e": 36558, "s": 36546, "text": "29AjayKumar" }, { "code": null, "e": 36575, "s": 36558, "text": "Software Testing" }, { "code": null, "e": 36588, "s": 36575, "text": "Mathematical" }, { "code": null, "e": 36609, "s": 36588, "text": "Software Engineering" }, { "code": null, "e": 36622, "s": 36609, "text": "Mathematical" }, { "code": null, "e": 36720, "s": 36622, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36729, "s": 36720, "text": "Comments" }, { "code": null, "e": 36742, "s": 36729, "text": "Old Comments" }, { "code": null, "e": 36787, "s": 36742, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 36819, "s": 36787, "text": "Check if a number is Palindrome" }, { "code": null, "e": 36863, "s": 36819, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 36897, "s": 36863, "text": "Program to add two binary strings" }, { "code": null, "e": 36922, "s": 36897, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 36948, "s": 36922, "text": "Types of Software Testing" }, { "code": null, "e": 36984, "s": 36948, "text": "Software Engineering | COCOMO Model" }, { "code": null, "e": 37020, "s": 36984, "text": "Software Engineering | Spiral Model" }, { "code": null, "e": 37079, "s": 37020, "text": "Differences between Black Box Testing vs White Box Testing" } ]
Pythonic MetaProgramming With MetaClasses | by Emmett Boudreau | Towards Data Science
Metaprogramming is the construction of code to manipulate code and can allow for some pretty interesting and expressive results in syntax. Metaprogramming is not a concept that is typically associated with Python, but the reality is that Python and meta actually go together in a lot of cool and unique ways. If you’ve ever worked with metaclasses or decorators in Python, then you were actually metaprogramming in Python. Like most high-level programming languages, in Python, every individual variable or object has a type. Types are important because they determine how data is stored in memory for each variable. Every type in Python is defined by a class, and we can illustrate this by using the type() function in the standard library: string = "example"print(type(string))<class 'str'> The class for the string type is the “ str” class, which contains methods like split() which are typically used to parse chars. This is likely not a new concept for any Python programmer, but we can take this one step further by using metaclasses to manipulate classes without ever writing in them. Unlike in C, Java, or even C++ where int, char, and float are the primary datatypes, in Python, they are an object in a class. This works both to Python’s advantage and Python’s disadvantage, as PyObjects are datatypes that aren’t typically readable universally. This means that often data can end up stuck in Python, but it also means that data used in Python is an instance of a class, which is an instance of a metaclass. The first thing that we’ll need is a decorator. A decorators job in Python is to create a design pattern that will allow us to add new functionality to our classes without modifying them. Using decorators will make it incredibly easy to keep our classes static while still adding additional features as needed. I like to make function decorators for my class decorators to inherit because it creates a greater boundary between our code, which we are trying to avoid mutating. from functools import wrapsdef debug(func): '''decorator; debugs function when passed.''' @wraps(func) def wrapper(*args, **kwargs): print("Full name of this method:", func.__qualname__) return func(*args, **kwargs) return wrapper Now we can add our actual class decorator: def debugmethods(cls): '''class decorator to use debug method''' for key, val in vars(cls).items(): if callable(val): setattr(cls, key, debug(val)) return cls And consequently, our metaclass: class debugMeta(type): '''meta class which feed created class object to debugmethod to get debug functionality enabled objects''' def __new__(cls, clsname, bases, clsdict): obj = super().__new__(cls, clsname, bases, clsdict) obj = debugmethods(obj) return obj Now we can inherit this new class’s data by creating a new class using the parameter (metaclass=). # now all the subclass of this # will have debugging applied class Base(metaclass=debugMeta):pass Now we can use object-oriented inheritence to inherit the properties of the meta-class into our new class. Every time “ debugMeta” is modified, all of its children that depend on it will inherit the changes. This makes for some interesting syntax where we can automate and add functionality to our class without the need to ever modify it. # inheriting Base class Calc(Base): def add(self, x, y): return x+y And now using the calculator: Our calculator class is actually using the debugging behavior that we set up with the metaclass, but note that the data isn’t a child of our object: Though Python isn’t typically associated with the idea of meta-programming, not only is it perfectly capable of achieving the concept with its unique decorators, it also uses it itself in a lot of ways. I think the biggest advantage that Python has to a lot of other languages where meta-programming is the norm is Python’s inheritance. For what I did above, none of it would have been possible without inheritance, and Python does inheritance really well in my subjective appearance. Since often we associate meta-programming with languages like Lisp or Scheme, it’s very interesting to see meta-programming done in an entirely different — and really cool way in an entirely different language from a completely different paradigm. On top of that, decorators are certainly a cool concept that I really wish more languages would adopt, as it makes the process of meta-programming really simple and straight-forward. This is especially true when comparing Python to other languages, and more specifically functional languages that I have used for meta-programming. Often tossing around macros and expressions can be powerful, but simultaneously it can be incredibly confusing, and I think Python leverages its syntax very well in the face of that exact problem.
[ { "code": null, "e": 595, "s": 172, "text": "Metaprogramming is the construction of code to manipulate code and can allow for some pretty interesting and expressive results in syntax. Metaprogramming is not a concept that is typically associated with Python, but the reality is that Python and meta actually go together in a lot of cool and unique ways. If you’ve ever worked with metaclasses or decorators in Python, then you were actually metaprogramming in Python." }, { "code": null, "e": 914, "s": 595, "text": "Like most high-level programming languages, in Python, every individual variable or object has a type. Types are important because they determine how data is stored in memory for each variable. Every type in Python is defined by a class, and we can illustrate this by using the type() function in the standard library:" }, { "code": null, "e": 965, "s": 914, "text": "string = \"example\"print(type(string))<class 'str'>" }, { "code": null, "e": 1264, "s": 965, "text": "The class for the string type is the “ str” class, which contains methods like split() which are typically used to parse chars. This is likely not a new concept for any Python programmer, but we can take this one step further by using metaclasses to manipulate classes without ever writing in them." }, { "code": null, "e": 1689, "s": 1264, "text": "Unlike in C, Java, or even C++ where int, char, and float are the primary datatypes, in Python, they are an object in a class. This works both to Python’s advantage and Python’s disadvantage, as PyObjects are datatypes that aren’t typically readable universally. This means that often data can end up stuck in Python, but it also means that data used in Python is an instance of a class, which is an instance of a metaclass." }, { "code": null, "e": 2165, "s": 1689, "text": "The first thing that we’ll need is a decorator. A decorators job in Python is to create a design pattern that will allow us to add new functionality to our classes without modifying them. Using decorators will make it incredibly easy to keep our classes static while still adding additional features as needed. I like to make function decorators for my class decorators to inherit because it creates a greater boundary between our code, which we are trying to avoid mutating." }, { "code": null, "e": 2404, "s": 2165, "text": "from functools import wrapsdef debug(func): '''decorator; debugs function when passed.''' @wraps(func) def wrapper(*args, **kwargs): print(\"Full name of this method:\", func.__qualname__) return func(*args, **kwargs) return wrapper" }, { "code": null, "e": 2447, "s": 2404, "text": "Now we can add our actual class decorator:" }, { "code": null, "e": 2614, "s": 2447, "text": "def debugmethods(cls): '''class decorator to use debug method''' for key, val in vars(cls).items(): if callable(val): setattr(cls, key, debug(val)) return cls" }, { "code": null, "e": 2647, "s": 2614, "text": "And consequently, our metaclass:" }, { "code": null, "e": 2918, "s": 2647, "text": "class debugMeta(type): '''meta class which feed created class object to debugmethod to get debug functionality enabled objects''' def __new__(cls, clsname, bases, clsdict): obj = super().__new__(cls, clsname, bases, clsdict) obj = debugmethods(obj) return obj " }, { "code": null, "e": 3017, "s": 2918, "text": "Now we can inherit this new class’s data by creating a new class using the parameter (metaclass=)." }, { "code": null, "e": 3115, "s": 3017, "text": "# now all the subclass of this # will have debugging applied class Base(metaclass=debugMeta):pass" }, { "code": null, "e": 3455, "s": 3115, "text": "Now we can use object-oriented inheritence to inherit the properties of the meta-class into our new class. Every time “ debugMeta” is modified, all of its children that depend on it will inherit the changes. This makes for some interesting syntax where we can automate and add functionality to our class without the need to ever modify it." }, { "code": null, "e": 3526, "s": 3455, "text": "# inheriting Base class Calc(Base): def add(self, x, y): return x+y" }, { "code": null, "e": 3556, "s": 3526, "text": "And now using the calculator:" }, { "code": null, "e": 3705, "s": 3556, "text": "Our calculator class is actually using the debugging behavior that we set up with the metaclass, but note that the data isn’t a child of our object:" }, { "code": null, "e": 4621, "s": 3705, "text": "Though Python isn’t typically associated with the idea of meta-programming, not only is it perfectly capable of achieving the concept with its unique decorators, it also uses it itself in a lot of ways. I think the biggest advantage that Python has to a lot of other languages where meta-programming is the norm is Python’s inheritance. For what I did above, none of it would have been possible without inheritance, and Python does inheritance really well in my subjective appearance. Since often we associate meta-programming with languages like Lisp or Scheme, it’s very interesting to see meta-programming done in an entirely different — and really cool way in an entirely different language from a completely different paradigm. On top of that, decorators are certainly a cool concept that I really wish more languages would adopt, as it makes the process of meta-programming really simple and straight-forward." } ]
PHP Sorting Arrays
The elements in an array can be sorted in alphabetical or numerical order, descending or ascending. In this chapter, we will go through the following PHP array sort functions: sort() - sort arrays in ascending order rsort() - sort arrays in descending order asort() - sort associative arrays in ascending order, according to the value ksort() - sort associative arrays in ascending order, according to the key arsort() - sort associative arrays in descending order, according to the value krsort() - sort associative arrays in descending order, according to the key The following example sorts the elements of the $cars array in ascending alphabetical order: The following example sorts the elements of the $numbers array in ascending numerical order: The following example sorts the elements of the $cars array in descending alphabetical order: The following example sorts the elements of the $numbers array in descending numerical order: The following example sorts an associative array in ascending order, according to the value: The following example sorts an associative array in ascending order, according to the key: The following example sorts an associative array in descending order, according to the value: The following example sorts an associative array in descending order, according to the key: For a complete reference of all array functions, go to our complete PHP Array Reference. The reference contains a brief description, and examples of use, for each function! Use the correct array method to sort the $colors array alphabetically. $colors = array("red", "green", "blue", "yellow"); ; We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 100, "s": 0, "text": "The elements in an array can be sorted in alphabetical or numerical order, descending or ascending." }, { "code": null, "e": 176, "s": 100, "text": "In this chapter, we will go through the following PHP array sort functions:" }, { "code": null, "e": 216, "s": 176, "text": "sort() - sort arrays in ascending order" }, { "code": null, "e": 258, "s": 216, "text": "rsort() - sort arrays in descending order" }, { "code": null, "e": 335, "s": 258, "text": "asort() - sort associative arrays in ascending order, according to the value" }, { "code": null, "e": 410, "s": 335, "text": "ksort() - sort associative arrays in ascending order, according to the key" }, { "code": null, "e": 489, "s": 410, "text": "arsort() - sort associative arrays in descending order, according to the value" }, { "code": null, "e": 566, "s": 489, "text": "krsort() - sort associative arrays in descending order, according to the key" }, { "code": null, "e": 659, "s": 566, "text": "The following example sorts the elements of the $cars array in ascending alphabetical order:" }, { "code": null, "e": 753, "s": 659, "text": "The following example sorts the elements of the $numbers array in ascending \nnumerical order:" }, { "code": null, "e": 847, "s": 753, "text": "The following example sorts the elements of the $cars array in descending alphabetical order:" }, { "code": null, "e": 942, "s": 847, "text": "The following example sorts the elements of the $numbers array in descending \nnumerical order:" }, { "code": null, "e": 1036, "s": 942, "text": "The following example sorts an associative array in ascending order, \naccording to the value:" }, { "code": null, "e": 1128, "s": 1036, "text": "The following example sorts an associative array in ascending order, \naccording to the key:" }, { "code": null, "e": 1223, "s": 1128, "text": "The following example sorts an associative array in descending order, \naccording to the value:" }, { "code": null, "e": 1316, "s": 1223, "text": "The following example sorts an associative array in descending order, \naccording to the key:" }, { "code": null, "e": 1405, "s": 1316, "text": "For a complete reference of all array functions, go to our complete PHP Array Reference." }, { "code": null, "e": 1489, "s": 1405, "text": "The reference contains a brief description, and examples of use, for each function!" }, { "code": null, "e": 1560, "s": 1489, "text": "Use the correct array method to sort the $colors array alphabetically." }, { "code": null, "e": 1615, "s": 1560, "text": "$colors = array(\"red\", \"green\", \"blue\", \"yellow\"); \n;\n" }, { "code": null, "e": 1648, "s": 1615, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1690, "s": 1648, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1797, "s": 1690, "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": 1816, "s": 1797, "text": "[email protected]" } ]
PL/SQL Online Quiz
Following quiz provides Multiple Choice Questions (MCQs) related to PL/SQL. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz. Q 1 - Which of the following is not true about the declaration section of a PL/SQL block? A - This section starts with the DECLARE keyword. B - It is a mandatory section. C - It defines all variables, cursors, subprograms, and other elements to be used in the program. D - None of the above. Q 2 - Which of the following is true about scalar data types in PL/SQL? A - They hold single values with no internal components. B - Examples of scalar data types are NUMBER, DATE, or BOOLEAN. C - PL/SQL provides subtypes of data types. D - All are true. Q 3 - What is wrong in the following code snippet? DECLARE x number := 1; BEGIN LOOP dbms_output.put_line(x); x := x + 1; IF x > 10 THEN exit; END IF; dbms_output.put_line('After Exit x is: ' || x); END; A - There is nothing wrong. B - The IF statement is not required. C - There should be an END LOOP statement. D - The exit statement should be in capital letters. Q 4 - A subprogram can be created − A - At schema level. B - Inside a package. C - Inside a PL/SQL block. D - All of the above. Q 5 - What would be the output of the following code? DECLARE a number; b number; c number; FUNCTION fx(x IN number, y IN number) RETURN number IS z number; BEGIN IF x > 2*y THEN z:= x; ELSE z:= 2*y; END IF; RETURN z; END; BEGIN a:= 23; b:= 47; c := fx(a, b); dbms_output.put_line(c); END; A - 46 B - 47 C - 94 D - 23 Q 6 - Which of the following code will successfully declare an exception named emp_exception1 in a PL/SQL block? A - EXCEPTION emp_exception1; B - emp_exception1 EXCEPTION; C - CREATE EXCEPTION emp_exception1; D - CREATE emp_exception1 AS EXCEPTION; Q 7 - Which of the following is not true about PL/SQL triggers? A - Triggers are stored programs. B - They are automatically executed or fired when some events occur. C - Triggers could be defined on the table, view, schema, or database with which the event is associated. D - None of the above. Q 8 - Which of the following is not true about PL/SQL packages? A - PL/SQL packages are schema objects that groups logically related PL/SQL types, variables and subprograms. B - A package has two parts: Package specification and Package body or definition. C - Both the parts are mandatory. D - None of the above. Q 9 - Which of the following is true about PL/SQL nested tables? A - Nested tables are like one-dimensional arrays with arbitrary number of elements. B - Unlike arrays a nested table doesn’t have declared number of elements. The size of a nested table can increase dynamically. C - Initially a nested array has consecutive subscripts or dense, but it can become sparse when elements are deleted from it. D - All of the above. Q 10 - Which of the following is not true about the comparison methods? A - These are used for comparing objects. B - The Map method is a function implemented in such a way that its value doesn’t depend upon the value of the attributes. C - The Order methods implement some internal logic for comparing two objects. D - None of the above. The Map method is a function implemented in such a way that its value depends upon the value of the attributes. Print Add Notes Bookmark this page
[ { "code": null, "e": 2385, "s": 2065, "text": "Following quiz provides Multiple Choice Questions (MCQs) related to PL/SQL. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz." }, { "code": null, "e": 2475, "s": 2385, "text": "Q 1 - Which of the following is not true about the declaration section of a PL/SQL block?" }, { "code": null, "e": 2525, "s": 2475, "text": "A - This section starts with the DECLARE keyword." }, { "code": null, "e": 2556, "s": 2525, "text": "B - It is a mandatory section." }, { "code": null, "e": 2654, "s": 2556, "text": "C - It defines all variables, cursors, subprograms, and other elements to be used in the program." }, { "code": null, "e": 2677, "s": 2654, "text": "D - None of the above." }, { "code": null, "e": 2749, "s": 2677, "text": "Q 2 - Which of the following is true about scalar data types in PL/SQL?" }, { "code": null, "e": 2806, "s": 2749, "text": "A - They hold single values with no internal components." }, { "code": null, "e": 2870, "s": 2806, "text": "B - Examples of scalar data types are NUMBER, DATE, or BOOLEAN." }, { "code": null, "e": 2914, "s": 2870, "text": "C - PL/SQL provides subtypes of data types." }, { "code": null, "e": 2932, "s": 2914, "text": "D - All are true." }, { "code": null, "e": 2983, "s": 2932, "text": "Q 3 - What is wrong in the following code snippet?" }, { "code": null, "e": 3180, "s": 2983, "text": "DECLARE\n x number := 1;\nBEGIN\n LOOP\n dbms_output.put_line(x);\n x := x + 1;\n IF x > 10 THEN\n exit;\n END IF;\n dbms_output.put_line('After Exit x is: ' || x);\nEND;" }, { "code": null, "e": 3208, "s": 3180, "text": "A - There is nothing wrong." }, { "code": null, "e": 3246, "s": 3208, "text": "B - The IF statement is not required." }, { "code": null, "e": 3289, "s": 3246, "text": "C - There should be an END LOOP statement." }, { "code": null, "e": 3342, "s": 3289, "text": "D - The exit statement should be in capital letters." }, { "code": null, "e": 3378, "s": 3342, "text": "Q 4 - A subprogram can be created −" }, { "code": null, "e": 3399, "s": 3378, "text": "A - At schema level." }, { "code": null, "e": 3421, "s": 3399, "text": "B - Inside a package." }, { "code": null, "e": 3448, "s": 3421, "text": "C - Inside a PL/SQL block." }, { "code": null, "e": 3470, "s": 3448, "text": "D - All of the above." }, { "code": null, "e": 3524, "s": 3470, "text": "Q 5 - What would be the output of the following code?" }, { "code": null, "e": 3813, "s": 3524, "text": "DECLARE\n a number;\n b number;\n c number;\nFUNCTION fx(x IN number, y IN number) \nRETURN number\nIS\n z number;\nBEGIN\n IF x > 2*y THEN\n z:= x;\n ELSE\n z:= 2*y;\n END IF;\n\n RETURN z;\nEND; \nBEGIN\n a:= 23;\n b:= 47;\n\n c := fx(a, b);\n dbms_output.put_line(c);\nEND;" }, { "code": null, "e": 3820, "s": 3813, "text": "A - 46" }, { "code": null, "e": 3827, "s": 3820, "text": "B - 47" }, { "code": null, "e": 3834, "s": 3827, "text": "C - 94" }, { "code": null, "e": 3841, "s": 3834, "text": "D - 23" }, { "code": null, "e": 3954, "s": 3841, "text": "Q 6 - Which of the following code will successfully declare an exception named emp_exception1 in a PL/SQL block?" }, { "code": null, "e": 3984, "s": 3954, "text": "A - EXCEPTION emp_exception1;" }, { "code": null, "e": 4014, "s": 3984, "text": "B - emp_exception1 EXCEPTION;" }, { "code": null, "e": 4051, "s": 4014, "text": "C - CREATE EXCEPTION emp_exception1;" }, { "code": null, "e": 4091, "s": 4051, "text": "D - CREATE emp_exception1 AS EXCEPTION;" }, { "code": null, "e": 4155, "s": 4091, "text": "Q 7 - Which of the following is not true about PL/SQL triggers?" }, { "code": null, "e": 4189, "s": 4155, "text": "A - Triggers are stored programs." }, { "code": null, "e": 4258, "s": 4189, "text": "B - They are automatically executed or fired when some events occur." }, { "code": null, "e": 4364, "s": 4258, "text": "C - Triggers could be defined on the table, view, schema, or database with which the event is associated." }, { "code": null, "e": 4387, "s": 4364, "text": "D - None of the above." }, { "code": null, "e": 4451, "s": 4387, "text": "Q 8 - Which of the following is not true about PL/SQL packages?" }, { "code": null, "e": 4561, "s": 4451, "text": "A - PL/SQL packages are schema objects that groups logically related PL/SQL types, variables and subprograms." }, { "code": null, "e": 4644, "s": 4561, "text": "B - A package has two parts: Package specification and Package body or definition." }, { "code": null, "e": 4678, "s": 4644, "text": "C - Both the parts are mandatory." }, { "code": null, "e": 4701, "s": 4678, "text": "D - None of the above." }, { "code": null, "e": 4766, "s": 4701, "text": "Q 9 - Which of the following is true about PL/SQL nested tables?" }, { "code": null, "e": 4851, "s": 4766, "text": "A - Nested tables are like one-dimensional arrays with arbitrary number of elements." }, { "code": null, "e": 4979, "s": 4851, "text": "B - Unlike arrays a nested table doesn’t have declared number of elements. The size of a nested table can increase dynamically." }, { "code": null, "e": 5105, "s": 4979, "text": "C - Initially a nested array has consecutive subscripts or dense, but it can become sparse when elements are deleted from it." }, { "code": null, "e": 5127, "s": 5105, "text": "D - All of the above." }, { "code": null, "e": 5199, "s": 5127, "text": "Q 10 - Which of the following is not true about the comparison methods?" }, { "code": null, "e": 5241, "s": 5199, "text": "A - These are used for comparing objects." }, { "code": null, "e": 5364, "s": 5241, "text": "B - The Map method is a function implemented in such a way that its value doesn’t depend upon the value of the attributes." }, { "code": null, "e": 5443, "s": 5364, "text": "C - The Order methods implement some internal logic for comparing two objects." }, { "code": null, "e": 5467, "s": 5443, "text": "D - None of the above. " }, { "code": null, "e": 5579, "s": 5467, "text": "The Map method is a function implemented in such a way that its value depends upon the value of the attributes." }, { "code": null, "e": 5586, "s": 5579, "text": " Print" }, { "code": null, "e": 5597, "s": 5586, "text": " Add Notes" } ]
Are quotes around tables and columns in a MySQL query really necessary?
If your table name or column name are any reserved words then you need to use quotes around table name and column name in a MySQL query. You need to use backticks around table name and column name. The syntax is as follows: SELECT *FROM `table` where `where`=condition; Here is the query to create a table without quotes with reserved words. You will get an error since they are predefined reserved words. The error is as follows: mysql> create table table -> ( -> where int -> ); ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table ( where int )' at line 1 Let us now include quotes around the name of the table and column since ‘table’ and ‘where’ are reserved words. Here is the query with quotes: mysql> create table `table` -> ( -> `where` int -> ); Query OK, 0 rows affected (0.55 sec) Insert records in the table using insert command. The query is as follows: mysql> insert into `table`(`where`) values(1); Query OK, 1 row affected (0.13 sec) mysql> insert into `table`(`where`) values(100); Query OK, 1 row affected (0.26 sec) mysql> insert into `table`(`where`) values(1000); Query OK, 1 row affected (0.13 sec) Display a specific record from the table with the help of where condition. The query is as follows: mysql> select *from `table` where `where`=100; The following is the output: +-------+ | where | +-------+ | 100 | +-------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1286, "s": 1062, "text": "If your table name or column name are any reserved words then you need to use quotes around table name and column name in a MySQL query. You need to use backticks around table name and column name. The syntax is as follows:" }, { "code": null, "e": 1332, "s": 1286, "text": "SELECT *FROM `table` where `where`=condition;" }, { "code": null, "e": 1493, "s": 1332, "text": "Here is the query to create a table without quotes with reserved words. You will get an error since they are predefined reserved words. The error is as follows:" }, { "code": null, "e": 1741, "s": 1493, "text": "mysql> create table table\n -> (\n -> where int\n -> );\nERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table\n(\n where int\n)' at line 1" }, { "code": null, "e": 1884, "s": 1741, "text": "Let us now include quotes around the name of the table and column since ‘table’ and ‘where’ are reserved words. Here is the query with quotes:" }, { "code": null, "e": 1984, "s": 1884, "text": "mysql> create table `table`\n -> (\n -> `where` int\n -> );\nQuery OK, 0 rows affected (0.55 sec)" }, { "code": null, "e": 2059, "s": 1984, "text": "Insert records in the table using insert command. The query is as follows:" }, { "code": null, "e": 2313, "s": 2059, "text": "mysql> insert into `table`(`where`) values(1);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into `table`(`where`) values(100);\nQuery OK, 1 row affected (0.26 sec)\nmysql> insert into `table`(`where`) values(1000);\nQuery OK, 1 row affected (0.13 sec)" }, { "code": null, "e": 2413, "s": 2313, "text": "Display a specific record from the table with the help of where condition. The query is as follows:" }, { "code": null, "e": 2460, "s": 2413, "text": "mysql> select *from `table` where `where`=100;" }, { "code": null, "e": 2489, "s": 2460, "text": "The following is the output:" }, { "code": null, "e": 2563, "s": 2489, "text": "+-------+\n| where |\n+-------+\n| 100 |\n+-------+\n1 row in set (0.00 sec)" } ]
Google Sheets, Meet Pandas DataFrame | by Nicholas Ballard | Towards Data Science
Maybe it’s from too many hours behind the keyboard. But sometimes my reading and watching on the internet gives me the feeling I’m one of an endangered species of developer. One who’s working inside spreadsheets. Every single day. Can you believe it? Developers, going about their lives like spreadsheets don’t exist. If you are one of these people, I’d like to meet you. To know that you exist, and this isn’t all a paranoid rant raging between my ears. For the rest of us, spreadsheets are very much a thing. Love them or hate them, those binary rows and columns are going nowhere. To cut the philosophy lesson short: spreadsheets are. Every non-developer employee save the cleaning staff lives inside spreadsheets. “Spreadsheets are.” Submit this existential bombshell to a university; an honorary doctorate in philosophy is sure to follow. Excel and Google Sheets, they’re going nowhere; neither is our productivity until we put automation between us and the knowledge worker ritual of passing the spreadsheet. Personally, I love a good spreadsheet. For munging data, quick and dirty calculations, visualizing 1-dimensional times series... 4 out of 5 times I will open Excel or Google Sheets, rather than fire up a Jupyter server. Except, spreadsheetitis in a business is a symptom of not knowing how to move data. I have personally seen the “human router” problem so bad where more than 20 (twenty!) people touched a version of a spreadsheet before it was finally–mercifully–put to rest in “the database” (another spreadsheet). And THE Spreadsheet. You know the business is in data hell when there’s The Spreadsheet, with a capital “S”. The one managers think is the business. There’s a few libraries we will talk about using for Google Sheets I/O in Python. No matter the approach, you have to enable the Google Sheets API inside the maze-like console for Google Cloud Platform (Google’s version of AWS and Azure). Fortunately Google–go figure–has a great search feature in the console that we’ll use to get you set up. Go to console.cloud.google.com/, sign in with the Google account with access to the spreadsheet you want to automate. The API is available for both GSuite and free Google accounts. If it’s a work-owned spreadsheet, the admin with GCP access is going to have to follow these steps and give you the credentials file. Select the project in the navbar on the top. Every resource is kept inside a project, like resource groups in Azure. If you do not have one yet, select the project dropdown and “NEW PROJECT”. Then search for “Google Sheets API”, which if you are a sadist and want to explore the dashboard by mouse, is under “APIs & Services”. “Enable” the API. Now you need to do the same for Google Drive API. Next up, you need to create a service account, which you will then create credentials for. Steps: You are in Google Cloud Platform > Google Sheets API at console.cloud.google.com/apis/api/sheets.googleapis.com Go to credentials 🗝 Credentials on the sidebar. Select + CREATE CREDENTIALS > Service Account. OAuth is a different story. This article covers a server-side, in-house use. Create the service account. Next view is to select an IAM role for the service account. This is optional, skip it. Next up is “Grant users access to this service account (optional)”. Also skip. Now you are back on the “Service accounts for project [PROJECT NAME]” screen. Select the service account in the table, either clicking on the hyperlinked Email field, or hamburger menu (three dots) > Create key. Either way, ADD KEY or Create key, select JSON key type and CREATE. This downloads a JSON file to your computer. Last thing: the spreadsheet. Here I created one for this example. Note the highlighted section of the URL in the Omnibar. That is the document’s ID. Most libraries give the choice of referencing the whole URL or just this ID. You can take a look at and download the spreadsheet from here. Open the credentials.json file you downloaded from GCP for the service account. Copy the email value in the client_email property. Share the Google Sheet with this email. This gives the service account access to the spreadsheet, which was created on another account (not the service account). Phew. That’s all the Google infrastructure stuff. I promise. Now we can get down to business writing Python code. Google has an API for Sheets, like it does for all Google Drive products. There is nothing you cannot do with its Python library. Still you would be mad to use it. My hard line on spreadsheets is they are a portable, visual way to deliver data to business users. A rectangle of data, cell A1 on the top left. Not to play Bob Ross🎨🖌 with conditional formatting, islands of data in the same worksheet forming archipelagos, or creating a Tableau-like dashboard of charts. Not to say all those things aren’t great. I’ve went down those rabbit holes with spreadsheet automation many times. It’s just, the payoff-to-time-spent-coding ratio falls off a cliff pretty fast when you dive into all the features Google Sheets built in over the years. This article is about data in, data out. Fastest time to solution wins. On the Python data side, that means using pandas DataFrames. On the Google Sheets connector side, it’s more up in the air. Time to go shopping on GitHub. For that, here are three of my favorite third party Python libraries wrapping the Google Sheets API: EZSheets Al Sweigart can do no wrong. His book Automate the Boring Stuff With Python singlehandedly taught me how to code for money. I still reference it a few times a month. Sweigart is this giant brain with a talent for taking the complex and breaking it down into baby food I can digest. EZSheets (GitHub) is his creation, along with sibling interfaces for Gmail, Calendar, and Drive. EZSheets shines with its clear methods for updating a selection of data all at once. Also, for selecting columns and rows. I haven’t found another library that captures the complexity of iterating over cells quite like this one. Other libraries are no better than the Sheets API, where the nested for loops for processing data give me vertigo. gspread gspread (GitHub) is a library by another brain, Anton Burnashev. gspread is popular to the point of being the de facto library for Python developers wanting to work with Google Sheets. And with good reason. The documentation is great, the source code is clear with a sensible layout and good docstrings. Plus, gspread’s interface wraps some Google Sheets formatting functionality. It also has methods for working with pandas and NumPy arrays. gspread-dataframe (Winner) A wrapper for the gspread library built by Robin Thomas, gspread-dataframe (GitHub) is my go-to package for reading and writing Google Sheets with DataFrames. The documentation is good, but somewhat unnecessary. The source code is brief, with two functions, get_as_dataframe and set_with_dataframe. gspread-dataframe is what we will be using for this tutorial. Scenario: We have a table of data about for an ongoing movie night. Coworkers need to add values to a column manually on a daily basis. As we schedule new movie nights, we need to collect the handwritten data entered in the sheet, as well as add new movies to the top. This example is fiction, but I have had multiple clients that were medium size tech companies request just this feature. You can imagine there is a database with tables like movies and movienights, and there's a view function joining those into this one table that the coordinators of the movie night help fill out. Short of a full-blown web app or form software, using a spreadsheet as the presentation and data entry layers is actually quite convenient. Bonus: With pandas 1.1.0, we can generate a markdown table without index from a method on the DataFrame! df.head(1).to_markdown(index=False)​‘| IMDB URL | IMDB Score | Length | Attendees | Mood | Staff Notes |\n|: — — — — — — — — — — — — — — — — — — — — — — — — — — — | — — — — — — -:| — — — — -:| — — — — — — :|: — — — -|: — — — — — — — — — — -|\n| https://m.imdb.com/title/tt5013056/?ref_=m_ttls_tt_20 | 7.9 | 106 | 18 | 😓 | Bane flies a plane ✈ |’ Our data: First install gspread_dataframe. Since it is a wrapper for gspread, we will need that library and its oauth2client dependency. pip install gspread_dataframe gspread oauth2client Check you can connect to the sheet: $ ipythonPython 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)]Type 'copyright', 'credits' or 'license' for more informationIPython 7.12.0 -- An enhanced Interactive Python. Type '?' for help.In [1]: import gspread ...: from gspread_dataframe import (get_as_dataframe, ...: set_with_dataframe) ...: from oauth2client.service_account import ServiceAccountCredentials ...: scope = ["https://spreadsheets.google.com/feeds", ...: "https://www.googleapis.com/auth/drive"] ...: credentials = ServiceAccountCredentials.from_json_keyfile_name("./credentials.json", scope) ...: gc = gspread.authorize(credentials) ...: gc.open_by_key("11zmk55OFpFL5HW_MhPfqfC-GjRQvHlI_M-jtHcBzyzA")Out[1]: <Spreadsheet 'Google Sheets Automation! 🐍' id:11zmk55OFpFL5HW_MhPfqfC-GjRQvHlI_M-jtHcBzyzA> If you have a problem connecting, read the Exception thrown by gspread, it's pretty informative. Remember, the downloaded keys for the JSON file has a client_email. That email needs the sheet shared with it. The OAuth library needs access to the credentials.json at the right file path. Remember to rename the file to credentials.json. Now to write to Google Sheets. # gsheets.py​import gspreadfrom gspread_dataframe import (get_as_dataframe, set_with_dataframe)from oauth2client.service_account import ServiceAccountCredentialsimport pandas as pd​​FILE_KEY: str = "11zmk55OFpFL5HW_MhPfqfC-GjRQvHlI_M-jtHcBzyzA"SHEET_NAME: str = "movie night"​​def _get_worksheet( key:str, worksheet_name:str, creds:"filepath to Google account credentials"="credentials.json", ) -> gspread.Worksheet: """ return a gspread Worksheet instance for given Google Sheets workbook/worksheet """ scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"] credentials = ServiceAccountCredentials.from_json_keyfile_name(creds, scope) gc = gspread.authorize(credentials) wb = gc.open_by_key(key) sheet = wb.worksheet(worksheet_name) return sheet​​def write(sheet: gspread.Worksheet, df: pd.DataFrame, **options) -> None: set_with_dataframe(sheet, df, include_index=False, resize=True, **options) And using these functions: sh: gspread.Worksheet = _get_worksheet(FILE_KEY, SHEET_NAME)​""" Here you are getting your data. Usually this would be adatabase. But it could be another spreadsheet, serialized data,generated from Python code... wherever. """df = pd.read_pickle("./movienight2.pickle")​write(sh, df) Options for set_as_dataframe (credit Robin Thomas, gspread-dataframe.py): :param worksheet: the gspread worksheet to set with content of DataFrame.:param dataframe: the DataFrame.:param include_index: if True, include the DataFrame's index as an additional column. Defaults to False.:param include_column_header: if True, add a header row or rows before data with column names. (If include_index is True, the index's name(s) will be used as its columns' headers.) Defaults to True.:param resize: if True, changes the worksheet's size to match the shape of the provided DataFrame. If False, worksheet will only be resized as necessary to contain the DataFrame contents. Defaults to False.:param allow_formulas: if True, interprets `=foo` as a formula in cell values; otherwise all text beginning with `=` is escaped to avoid its interpretation as a formula. Defaults to True. Python writes to Google Sheets! Nice! (I love seeing computers perform drudgery. Means it’s saving me work. 😄) Notice how the resize=True option makes the worksheet fit the DataFrame shape. Could be better though. Will make a few tweaks to the DataFrame before writing to the sheet. The dates are formatted as datetime. Also, let’s use the power of cell formulas to neaten up the IMDB links. def _to_string(df: pd.DataFrame, *cols) -> pd.DataFrame: for col in cols: if col in df.columns: df[col] = df[col].astype(str) return df​def hyperlink_formula(df: pd.DataFrame, textcol: str, linkcol: str) -> pd.DataFrame: ix: int = df.columns.tolist().index(textcol) vals: pd.Series = \ '=HYPERLINK("' + df["IMDB URL"] + '", "' + df["Movie"] + '")' df.insert(ix, textcol+"_temp", vals) df.drop([textcol, linkcol], axis=1, inplace=True) df.rename(columns={textcol+"_temp": textcol}, inplace=True) return df​sh: gspread.Worksheet = _get_worksheet(FILE_KEY, SHEET_NAME)df = pd.read_pickle("./movienight1.pickle")​df = _to_string(df, "Date", "Movie")df = hyperlink_formula(df, "Movie", "IMDB URL")​write(sh, df) Much cleaner. And now, the Movie column has working hyperlinks! As new movies nights are inserted into the database, the scheduler running the Python script updates the sheet: The movie night secretary counts heads, reads the crowd, and writes comments on the event. Things people still do better than machines. Now for Python to slurp it up. To upsert into a database, save in an S3 bucket, file system, or somewhere. For this we use the other function provided by gspread_dataframe: get_as_dataframe. Options for set_as_dataframe (again, credit Robin Thomas, gspread-dataframe.py): :param worksheet: the worksheet.:param evaluate_formulas: if True, get the value of a cell after formula evaluation; otherwise get the formula itself if present. Defaults to False.:param nrows: if present and not None, limits the number of rows read from the worksheet. Defaults to None. See pandas documentation for more info on this parameter.:param \*\*options: all the options for pandas.io.parsers.TextParser, according to the version of pandas that is installed. (Note: TextParser supports only the default 'python' parser engine, not the C engine.) The code: def read(sheet: gspread.Worksheet, **options) -> pd.DataFrame: return get_as_dataframe(sheet, evaluate_formulas=False, **options)​df = read(sh)(df[df["Movie"].str.contains("Rambo")] .values.tolist()) This returns: [['2020-08-28', '=HYPERLINK("https://m.imdb.com/title/tt1206885/?ref_=m_ttls_tt_119", "Rambo: Last Blood")', 6.2, 89, 1.0, '😭😭😭😭', 'WHY AM I THE ONLY ONE HERE???']] Spreadsheets are a powerful tool. And with amazing wrappers around the Google Sheets API like EZSheets, gspread and gspread_dataframe, a lot of the work managing them with Python is done for you. Instead of getting in the way of business automation, using spreadsheets as part of the toolchain with Python... it’s saves us a lot of time and unfun work. Best of all, it stops the ritual of “passing the spreadsheet”. It is a wonderful thing! Here’s the link again to the Google Sheet used in this article.
[ { "code": null, "e": 402, "s": 171, "text": "Maybe it’s from too many hours behind the keyboard. But sometimes my reading and watching on the internet gives me the feeling I’m one of an endangered species of developer. One who’s working inside spreadsheets. Every single day." }, { "code": null, "e": 626, "s": 402, "text": "Can you believe it? Developers, going about their lives like spreadsheets don’t exist. If you are one of these people, I’d like to meet you. To know that you exist, and this isn’t all a paranoid rant raging between my ears." }, { "code": null, "e": 889, "s": 626, "text": "For the rest of us, spreadsheets are very much a thing. Love them or hate them, those binary rows and columns are going nowhere. To cut the philosophy lesson short: spreadsheets are. Every non-developer employee save the cleaning staff lives inside spreadsheets." }, { "code": null, "e": 1015, "s": 889, "text": "“Spreadsheets are.” Submit this existential bombshell to a university; an honorary doctorate in philosophy is sure to follow." }, { "code": null, "e": 1186, "s": 1015, "text": "Excel and Google Sheets, they’re going nowhere; neither is our productivity until we put automation between us and the knowledge worker ritual of passing the spreadsheet." }, { "code": null, "e": 1406, "s": 1186, "text": "Personally, I love a good spreadsheet. For munging data, quick and dirty calculations, visualizing 1-dimensional times series... 4 out of 5 times I will open Excel or Google Sheets, rather than fire up a Jupyter server." }, { "code": null, "e": 1704, "s": 1406, "text": "Except, spreadsheetitis in a business is a symptom of not knowing how to move data. I have personally seen the “human router” problem so bad where more than 20 (twenty!) people touched a version of a spreadsheet before it was finally–mercifully–put to rest in “the database” (another spreadsheet)." }, { "code": null, "e": 1853, "s": 1704, "text": "And THE Spreadsheet. You know the business is in data hell when there’s The Spreadsheet, with a capital “S”. The one managers think is the business." }, { "code": null, "e": 2197, "s": 1853, "text": "There’s a few libraries we will talk about using for Google Sheets I/O in Python. No matter the approach, you have to enable the Google Sheets API inside the maze-like console for Google Cloud Platform (Google’s version of AWS and Azure). Fortunately Google–go figure–has a great search feature in the console that we’ll use to get you set up." }, { "code": null, "e": 2512, "s": 2197, "text": "Go to console.cloud.google.com/, sign in with the Google account with access to the spreadsheet you want to automate. The API is available for both GSuite and free Google accounts. If it’s a work-owned spreadsheet, the admin with GCP access is going to have to follow these steps and give you the credentials file." }, { "code": null, "e": 2839, "s": 2512, "text": "Select the project in the navbar on the top. Every resource is kept inside a project, like resource groups in Azure. If you do not have one yet, select the project dropdown and “NEW PROJECT”. Then search for “Google Sheets API”, which if you are a sadist and want to explore the dashboard by mouse, is under “APIs & Services”." }, { "code": null, "e": 2857, "s": 2839, "text": "“Enable” the API." }, { "code": null, "e": 2907, "s": 2857, "text": "Now you need to do the same for Google Drive API." }, { "code": null, "e": 2998, "s": 2907, "text": "Next up, you need to create a service account, which you will then create credentials for." }, { "code": null, "e": 3005, "s": 2998, "text": "Steps:" }, { "code": null, "e": 3117, "s": 3005, "text": "You are in Google Cloud Platform > Google Sheets API at console.cloud.google.com/apis/api/sheets.googleapis.com" }, { "code": null, "e": 3165, "s": 3117, "text": "Go to credentials 🗝 Credentials on the sidebar." }, { "code": null, "e": 3317, "s": 3165, "text": "Select + CREATE CREDENTIALS > Service Account. OAuth is a different story. This article covers a server-side, in-house use. Create the service account." }, { "code": null, "e": 3404, "s": 3317, "text": "Next view is to select an IAM role for the service account. This is optional, skip it." }, { "code": null, "e": 3483, "s": 3404, "text": "Next up is “Grant users access to this service account (optional)”. Also skip." }, { "code": null, "e": 3695, "s": 3483, "text": "Now you are back on the “Service accounts for project [PROJECT NAME]” screen. Select the service account in the table, either clicking on the hyperlinked Email field, or hamburger menu (three dots) > Create key." }, { "code": null, "e": 3808, "s": 3695, "text": "Either way, ADD KEY or Create key, select JSON key type and CREATE. This downloads a JSON file to your computer." }, { "code": null, "e": 4034, "s": 3808, "text": "Last thing: the spreadsheet. Here I created one for this example. Note the highlighted section of the URL in the Omnibar. That is the document’s ID. Most libraries give the choice of referencing the whole URL or just this ID." }, { "code": null, "e": 4097, "s": 4034, "text": "You can take a look at and download the spreadsheet from here." }, { "code": null, "e": 4390, "s": 4097, "text": "Open the credentials.json file you downloaded from GCP for the service account. Copy the email value in the client_email property. Share the Google Sheet with this email. This gives the service account access to the spreadsheet, which was created on another account (not the service account)." }, { "code": null, "e": 4451, "s": 4390, "text": "Phew. That’s all the Google infrastructure stuff. I promise." }, { "code": null, "e": 4504, "s": 4451, "text": "Now we can get down to business writing Python code." }, { "code": null, "e": 4634, "s": 4504, "text": "Google has an API for Sheets, like it does for all Google Drive products. There is nothing you cannot do with its Python library." }, { "code": null, "e": 4668, "s": 4634, "text": "Still you would be mad to use it." }, { "code": null, "e": 4973, "s": 4668, "text": "My hard line on spreadsheets is they are a portable, visual way to deliver data to business users. A rectangle of data, cell A1 on the top left. Not to play Bob Ross🎨🖌 with conditional formatting, islands of data in the same worksheet forming archipelagos, or creating a Tableau-like dashboard of charts." }, { "code": null, "e": 5243, "s": 4973, "text": "Not to say all those things aren’t great. I’ve went down those rabbit holes with spreadsheet automation many times. It’s just, the payoff-to-time-spent-coding ratio falls off a cliff pretty fast when you dive into all the features Google Sheets built in over the years." }, { "code": null, "e": 5315, "s": 5243, "text": "This article is about data in, data out. Fastest time to solution wins." }, { "code": null, "e": 5469, "s": 5315, "text": "On the Python data side, that means using pandas DataFrames. On the Google Sheets connector side, it’s more up in the air. Time to go shopping on GitHub." }, { "code": null, "e": 5570, "s": 5469, "text": "For that, here are three of my favorite third party Python libraries wrapping the Google Sheets API:" }, { "code": null, "e": 5579, "s": 5570, "text": "EZSheets" }, { "code": null, "e": 5745, "s": 5579, "text": "Al Sweigart can do no wrong. His book Automate the Boring Stuff With Python singlehandedly taught me how to code for money. I still reference it a few times a month." }, { "code": null, "e": 5958, "s": 5745, "text": "Sweigart is this giant brain with a talent for taking the complex and breaking it down into baby food I can digest. EZSheets (GitHub) is his creation, along with sibling interfaces for Gmail, Calendar, and Drive." }, { "code": null, "e": 6302, "s": 5958, "text": "EZSheets shines with its clear methods for updating a selection of data all at once. Also, for selecting columns and rows. I haven’t found another library that captures the complexity of iterating over cells quite like this one. Other libraries are no better than the Sheets API, where the nested for loops for processing data give me vertigo." }, { "code": null, "e": 6310, "s": 6302, "text": "gspread" }, { "code": null, "e": 6495, "s": 6310, "text": "gspread (GitHub) is a library by another brain, Anton Burnashev. gspread is popular to the point of being the de facto library for Python developers wanting to work with Google Sheets." }, { "code": null, "e": 6753, "s": 6495, "text": "And with good reason. The documentation is great, the source code is clear with a sensible layout and good docstrings. Plus, gspread’s interface wraps some Google Sheets formatting functionality. It also has methods for working with pandas and NumPy arrays." }, { "code": null, "e": 6780, "s": 6753, "text": "gspread-dataframe (Winner)" }, { "code": null, "e": 6939, "s": 6780, "text": "A wrapper for the gspread library built by Robin Thomas, gspread-dataframe (GitHub) is my go-to package for reading and writing Google Sheets with DataFrames." }, { "code": null, "e": 7079, "s": 6939, "text": "The documentation is good, but somewhat unnecessary. The source code is brief, with two functions, get_as_dataframe and set_with_dataframe." }, { "code": null, "e": 7141, "s": 7079, "text": "gspread-dataframe is what we will be using for this tutorial." }, { "code": null, "e": 7410, "s": 7141, "text": "Scenario: We have a table of data about for an ongoing movie night. Coworkers need to add values to a column manually on a daily basis. As we schedule new movie nights, we need to collect the handwritten data entered in the sheet, as well as add new movies to the top." }, { "code": null, "e": 7726, "s": 7410, "text": "This example is fiction, but I have had multiple clients that were medium size tech companies request just this feature. You can imagine there is a database with tables like movies and movienights, and there's a view function joining those into this one table that the coordinators of the movie night help fill out." }, { "code": null, "e": 7866, "s": 7726, "text": "Short of a full-blown web app or form software, using a spreadsheet as the presentation and data entry layers is actually quite convenient." }, { "code": null, "e": 7971, "s": 7866, "text": "Bonus: With pandas 1.1.0, we can generate a markdown table without index from a method on the DataFrame!" }, { "code": null, "e": 8317, "s": 7971, "text": "df.head(1).to_markdown(index=False)​‘| IMDB URL | IMDB Score | Length | Attendees | Mood | Staff Notes |\\n|: — — — — — — — — — — — — — — — — — — — — — — — — — — — | — — — — — — -:| — — — — -:| — — — — — — :|: — — — -|: — — — — — — — — — — -|\\n| https://m.imdb.com/title/tt5013056/?ref_=m_ttls_tt_20 | 7.9 | 106 | 18 | 😓 | Bane flies a plane ✈ |’" }, { "code": null, "e": 8327, "s": 8317, "text": "Our data:" }, { "code": null, "e": 8454, "s": 8327, "text": "First install gspread_dataframe. Since it is a wrapper for gspread, we will need that library and its oauth2client dependency." }, { "code": null, "e": 8505, "s": 8454, "text": "pip install gspread_dataframe gspread oauth2client" }, { "code": null, "e": 8541, "s": 8505, "text": "Check you can connect to the sheet:" }, { "code": null, "e": 9400, "s": 8541, "text": "$ ipythonPython 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)]Type 'copyright', 'credits' or 'license' for more informationIPython 7.12.0 -- An enhanced Interactive Python. Type '?' for help.In [1]: import gspread ...: from gspread_dataframe import (get_as_dataframe, ...: set_with_dataframe) ...: from oauth2client.service_account import ServiceAccountCredentials ...: scope = [\"https://spreadsheets.google.com/feeds\", ...: \"https://www.googleapis.com/auth/drive\"] ...: credentials = ServiceAccountCredentials.from_json_keyfile_name(\"./credentials.json\", scope) ...: gc = gspread.authorize(credentials) ...: gc.open_by_key(\"11zmk55OFpFL5HW_MhPfqfC-GjRQvHlI_M-jtHcBzyzA\")Out[1]: <Spreadsheet 'Google Sheets Automation! 🐍' id:11zmk55OFpFL5HW_MhPfqfC-GjRQvHlI_M-jtHcBzyzA>" }, { "code": null, "e": 9736, "s": 9400, "text": "If you have a problem connecting, read the Exception thrown by gspread, it's pretty informative. Remember, the downloaded keys for the JSON file has a client_email. That email needs the sheet shared with it. The OAuth library needs access to the credentials.json at the right file path. Remember to rename the file to credentials.json." }, { "code": null, "e": 9767, "s": 9736, "text": "Now to write to Google Sheets." }, { "code": null, "e": 10838, "s": 9767, "text": "# gsheets.py​import gspreadfrom gspread_dataframe import (get_as_dataframe, set_with_dataframe)from oauth2client.service_account import ServiceAccountCredentialsimport pandas as pd​​FILE_KEY: str = \"11zmk55OFpFL5HW_MhPfqfC-GjRQvHlI_M-jtHcBzyzA\"SHEET_NAME: str = \"movie night\"​​def _get_worksheet( key:str, worksheet_name:str, creds:\"filepath to Google account credentials\"=\"credentials.json\", ) -> gspread.Worksheet: \"\"\" return a gspread Worksheet instance for given Google Sheets workbook/worksheet \"\"\" scope = [\"https://spreadsheets.google.com/feeds\", \"https://www.googleapis.com/auth/drive\"] credentials = ServiceAccountCredentials.from_json_keyfile_name(creds, scope) gc = gspread.authorize(credentials) wb = gc.open_by_key(key) sheet = wb.worksheet(worksheet_name) return sheet​​def write(sheet: gspread.Worksheet, df: pd.DataFrame, **options) -> None: set_with_dataframe(sheet, df, include_index=False, resize=True, **options)" }, { "code": null, "e": 10865, "s": 10838, "text": "And using these functions:" }, { "code": null, "e": 11149, "s": 10865, "text": "sh: gspread.Worksheet = _get_worksheet(FILE_KEY, SHEET_NAME)​\"\"\" Here you are getting your data. Usually this would be adatabase. But it could be another spreadsheet, serialized data,generated from Python code... wherever. \"\"\"df = pd.read_pickle(\"./movienight2.pickle\")​write(sh, df)" }, { "code": null, "e": 11223, "s": 11149, "text": "Options for set_as_dataframe (credit Robin Thomas, gspread-dataframe.py):" }, { "code": null, "e": 12080, "s": 11223, "text": ":param worksheet: the gspread worksheet to set with content of DataFrame.:param dataframe: the DataFrame.:param include_index: if True, include the DataFrame's index as an additional column. Defaults to False.:param include_column_header: if True, add a header row or rows before data with column names. (If include_index is True, the index's name(s) will be used as its columns' headers.) Defaults to True.:param resize: if True, changes the worksheet's size to match the shape of the provided DataFrame. If False, worksheet will only be resized as necessary to contain the DataFrame contents. Defaults to False.:param allow_formulas: if True, interprets `=foo` as a formula in cell values; otherwise all text beginning with `=` is escaped to avoid its interpretation as a formula. Defaults to True." }, { "code": null, "e": 12112, "s": 12080, "text": "Python writes to Google Sheets!" }, { "code": null, "e": 12270, "s": 12112, "text": "Nice! (I love seeing computers perform drudgery. Means it’s saving me work. 😄) Notice how the resize=True option makes the worksheet fit the DataFrame shape." }, { "code": null, "e": 12472, "s": 12270, "text": "Could be better though. Will make a few tweaks to the DataFrame before writing to the sheet. The dates are formatted as datetime. Also, let’s use the power of cell formulas to neaten up the IMDB links." }, { "code": null, "e": 13228, "s": 12472, "text": "def _to_string(df: pd.DataFrame, *cols) -> pd.DataFrame: for col in cols: if col in df.columns: df[col] = df[col].astype(str) return df​def hyperlink_formula(df: pd.DataFrame, textcol: str, linkcol: str) -> pd.DataFrame: ix: int = df.columns.tolist().index(textcol) vals: pd.Series = \\ '=HYPERLINK(\"' + df[\"IMDB URL\"] + '\", \"' + df[\"Movie\"] + '\")' df.insert(ix, textcol+\"_temp\", vals) df.drop([textcol, linkcol], axis=1, inplace=True) df.rename(columns={textcol+\"_temp\": textcol}, inplace=True) return df​sh: gspread.Worksheet = _get_worksheet(FILE_KEY, SHEET_NAME)df = pd.read_pickle(\"./movienight1.pickle\")​df = _to_string(df, \"Date\", \"Movie\")df = hyperlink_formula(df, \"Movie\", \"IMDB URL\")​write(sh, df)" }, { "code": null, "e": 13292, "s": 13228, "text": "Much cleaner. And now, the Movie column has working hyperlinks!" }, { "code": null, "e": 13404, "s": 13292, "text": "As new movies nights are inserted into the database, the scheduler running the Python script updates the sheet:" }, { "code": null, "e": 13540, "s": 13404, "text": "The movie night secretary counts heads, reads the crowd, and writes comments on the event. Things people still do better than machines." }, { "code": null, "e": 13647, "s": 13540, "text": "Now for Python to slurp it up. To upsert into a database, save in an S3 bucket, file system, or somewhere." }, { "code": null, "e": 13731, "s": 13647, "text": "For this we use the other function provided by gspread_dataframe: get_as_dataframe." }, { "code": null, "e": 13812, "s": 13731, "text": "Options for set_as_dataframe (again, credit Robin Thomas, gspread-dataframe.py):" }, { "code": null, "e": 14418, "s": 13812, "text": ":param worksheet: the worksheet.:param evaluate_formulas: if True, get the value of a cell after formula evaluation; otherwise get the formula itself if present. Defaults to False.:param nrows: if present and not None, limits the number of rows read from the worksheet. Defaults to None. See pandas documentation for more info on this parameter.:param \\*\\*options: all the options for pandas.io.parsers.TextParser, according to the version of pandas that is installed. (Note: TextParser supports only the default 'python' parser engine, not the C engine.)" }, { "code": null, "e": 14428, "s": 14418, "text": "The code:" }, { "code": null, "e": 14674, "s": 14428, "text": "def read(sheet: gspread.Worksheet, **options) -> pd.DataFrame: return get_as_dataframe(sheet, evaluate_formulas=False, **options)​df = read(sh)(df[df[\"Movie\"].str.contains(\"Rambo\")] .values.tolist())" }, { "code": null, "e": 14688, "s": 14674, "text": "This returns:" }, { "code": null, "e": 14859, "s": 14688, "text": "[['2020-08-28', '=HYPERLINK(\"https://m.imdb.com/title/tt1206885/?ref_=m_ttls_tt_119\", \"Rambo: Last Blood\")', 6.2, 89, 1.0, '😭😭😭😭', 'WHY AM I THE ONLY ONE HERE???']]" }, { "code": null, "e": 15055, "s": 14859, "text": "Spreadsheets are a powerful tool. And with amazing wrappers around the Google Sheets API like EZSheets, gspread and gspread_dataframe, a lot of the work managing them with Python is done for you." }, { "code": null, "e": 15300, "s": 15055, "text": "Instead of getting in the way of business automation, using spreadsheets as part of the toolchain with Python... it’s saves us a lot of time and unfun work. Best of all, it stops the ritual of “passing the spreadsheet”. It is a wonderful thing!" } ]