title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Sum of n numbers in Python using while loop
Theory of Computation In this post, you will learn how to find the sum of n numbers in Python using a while loop. The while loop in Python is used to iterate over a block of code as long as the truth expression (condition) is true. In the given example, we have used the if..else statement in combination with a while loop to calculate the sum of n numbers. First, we have taken a number input from the user and stored it in a variable num. Initially, the sum is initialized to 0. Then, we have used the while loop to iterate until num gets zero. In every iteration of the loop, we have added the num to sum, and the value of num is decreased by 1. # Sum of natural numbers up to num num = int(input("Enter a number: ")) if num < 0: print("Please enter a positive number") else: sum = 0 # use while loop to iterate until zero while(num > 0): sum += num num -= 1 print("The result is", sum) Enter a number: 15 The result is 120 The above example shows the sum of the first 15 positive numbers (0-15). Enter a number: 22 The result is 253 Jan 3 Stateful vs Stateless A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities... A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities... Dec 29 Best programming language to learn in 2021 In this article, we have mentioned the analyzed results of the best programming language for 2021... In this article, we have mentioned the analyzed results of the best programming language for 2021... Dec 20 How is Python best for mobile app development? Python has a set of useful Libraries and Packages that minimize the use of code... Python has a set of useful Libraries and Packages that minimize the use of code... July 18 Learn all about Emoji In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more... In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more... Jan 10 Data Science Recruitment of Freshers In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician... In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician... eTutorialsPoint©Copyright 2016-2022. All Rights Reserved.
[ { "code": null, "e": 112, "s": 90, "text": "Theory of Computation" }, { "code": null, "e": 322, "s": 112, "text": "In this post, you will learn how to find the sum of n numbers in Python using a while loop. The while loop in Python is used to iterate over a block of code as long as the truth expression (condition) is true." }, { "code": null, "e": 739, "s": 322, "text": "In the given example, we have used the if..else statement in combination with a while loop to calculate the sum of n numbers. First, we have taken a number input from the user and stored it in a variable num. Initially, the sum is initialized to 0. Then, we have used the while loop to iterate until num gets zero. In every iteration of the loop, we have added the num to sum, and the value of num is decreased by 1." }, { "code": null, "e": 1016, "s": 739, "text": "# Sum of natural numbers up to num\n\nnum = int(input(\"Enter a number: \")) \n\nif num < 0:\n print(\"Please enter a positive number\")\nelse:\n sum = 0\n \n # use while loop to iterate until zero\n while(num > 0):\n sum += num\n num -= 1\n print(\"The result is\", sum)" }, { "code": null, "e": 1053, "s": 1016, "text": "Enter a number: 15\nThe result is 120" }, { "code": null, "e": 1126, "s": 1053, "text": "The above example shows the sum of the first 15 positive numbers (0-15)." }, { "code": null, "e": 1163, "s": 1126, "text": "Enter a number: 22\nThe result is 253" }, { "code": null, "e": 1309, "s": 1163, "text": "\nJan 3\nStateful vs Stateless\nA Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...\n" }, { "code": null, "e": 1425, "s": 1309, "text": "A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities..." }, { "code": null, "e": 1578, "s": 1425, "text": "\nDec 29\nBest programming language to learn in 2021\nIn this article, we have mentioned the analyzed results of the best programming language for 2021...\n" }, { "code": null, "e": 1679, "s": 1578, "text": "In this article, we have mentioned the analyzed results of the best programming language for 2021..." }, { "code": null, "e": 1818, "s": 1679, "text": "\nDec 20\nHow is Python best for mobile app development?\nPython has a set of useful Libraries and Packages that minimize the use of code...\n" }, { "code": null, "e": 1901, "s": 1818, "text": "Python has a set of useful Libraries and Packages that minimize the use of code..." }, { "code": null, "e": 2067, "s": 1901, "text": "\nJuly 18\nLearn all about Emoji\nIn this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...\n" }, { "code": null, "e": 2201, "s": 2067, "text": "In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more..." }, { "code": null, "e": 2368, "s": 2201, "text": "\nJan 10\nData Science Recruitment of Freshers\nIn this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...\n" }, { "code": null, "e": 2489, "s": 2368, "text": "In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician..." } ]
How to disable form submit on enter button using jQuery ? - GeeksforGeeks
03 Aug, 2021 There are two methods to submit a form, Using the “enter” key: When the user press the “enter” key from the keyboard then the form submit. This method works only when one (or more) of the elements in the concerned form have focus. Using the “mouse click”: The user clicks on the “submit” form button. Approach: First, We need to select the form. This is done using the query selector: $("#form-id") Now, we need to handle the form submission process. For this purpose, we use event handling. Since we need whether the user presses the enter key, we add an event listener on every keypress event: on("keypress", function (event) {} ) This event handler will check every keyboard press, so we require a check on the “enter” key. To accomplish this, we can use the event.keyCode or event.which; event.keyCode: The “keyCode” property returns the Unicode character code of the key that triggered the keypress event.event.which: The “which” property returns the keyboard key (or mouse button) that was pressed for the event.Now, we know that the enter key is pressed, we need to stop the default behavior. To accomplish this, we include a call to the jQuery method preventDefault() to stop the event propagating. preventDefault() preventDefault(): This method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. Example: <!DOCTYPE html> <html> <head> <title> Disable form submission on pressing enter key </title> <style> body { display: block; margin-top: 8%; } h1 { color:green; text-align:center; } form { display: block; margin: 0 auto; text-align: center; } input { margin: 4px; } </style> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script></head> <body> <h1>GeeksforGeeks</h1> <form id="form-id"> <label>First name:</label> <input type="text" name="first-name"> <br /> <label>Last name:</label> <input type="text" name="last-name"> <br /> <input type="submit" value="Submit" /> </form> <script> $(window).ready(function() { $("#form-id").on("keypress", function (event) { console.log("aaya"); var keyPressed = event.keyCode || event.which; if (keyPressed === 13) { alert("You pressed the Enter key!!"); event.preventDefault(); return false; } }); }); </script> </body> </html> Output: jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc jQuery-Misc Picked CSS HTML JQuery Web Technologies Web technologies Questions Write From Home HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 25387, "s": 25359, "text": "\n03 Aug, 2021" }, { "code": null, "e": 25427, "s": 25387, "text": "There are two methods to submit a form," }, { "code": null, "e": 25618, "s": 25427, "text": "Using the “enter” key: When the user press the “enter” key from the keyboard then the form submit. This method works only when one (or more) of the elements in the concerned form have focus." }, { "code": null, "e": 25688, "s": 25618, "text": "Using the “mouse click”: The user clicks on the “submit” form button." }, { "code": null, "e": 26020, "s": 25688, "text": "Approach: First, We need to select the form. This is done using the query selector: $(\"#form-id\") Now, we need to handle the form submission process. For this purpose, we use event handling. Since we need whether the user presses the enter key, we add an event listener on every keypress event: on(\"keypress\", function (event) {} )" }, { "code": null, "e": 26179, "s": 26020, "text": "This event handler will check every keyboard press, so we require a check on the “enter” key. To accomplish this, we can use the event.keyCode or event.which;" }, { "code": null, "e": 26611, "s": 26179, "text": "event.keyCode: The “keyCode” property returns the Unicode character code of the key that triggered the keypress event.event.which: The “which” property returns the keyboard key (or mouse button) that was pressed for the event.Now, we know that the enter key is pressed, we need to stop the default behavior. To accomplish this, we include a call to the jQuery method preventDefault() to stop the event propagating. preventDefault()" }, { "code": null, "e": 26754, "s": 26611, "text": "preventDefault(): This method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur." }, { "code": null, "e": 26763, "s": 26754, "text": "Example:" }, { "code": " <!DOCTYPE html> <html> <head> <title> Disable form submission on pressing enter key </title> <style> body { display: block; margin-top: 8%; } h1 { color:green; text-align:center; } form { display: block; margin: 0 auto; text-align: center; } input { margin: 4px; } </style> <script src=\"https://code.jquery.com/jquery-3.4.1.min.js\" integrity=\"sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=\" crossorigin=\"anonymous\"></script></head> <body> <h1>GeeksforGeeks</h1> <form id=\"form-id\"> <label>First name:</label> <input type=\"text\" name=\"first-name\"> <br /> <label>Last name:</label> <input type=\"text\" name=\"last-name\"> <br /> <input type=\"submit\" value=\"Submit\" /> </form> <script> $(window).ready(function() { $(\"#form-id\").on(\"keypress\", function (event) { console.log(\"aaya\"); var keyPressed = event.keyCode || event.which; if (keyPressed === 13) { alert(\"You pressed the Enter key!!\"); event.preventDefault(); return false; } }); }); </script> </body> </html> ", "e": 28192, "s": 26763, "text": null }, { "code": null, "e": 28200, "s": 28192, "text": "Output:" }, { "code": null, "e": 28468, "s": 28200, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 28605, "s": 28468, "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": 28614, "s": 28605, "text": "CSS-Misc" }, { "code": null, "e": 28624, "s": 28614, "text": "HTML-Misc" }, { "code": null, "e": 28636, "s": 28624, "text": "jQuery-Misc" }, { "code": null, "e": 28643, "s": 28636, "text": "Picked" }, { "code": null, "e": 28647, "s": 28643, "text": "CSS" }, { "code": null, "e": 28652, "s": 28647, "text": "HTML" }, { "code": null, "e": 28659, "s": 28652, "text": "JQuery" }, { "code": null, "e": 28676, "s": 28659, "text": "Web Technologies" }, { "code": null, "e": 28703, "s": 28676, "text": "Web technologies Questions" }, { "code": null, "e": 28719, "s": 28703, "text": "Write From Home" }, { "code": null, "e": 28724, "s": 28719, "text": "HTML" }, { "code": null, "e": 28822, "s": 28724, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28880, "s": 28822, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28917, "s": 28880, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28981, "s": 28917, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 29022, "s": 28981, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 29059, "s": 29022, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29119, "s": 29059, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 29180, "s": 29119, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 29233, "s": 29180, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 29283, "s": 29233, "text": "How to Insert Form Data into Database using PHP ?" } ]
Perl goto Statement
Perl does support a goto statement. There are three forms: goto LABEL, goto EXPR, and goto &NAME. goto LABEL The goto LABEL form jumps to the statement labeled with LABEL and resumes execution from there. goto EXPR The goto EXPR form is just a generalization of goto LABEL. It expects the expression to return a label name and then jumps to that labeled statement. goto &NAME It substitutes a call to the named subroutine for the currently running subroutine. The syntax for a goto statements is as follows − goto LABEL or goto EXPR or goto &NAME The following program shows the most frequently used form of goto statement − #/usr/local/bin/perl $a = 10; LOOP:do { if( $a == 15) { # skip the iteration. $a = $a + 1; # use goto LABEL form goto LOOP; } print "Value of a = $a\n"; $a = $a + 1; } while( $a < 20 ); When the above code is executed, it produces the following result − Value of a = 10 Value of a = 11 Value of a = 12 Value of a = 13 Value of a = 14 Value of a = 16 Value of a = 17 Value of a = 18 Value of a = 19 Following example shows the usage of goto EXPR form. Here we are using two strings and then concatenating them using string concatenation operator (.). Finally, its forming a label and goto is being used to jump to the label − #/usr/local/bin/perl $a = 10; $str1 = "LO"; $str2 = "OP"; LOOP:do { if( $a == 15) { # skip the iteration. $a = $a + 1; # use goto EXPR form goto $str1.$str2; } print "Value of a = $a\n"; $a = $a + 1; } while( $a < 20 ); When the above code is executed, it produces the following result − Value of a = 10 Value of a = 11 Value of a = 12 Value of a = 13 Value of a = 14 Value of a = 16 Value of a = 17 Value of a = 18 Value of a = 19 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2318, "s": 2220, "text": "Perl does support a goto statement. There are three forms: goto LABEL, goto EXPR, and goto &NAME." }, { "code": null, "e": 2329, "s": 2318, "text": "goto LABEL" }, { "code": null, "e": 2425, "s": 2329, "text": "The goto LABEL form jumps to the statement labeled with LABEL and resumes execution from there." }, { "code": null, "e": 2435, "s": 2425, "text": "goto EXPR" }, { "code": null, "e": 2585, "s": 2435, "text": "The goto EXPR form is just a generalization of goto LABEL. It expects the expression to return a label name and then jumps to that labeled statement." }, { "code": null, "e": 2596, "s": 2585, "text": "goto &NAME" }, { "code": null, "e": 2680, "s": 2596, "text": "It substitutes a call to the named subroutine for the currently running subroutine." }, { "code": null, "e": 2729, "s": 2680, "text": "The syntax for a goto statements is as follows −" }, { "code": null, "e": 2772, "s": 2729, "text": "goto LABEL\n\nor\n\ngoto EXPR\n\nor\n\ngoto &NAME\n" }, { "code": null, "e": 2850, "s": 2772, "text": "The following program shows the most frequently used form of goto statement −" }, { "code": null, "e": 3077, "s": 2850, "text": "#/usr/local/bin/perl\n \n$a = 10;\n\nLOOP:do {\n if( $a == 15) {\n # skip the iteration.\n $a = $a + 1;\n # use goto LABEL form\n goto LOOP;\n }\n print \"Value of a = $a\\n\";\n $a = $a + 1;\n} while( $a < 20 );" }, { "code": null, "e": 3145, "s": 3077, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 3290, "s": 3145, "text": "Value of a = 10\nValue of a = 11\nValue of a = 12\nValue of a = 13\nValue of a = 14\nValue of a = 16\nValue of a = 17\nValue of a = 18\nValue of a = 19\n" }, { "code": null, "e": 3517, "s": 3290, "text": "Following example shows the usage of goto EXPR form. Here we are using two strings and then concatenating them using string concatenation operator (.). Finally, its forming a label and goto is being used to jump to the label −" }, { "code": null, "e": 3778, "s": 3517, "text": "#/usr/local/bin/perl\n \n$a = 10;\n$str1 = \"LO\";\n$str2 = \"OP\";\n\nLOOP:do {\n if( $a == 15) {\n # skip the iteration.\n $a = $a + 1;\n # use goto EXPR form\n goto $str1.$str2;\n }\n print \"Value of a = $a\\n\";\n $a = $a + 1;\n} while( $a < 20 );" }, { "code": null, "e": 3846, "s": 3778, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 3991, "s": 3846, "text": "Value of a = 10\nValue of a = 11\nValue of a = 12\nValue of a = 13\nValue of a = 14\nValue of a = 16\nValue of a = 17\nValue of a = 18\nValue of a = 19\n" }, { "code": null, "e": 4026, "s": 3991, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4040, "s": 4026, "text": " Devi Killada" }, { "code": null, "e": 4075, "s": 4040, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4095, "s": 4075, "text": " Harshit Srivastava" }, { "code": null, "e": 4128, "s": 4095, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 4144, "s": 4128, "text": " TELCOMA Global" }, { "code": null, "e": 4177, "s": 4144, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 4194, "s": 4177, "text": " Mohammad Nauman" }, { "code": null, "e": 4227, "s": 4194, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 4250, "s": 4227, "text": " Stone River ELearning" }, { "code": null, "e": 4285, "s": 4250, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4308, "s": 4285, "text": " Stone River ELearning" }, { "code": null, "e": 4315, "s": 4308, "text": " Print" }, { "code": null, "e": 4326, "s": 4315, "text": " Add Notes" } ]
Python | Foreground Extraction in an Image using Grabcut Algorithm - GeeksforGeeks
05 Jan, 2022 Let’s discuss an efficient method of foreground extraction from the background in an image. The idea here is to find the foreground, and remove the background. Foreground extract is any technique which allows an image’s foreground to be extracted for further processing like object recognition, tracking etc. The algorithm used for foreground extraction here is GrabCut Algorithm. In this algorithm, the region is drawn in accordance with the foreground, a rectangle is drawn over it. This is the rectangle that encases our main object. The region coordinates are decided over understanding the foreground mask. But this segmentation is not perfect, as it may have marked some foreground region as background and vice versa. This problem can be avoided manually. This foreground extraction technique functions just like a green screen in cinematics. The region of interest is decided by the amount of segmentation of foreground and background is to be performed and is chosen by the user. Everything outside the ROI is considered as background and turned black. The elements inside the ROI is still unknown. Then Gaussian Mixture Model(GMM) is used for modeling the foreground and the background. Then, in accordance with the data provided by the user, the GMM learns and creates labels for the unknown pixels and each pixel is clustered in terms of color statistics. A graph is generated from this pixel distribution where the pixels are considered as nodes and two additional nodes are added that is the Source node and Sink node. All the foreground pixels are connected to the Source node and every Background pixel is connected to the Sink node. The weights of edges connecting pixels to the Source node and to the End node are defined by the probability of a pixel being in the foreground or in the background. If huge dissimilarity is found in pixel color, the low weight is assigned to that edge. Then the algorithm is applied to segment the graph. The algorithm segments the graph into two, separating the source node and the sink node with the help of a cost function which is the sum of all weights of the edges that are segmented. After the segmentation, the pixels that are connected to the Source node is labeled as foreground and those pixels which are connected to the Sink node is labeled as background. This process is done for multiple iterations as specified by the user. This gives us the extracted foreground. The function used here is cv2.grabCut() Syntax: cv2.grabCut(image, mask, rectangle, backgroundModel, foregroundModel, iterationCount[, mode])Parameters: image: Input 8-bit 3-channel image. mask: Input/output 8-bit single-channel mask. The mask is initialized by the function when mode is set to GC_INIT_WITH_RECT. Its elements may have one of following values: GC_BGD defines an obvious background pixels.GC_FGD defines an obvious foreground (object) pixel.GC_PR_BGD defines a possible background pixel.GC_PR_FGD defines a possible foreground pixel. GC_BGD defines an obvious background pixels. GC_FGD defines an obvious foreground (object) pixel. GC_PR_BGD defines a possible background pixel. GC_PR_FGD defines a possible foreground pixel. rectangle: It is the region of interest containing a segmented object. The pixels outside of the ROI are marked as obvious background. The parameter is only used when mode==GC_INIT_WITH_RECT. backgroundModel: Temporary array for the background model. foregroundModel: Temporary array for the foreground model. iterationCount: Number of iterations the algorithm should make before returning the result. Note that the result can be refined with further calls with mode==GC_INIT_WITH_MASK or mode==GC_EVAL. mode: It defines the Operation mode. It can be one of the following: GC_INIT_WITH_RECT: The function initializes the state and the mask using the provided rectangle. After that it runs iterCount iterations of the algorithm.GC_INIT_WITH_MASK: The function initializes the state using the provided mask. Note that GC_INIT_WITH_RECT and GC_INIT_WITH_MASK can be combined. Then, all the pixels outside of the ROI are automatically initialized with GC_BGD.GC_EVAL: The value means that the algorithm should just resume. GC_INIT_WITH_RECT: The function initializes the state and the mask using the provided rectangle. After that it runs iterCount iterations of the algorithm. GC_INIT_WITH_MASK: The function initializes the state using the provided mask. Note that GC_INIT_WITH_RECT and GC_INIT_WITH_MASK can be combined. Then, all the pixels outside of the ROI are automatically initialized with GC_BGD. GC_EVAL: The value means that the algorithm should just resume. Below is the implementation: Python3 # Python program to illustrate# foreground extraction using# GrabCut algorithm # organize importsimport numpy as npimport cv2from matplotlib import pyplot as plt # path to input image specified and# image is loaded with imread commandimage = cv2.imread('image.jpg') # create a simple mask image similar# to the loaded image, with the# shape and return typemask = np.zeros(image.shape[:2], np.uint8) # specify the background and foreground model# using numpy the array is constructed of 1 row# and 65 columns, and all array elements are 0# Data type for the array is np.float64 (default)backgroundModel = np.zeros((1, 65), np.float64)foregroundModel = np.zeros((1, 65), np.float64) # define the Region of Interest (ROI)# as the coordinates of the rectangle# where the values are entered as# (startingPoint_x, startingPoint_y, width, height)# these coordinates are according to the input image# it may vary for different imagesrectangle = (20, 100, 150, 150) # apply the grabcut algorithm with appropriate# values as parameters, number of iterations = 3# cv2.GC_INIT_WITH_RECT is used because# of the rectangle mode is usedcv2.grabCut(image, mask, rectangle, backgroundModel, foregroundModel, 3, cv2.GC_INIT_WITH_RECT) # In the new mask image, pixels will# be marked with four flags# four flags denote the background / foreground# mask is changed, all the 0 and 2 pixels# are converted to the background# mask is changed, all the 1 and 3 pixels# are now the part of the foreground# the return type is also mentioned,# this gives us the final maskmask2 = np.where((mask == 2)|(mask == 0), 0, 1).astype('uint8') # The final mask is multiplied with# the input image to give the segmented image.image = image * mask2[:, :, np.newaxis] # output segmented image with colorbarplt.imshow(image)plt.colorbar()plt.show() Input Image: Output: Here we have taken an input image of size 500X281 and decided the coordinates for rectangle accordingly. The output image shows how the object in the left of the image becomes the part of the foreground and the background is subtracted. avtarkumar719 Image-Processing OpenCV Technical Scripter 2018 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Bar Plot in Matplotlib Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Python - Call function from another file loops in python Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method Python Lambda Functions
[ { "code": null, "e": 23927, "s": 23899, "text": "\n05 Jan, 2022" }, { "code": null, "e": 24779, "s": 23927, "text": "Let’s discuss an efficient method of foreground extraction from the background in an image. The idea here is to find the foreground, and remove the background. Foreground extract is any technique which allows an image’s foreground to be extracted for further processing like object recognition, tracking etc. The algorithm used for foreground extraction here is GrabCut Algorithm. In this algorithm, the region is drawn in accordance with the foreground, a rectangle is drawn over it. This is the rectangle that encases our main object. The region coordinates are decided over understanding the foreground mask. But this segmentation is not perfect, as it may have marked some foreground region as background and vice versa. This problem can be avoided manually. This foreground extraction technique functions just like a green screen in cinematics. " }, { "code": null, "e": 25037, "s": 24779, "text": "The region of interest is decided by the amount of segmentation of foreground and background is to be performed and is chosen by the user. Everything outside the ROI is considered as background and turned black. The elements inside the ROI is still unknown." }, { "code": null, "e": 25297, "s": 25037, "text": "Then Gaussian Mixture Model(GMM) is used for modeling the foreground and the background. Then, in accordance with the data provided by the user, the GMM learns and creates labels for the unknown pixels and each pixel is clustered in terms of color statistics." }, { "code": null, "e": 25745, "s": 25297, "text": "A graph is generated from this pixel distribution where the pixels are considered as nodes and two additional nodes are added that is the Source node and Sink node. All the foreground pixels are connected to the Source node and every Background pixel is connected to the Sink node. The weights of edges connecting pixels to the Source node and to the End node are defined by the probability of a pixel being in the foreground or in the background." }, { "code": null, "e": 26071, "s": 25745, "text": "If huge dissimilarity is found in pixel color, the low weight is assigned to that edge. Then the algorithm is applied to segment the graph. The algorithm segments the graph into two, separating the source node and the sink node with the help of a cost function which is the sum of all weights of the edges that are segmented." }, { "code": null, "e": 26360, "s": 26071, "text": "After the segmentation, the pixels that are connected to the Source node is labeled as foreground and those pixels which are connected to the Sink node is labeled as background. This process is done for multiple iterations as specified by the user. This gives us the extracted foreground." }, { "code": null, "e": 26401, "s": 26360, "text": "The function used here is cv2.grabCut() " }, { "code": null, "e": 26516, "s": 26401, "text": "Syntax: cv2.grabCut(image, mask, rectangle, backgroundModel, foregroundModel, iterationCount[, mode])Parameters: " }, { "code": null, "e": 26552, "s": 26516, "text": "image: Input 8-bit 3-channel image." }, { "code": null, "e": 26913, "s": 26552, "text": "mask: Input/output 8-bit single-channel mask. The mask is initialized by the function when mode is set to GC_INIT_WITH_RECT. Its elements may have one of following values: GC_BGD defines an obvious background pixels.GC_FGD defines an obvious foreground (object) pixel.GC_PR_BGD defines a possible background pixel.GC_PR_FGD defines a possible foreground pixel." }, { "code": null, "e": 26958, "s": 26913, "text": "GC_BGD defines an obvious background pixels." }, { "code": null, "e": 27011, "s": 26958, "text": "GC_FGD defines an obvious foreground (object) pixel." }, { "code": null, "e": 27058, "s": 27011, "text": "GC_PR_BGD defines a possible background pixel." }, { "code": null, "e": 27105, "s": 27058, "text": "GC_PR_FGD defines a possible foreground pixel." }, { "code": null, "e": 27297, "s": 27105, "text": "rectangle: It is the region of interest containing a segmented object. The pixels outside of the ROI are marked as obvious background. The parameter is only used when mode==GC_INIT_WITH_RECT." }, { "code": null, "e": 27356, "s": 27297, "text": "backgroundModel: Temporary array for the background model." }, { "code": null, "e": 27415, "s": 27356, "text": "foregroundModel: Temporary array for the foreground model." }, { "code": null, "e": 27609, "s": 27415, "text": "iterationCount: Number of iterations the algorithm should make before returning the result. Note that the result can be refined with further calls with mode==GC_INIT_WITH_MASK or mode==GC_EVAL." }, { "code": null, "e": 28124, "s": 27609, "text": "mode: It defines the Operation mode. It can be one of the following: GC_INIT_WITH_RECT: The function initializes the state and the mask using the provided rectangle. After that it runs iterCount iterations of the algorithm.GC_INIT_WITH_MASK: The function initializes the state using the provided mask. Note that GC_INIT_WITH_RECT and GC_INIT_WITH_MASK can be combined. Then, all the pixels outside of the ROI are automatically initialized with GC_BGD.GC_EVAL: The value means that the algorithm should just resume." }, { "code": null, "e": 28279, "s": 28124, "text": "GC_INIT_WITH_RECT: The function initializes the state and the mask using the provided rectangle. After that it runs iterCount iterations of the algorithm." }, { "code": null, "e": 28508, "s": 28279, "text": "GC_INIT_WITH_MASK: The function initializes the state using the provided mask. Note that GC_INIT_WITH_RECT and GC_INIT_WITH_MASK can be combined. Then, all the pixels outside of the ROI are automatically initialized with GC_BGD." }, { "code": null, "e": 28572, "s": 28508, "text": "GC_EVAL: The value means that the algorithm should just resume." }, { "code": null, "e": 28603, "s": 28572, "text": "Below is the implementation: " }, { "code": null, "e": 28611, "s": 28603, "text": "Python3" }, { "code": "# Python program to illustrate# foreground extraction using# GrabCut algorithm # organize importsimport numpy as npimport cv2from matplotlib import pyplot as plt # path to input image specified and# image is loaded with imread commandimage = cv2.imread('image.jpg') # create a simple mask image similar# to the loaded image, with the# shape and return typemask = np.zeros(image.shape[:2], np.uint8) # specify the background and foreground model# using numpy the array is constructed of 1 row# and 65 columns, and all array elements are 0# Data type for the array is np.float64 (default)backgroundModel = np.zeros((1, 65), np.float64)foregroundModel = np.zeros((1, 65), np.float64) # define the Region of Interest (ROI)# as the coordinates of the rectangle# where the values are entered as# (startingPoint_x, startingPoint_y, width, height)# these coordinates are according to the input image# it may vary for different imagesrectangle = (20, 100, 150, 150) # apply the grabcut algorithm with appropriate# values as parameters, number of iterations = 3# cv2.GC_INIT_WITH_RECT is used because# of the rectangle mode is usedcv2.grabCut(image, mask, rectangle, backgroundModel, foregroundModel, 3, cv2.GC_INIT_WITH_RECT) # In the new mask image, pixels will# be marked with four flags# four flags denote the background / foreground# mask is changed, all the 0 and 2 pixels# are converted to the background# mask is changed, all the 1 and 3 pixels# are now the part of the foreground# the return type is also mentioned,# this gives us the final maskmask2 = np.where((mask == 2)|(mask == 0), 0, 1).astype('uint8') # The final mask is multiplied with# the input image to give the segmented image.image = image * mask2[:, :, np.newaxis] # output segmented image with colorbarplt.imshow(image)plt.colorbar()plt.show()", "e": 30452, "s": 28611, "text": null }, { "code": null, "e": 30467, "s": 30452, "text": "Input Image: " }, { "code": null, "e": 30477, "s": 30467, "text": "Output: " }, { "code": null, "e": 30715, "s": 30477, "text": "Here we have taken an input image of size 500X281 and decided the coordinates for rectangle accordingly. The output image shows how the object in the left of the image becomes the part of the foreground and the background is subtracted. " }, { "code": null, "e": 30729, "s": 30715, "text": "avtarkumar719" }, { "code": null, "e": 30746, "s": 30729, "text": "Image-Processing" }, { "code": null, "e": 30753, "s": 30746, "text": "OpenCV" }, { "code": null, "e": 30777, "s": 30753, "text": "Technical Scripter 2018" }, { "code": null, "e": 30784, "s": 30777, "text": "Python" }, { "code": null, "e": 30803, "s": 30784, "text": "Technical Scripter" }, { "code": null, "e": 30901, "s": 30803, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30910, "s": 30901, "text": "Comments" }, { "code": null, "e": 30923, "s": 30910, "text": "Old Comments" }, { "code": null, "e": 30959, "s": 30923, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 30982, "s": 30959, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 31021, "s": 30982, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 31054, "s": 31021, "text": "Python | Convert set into a list" }, { "code": null, "e": 31103, "s": 31054, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 31144, "s": 31103, "text": "Python - Call function from another file" }, { "code": null, "e": 31160, "s": 31144, "text": "loops in python" }, { "code": null, "e": 31211, "s": 31160, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 31243, "s": 31211, "text": "Python Dictionary keys() method" } ]
Angular Material 7 - Toolbar
The <mat-toolbar>, an Angular Directive, is used to create a toolbar to show title, header or any action button. <mat-toolbar> - Represents the main container. <mat-toolbar> - Represents the main container. <mat-toolbar-row> - Add a new row. <mat-toolbar-row> - Add a new row. In this chapter, we will showcase the configuration required to draw a toolbar control using Angular Material. Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter − Following is the content of the modified module descriptor app.module.ts. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {MatToolbarModule} from '@angular/material' import {FormsModule, ReactiveFormsModule} from '@angular/forms'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, MatToolbarModule, FormsModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Following is the content of the modified CSS file app.component.css. .filler { flex: 1 1 auto; } .gap { margin-right: 10px; } Following is the content of the modified HTML host file app.component.html. <mat-toolbar color = "primary"> <span class = "gap">File</span> <span>Edit</span> <span class = "filler"></span> <span>About</span> </mat-toolbar> Verify the result. As first, we've created a toolbar spanning the complete page. Then labels are added. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2868, "s": 2755, "text": "The <mat-toolbar>, an Angular Directive, is used to create a toolbar to show title, header or any action button." }, { "code": null, "e": 2915, "s": 2868, "text": "<mat-toolbar> - Represents the main container." }, { "code": null, "e": 2962, "s": 2915, "text": "<mat-toolbar> - Represents the main container." }, { "code": null, "e": 2997, "s": 2962, "text": "<mat-toolbar-row> - Add a new row." }, { "code": null, "e": 3032, "s": 2997, "text": "<mat-toolbar-row> - Add a new row." }, { "code": null, "e": 3143, "s": 3032, "text": "In this chapter, we will showcase the configuration required to draw a toolbar control using Angular Material." }, { "code": null, "e": 3254, "s": 3143, "text": "Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −" }, { "code": null, "e": 3328, "s": 3254, "text": "Following is the content of the modified module descriptor app.module.ts." }, { "code": null, "e": 3945, "s": 3328, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport {BrowserAnimationsModule} from '@angular/platform-browser/animations';\nimport {MatToolbarModule} from '@angular/material'\nimport {FormsModule, ReactiveFormsModule} from '@angular/forms';\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n MatToolbarModule,\n FormsModule,\n ReactiveFormsModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 4014, "s": 3945, "text": "Following is the content of the modified CSS file app.component.css." }, { "code": null, "e": 4077, "s": 4014, "text": ".filler {\n flex: 1 1 auto;\n}\n.gap {\n margin-right: 10px;\n}" }, { "code": null, "e": 4153, "s": 4077, "text": "Following is the content of the modified HTML host file app.component.html." }, { "code": null, "e": 4312, "s": 4153, "text": "<mat-toolbar color = \"primary\">\n <span class = \"gap\">File</span>\n <span>Edit</span>\n <span class = \"filler\"></span>\n <span>About</span>\n</mat-toolbar>" }, { "code": null, "e": 4331, "s": 4312, "text": "Verify the result." }, { "code": null, "e": 4393, "s": 4331, "text": "As first, we've created a toolbar spanning the complete page." }, { "code": null, "e": 4416, "s": 4393, "text": "Then labels are added." }, { "code": null, "e": 4451, "s": 4416, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4465, "s": 4451, "text": " Anadi Sharma" }, { "code": null, "e": 4500, "s": 4465, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4514, "s": 4500, "text": " Anadi Sharma" }, { "code": null, "e": 4549, "s": 4514, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4569, "s": 4549, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 4604, "s": 4569, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4621, "s": 4604, "text": " Frahaan Hussain" }, { "code": null, "e": 4654, "s": 4621, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 4666, "s": 4654, "text": " Senol Atac" }, { "code": null, "e": 4701, "s": 4666, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4713, "s": 4701, "text": " Senol Atac" }, { "code": null, "e": 4720, "s": 4713, "text": " Print" }, { "code": null, "e": 4731, "s": 4720, "text": " Add Notes" } ]
Python Program to Check if a Number is a Strong Number
Strong number is a number whose sum of all digits’ factorial is equal to the number ‘n’. Factorial implies when we find the product of all the numbers below that number including that number and is denoted by ! (Exclamation sign), For example: 5! = 5x4x3x2x1 = 120. When it is required to check if a number is a strong number or not, the remainder/modulus operator and the ‘while’ loop can be used. Below is the demonstration of the same − Live Demo my_sum=0 my_num = 296 print("The number is") print(my_num) temp = my_num while(my_num): i=1 fact=1 remainder = my_num%10 while(i<=remainder): fact=fact*i i=i+1 my_sum = my_sum+fact my_num=my_num//10 if(my_sum == temp): print("The number is a strong number") else: print("The number is not a strong number") The number is 296 The number is not a strong number A sum is initialized to 0. A sum is initialized to 0. The number is defined and is displayed on the console. The number is defined and is displayed on the console. The number is defined to a temporary variable. The number is defined to a temporary variable. The while loop is used where the remainder is determined. The while loop is used where the remainder is determined. The while loop is used again to see whether the iterator is less than or equal to the remainder. The while loop is used again to see whether the iterator is less than or equal to the remainder. If it is less, the ‘fact’ variable is multiplied with the iterator. If it is less, the ‘fact’ variable is multiplied with the iterator. It is then incremented by 1. It is then incremented by 1. The sum value is added to the ‘fact’ variable. The sum value is added to the ‘fact’ variable. If the ‘temp’ variable and the sum are equal, it is considered a string number. If the ‘temp’ variable and the sum are equal, it is considered a string number.
[ { "code": null, "e": 1461, "s": 1062, "text": "Strong number is a number whose sum of all digits’ factorial is equal to the number ‘n’. Factorial implies when we find the product of all the numbers below that number including that number and is denoted by ! (Exclamation sign), For example: 5! = 5x4x3x2x1 = 120. When it is required to check if a number is a strong number or not, the remainder/modulus operator and the ‘while’ loop can be used." }, { "code": null, "e": 1502, "s": 1461, "text": "Below is the demonstration of the same −" }, { "code": null, "e": 1513, "s": 1502, "text": " Live Demo" }, { "code": null, "e": 1856, "s": 1513, "text": "my_sum=0\nmy_num = 296\nprint(\"The number is\")\nprint(my_num)\ntemp = my_num\nwhile(my_num):\n i=1\n fact=1\n remainder = my_num%10\n while(i<=remainder):\n fact=fact*i\n i=i+1\n my_sum = my_sum+fact\n my_num=my_num//10\nif(my_sum == temp):\n print(\"The number is a strong number\")\nelse:\n print(\"The number is not a strong number\")" }, { "code": null, "e": 1908, "s": 1856, "text": "The number is\n296\nThe number is not a strong number" }, { "code": null, "e": 1935, "s": 1908, "text": "A sum is initialized to 0." }, { "code": null, "e": 1962, "s": 1935, "text": "A sum is initialized to 0." }, { "code": null, "e": 2017, "s": 1962, "text": "The number is defined and is displayed on the console." }, { "code": null, "e": 2072, "s": 2017, "text": "The number is defined and is displayed on the console." }, { "code": null, "e": 2119, "s": 2072, "text": "The number is defined to a temporary variable." }, { "code": null, "e": 2166, "s": 2119, "text": "The number is defined to a temporary variable." }, { "code": null, "e": 2224, "s": 2166, "text": "The while loop is used where the remainder is determined." }, { "code": null, "e": 2282, "s": 2224, "text": "The while loop is used where the remainder is determined." }, { "code": null, "e": 2379, "s": 2282, "text": "The while loop is used again to see whether the iterator is less than or equal to the remainder." }, { "code": null, "e": 2476, "s": 2379, "text": "The while loop is used again to see whether the iterator is less than or equal to the remainder." }, { "code": null, "e": 2544, "s": 2476, "text": "If it is less, the ‘fact’ variable is multiplied with the iterator." }, { "code": null, "e": 2612, "s": 2544, "text": "If it is less, the ‘fact’ variable is multiplied with the iterator." }, { "code": null, "e": 2641, "s": 2612, "text": "It is then incremented by 1." }, { "code": null, "e": 2670, "s": 2641, "text": "It is then incremented by 1." }, { "code": null, "e": 2717, "s": 2670, "text": "The sum value is added to the ‘fact’ variable." }, { "code": null, "e": 2764, "s": 2717, "text": "The sum value is added to the ‘fact’ variable." }, { "code": null, "e": 2844, "s": 2764, "text": "If the ‘temp’ variable and the sum are equal, it is considered a string number." }, { "code": null, "e": 2924, "s": 2844, "text": "If the ‘temp’ variable and the sum are equal, it is considered a string number." } ]
Python Program to Implement Binary Search with Recursion
When it is required to implement binary search using recursion, a method can be defined, that checks if the index 'high' is greater than index 'low. Based on value present at 'mid' variable, the function is called again to search for the element. A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). Below is a demonstration for the same − Live Demo def binary_search(my_list, low, high, elem): if high >= low: mid = (high + low) // 2 if my_list[mid] == elem: return mid elif my_list[mid] > elem: return binary_search(my_list, low, mid - 1, elem) else: return binary_search(my_list, mid + 1, high, elem) else: return -1 my_list = [ 1, 9, 11, 21, 34, 54, 67, 90 ] elem_to_search = 1 print("The list is") print(my_list) my_result = binary_search(my_list,0,len(my_list)-1,elem_to_search) if my_result != -1: print("Element found at index ", str(my_result)) else: print("Element not found!") The list is [1, 9, 11, 21, 34, 54, 67, 90] Element found at index 0 A function named 'binary_search' is defined. It takes the list, the 'low' variable, 'high' variable and the element to be searched as parameter. Then, the variable 'mid' is assigned the average of 'high' and 'low' variables. If the element at 'mid' is same as the element that needs to be searched for, it is returned. Else, if the element at 'mid' position is greater than the element to be searched, the function is called again by passing different set of parameters. Else if the element at 'mid' position is less than the element to be searched, the function is called again by passing a different set of parameters. Now the list is defined, and the function is called by passing this list as parameter. This operation's data is stored in a variable. This variable is the output that is displayed on the console.
[ { "code": null, "e": 1309, "s": 1062, "text": "When it is required to implement binary search using recursion, a method can be defined, that checks if the index 'high' is greater than index 'low. Based on value present at 'mid' variable, the function is called again to search for the element." }, { "code": null, "e": 1436, "s": 1309, "text": "A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on)." }, { "code": null, "e": 1476, "s": 1436, "text": "Below is a demonstration for the same −" }, { "code": null, "e": 1486, "s": 1476, "text": "Live Demo" }, { "code": null, "e": 2101, "s": 1486, "text": "def binary_search(my_list, low, high, elem):\n if high >= low:\n mid = (high + low) // 2\n if my_list[mid] == elem:\n return mid\n elif my_list[mid] > elem:\n return binary_search(my_list, low, mid - 1, elem)\n else:\n return binary_search(my_list, mid + 1, high, elem)\n else:\n return -1\n \nmy_list = [ 1, 9, 11, 21, 34, 54, 67, 90 ]\nelem_to_search = 1\nprint(\"The list is\")\nprint(my_list)\n\nmy_result = binary_search(my_list,0,len(my_list)-1,elem_to_search)\n\nif my_result != -1:\n print(\"Element found at index \", str(my_result))\nelse:\n print(\"Element not found!\")" }, { "code": null, "e": 2169, "s": 2101, "text": "The list is\n[1, 9, 11, 21, 34, 54, 67, 90]\nElement found at index 0" }, { "code": null, "e": 2214, "s": 2169, "text": "A function named 'binary_search' is defined." }, { "code": null, "e": 2314, "s": 2214, "text": "It takes the list, the 'low' variable, 'high' variable and the element to be searched as parameter." }, { "code": null, "e": 2394, "s": 2314, "text": "Then, the variable 'mid' is assigned the average of 'high' and 'low' variables." }, { "code": null, "e": 2488, "s": 2394, "text": "If the element at 'mid' is same as the element that needs to be searched for, it is returned." }, { "code": null, "e": 2640, "s": 2488, "text": "Else, if the element at 'mid' position is greater than the element to be searched, the function is called again by passing different set of parameters." }, { "code": null, "e": 2790, "s": 2640, "text": "Else if the element at 'mid' position is less than the element to be searched, the function is called again by passing a different set of parameters." }, { "code": null, "e": 2877, "s": 2790, "text": "Now the list is defined, and the function is called by passing this list as parameter." }, { "code": null, "e": 2924, "s": 2877, "text": "This operation's data is stored in a variable." }, { "code": null, "e": 2986, "s": 2924, "text": "This variable is the output that is displayed on the console." } ]
Python | Introduction to PyQt5 - GeeksforGeeks
26 May, 2019 There are so many options provided by Python to develop GUI application and PyQt5 is one of them. PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library. A GUI application consists of Front-end and Back-end. PyQt5 has provided a tool called ‘QtDesigner’ to design the front-end by drag and drop method so that development can become faster and one can give more time on back-end stuff. Installation: First, we need to install PyQt5 library. For this, type the following command in the terminal or command prompt: pip install pyqt5 If successfully installed one can verify it by running the code: >>>import PyQt5 PyQt5 provides lots of tools and QtDesigner is one of them. For this run this command: pip install PyQt5-tools This is a simple app having a single button in the window. After clicking that button a message will appear “You clicked me”. Let’s start. First of all, we need to find QtDesigner to create the front-end part.– QtDesigner is present at ‘site-packages/pyqt5_tools’– For finding the location of site-packages write the following python code using any editor of your choice and then run:>>> import site >>> site.getsitepackages()– Run the application named ‘designer’. >>> import site >>> site.getsitepackages() – Run the application named ‘designer’. A window will open as shown in the figure:select the ‘Dialog without Button’ option and click ‘Create’ At the left side of the designer there will be various widgets which can be dragged and dropped in our window according to our requirement. Find and drag-and-drop ‘Push Button’ and ‘Label’. Change the text inside the widgets by right clicking it and selecting ‘Change plain text’. Keep the text of the Label blank. We have created our front-end layout, just save it at your desired location.Remember, this file will have .ui as extension. We need to convert the .ui file into .py file to get the python form of the widgets and attach necessary event listeners to them.Converting .ui file into .py file:For this we have to go to sitpackages directory in terminal or command prompt and run the command as shown below. Getting the location of sitepackages is mentioned previously.>>> cd “C:\\Users\\......\\Programs\\Python\\Python36-32\\lib\\site-packages” [Location of sitepackages]>>> pyuic5 “C:\Users\......\FILENAME.ui”[Exact location of .ui file] -o ” C:\Users\.......\FILENAME.py” [Location where want to put .py file] For this we have to go to sitpackages directory in terminal or command prompt and run the command as shown below. Getting the location of sitepackages is mentioned previously. >>> cd “C:\\Users\\......\\Programs\\Python\\Python36-32\\lib\\site-packages” [Location of sitepackages] >>> pyuic5 “C:\Users\......\FILENAME.ui”[Exact location of .ui file] -o ” C:\Users\.......\FILENAME.py” [Location where want to put .py file] Finally we will add signals and slot in the python code to make it fully functional.widget.signal.connect(slot)A signal is emitted by widgets after the occurrence of a certain kind of event like a click, Double click, etc.A slot is any callable function which will perform some action after the occurrence of an event. widget.signal.connect(slot) A signal is emitted by widgets after the occurrence of a certain kind of event like a click, Double click, etc.A slot is any callable function which will perform some action after the occurrence of an event. Run the app and click the button. Below is the code – import sysfrom PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(400, 300) self.pushButton = QtWidgets.QPushButton(Dialog) self.pushButton.setGeometry(QtCore.QRect(150, 70, 93, 28)) self.label = QtWidgets.QLabel(Dialog) self.label.setGeometry(QtCore.QRect(130, 149, 151, 31)) self.label.setText("") self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) # adding signal and slot self.pushButton.clicked.connect(self.showmsg) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Dialog")) self.pushButton.setText(_translate("Dialog", "Click")) def showmsg(self): # slot self.label.setText("You clicked me") if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_Dialog() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) Python-gui Python-PyQt 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 How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python Create a Pandas DataFrame from Lists sum() function in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 24101, "s": 24073, "text": "\n26 May, 2019" }, { "code": null, "e": 24403, "s": 24101, "text": "There are so many options provided by Python to develop GUI application and PyQt5 is one of them. PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library." }, { "code": null, "e": 24635, "s": 24403, "text": "A GUI application consists of Front-end and Back-end. PyQt5 has provided a tool called ‘QtDesigner’ to design the front-end by drag and drop method so that development can become faster and one can give more time on back-end stuff." }, { "code": null, "e": 24649, "s": 24635, "text": "Installation:" }, { "code": null, "e": 24762, "s": 24649, "text": "First, we need to install PyQt5 library. For this, type the following command in the terminal or command prompt:" }, { "code": null, "e": 24780, "s": 24762, "text": "pip install pyqt5" }, { "code": null, "e": 24845, "s": 24780, "text": "If successfully installed one can verify it by running the code:" }, { "code": null, "e": 24861, "s": 24845, "text": ">>>import PyQt5" }, { "code": null, "e": 24948, "s": 24861, "text": "PyQt5 provides lots of tools and QtDesigner is one of them. For this run this command:" }, { "code": null, "e": 24972, "s": 24948, "text": "pip install PyQt5-tools" }, { "code": null, "e": 25111, "s": 24972, "text": "This is a simple app having a single button in the window. After clicking that button a message will appear “You clicked me”. Let’s start." }, { "code": null, "e": 25438, "s": 25111, "text": "First of all, we need to find QtDesigner to create the front-end part.– QtDesigner is present at ‘site-packages/pyqt5_tools’– For finding the location of site-packages write the following python code using any editor of your choice and then run:>>> import site\n>>> site.getsitepackages()– Run the application named ‘designer’." }, { "code": null, "e": 25481, "s": 25438, "text": ">>> import site\n>>> site.getsitepackages()" }, { "code": null, "e": 25521, "s": 25481, "text": "– Run the application named ‘designer’." }, { "code": null, "e": 25624, "s": 25521, "text": "A window will open as shown in the figure:select the ‘Dialog without Button’ option and click ‘Create’" }, { "code": null, "e": 25764, "s": 25624, "text": "At the left side of the designer there will be various widgets which can be dragged and dropped in our window according to our requirement." }, { "code": null, "e": 25814, "s": 25764, "text": "Find and drag-and-drop ‘Push Button’ and ‘Label’." }, { "code": null, "e": 25939, "s": 25814, "text": "Change the text inside the widgets by right clicking it and selecting ‘Change plain text’. Keep the text of the Label blank." }, { "code": null, "e": 26063, "s": 25939, "text": "We have created our front-end layout, just save it at your desired location.Remember, this file will have .ui as extension." }, { "code": null, "e": 26647, "s": 26063, "text": "We need to convert the .ui file into .py file to get the python form of the widgets and attach necessary event listeners to them.Converting .ui file into .py file:For this we have to go to sitpackages directory in terminal or command prompt and run the command as shown below. Getting the location of sitepackages is mentioned previously.>>> cd “C:\\\\Users\\\\......\\\\Programs\\\\Python\\\\Python36-32\\\\lib\\\\site-packages” [Location of sitepackages]>>> pyuic5 “C:\\Users\\......\\FILENAME.ui”[Exact location of .ui file] -o ” C:\\Users\\.......\\FILENAME.py” [Location where want to put .py file]" }, { "code": null, "e": 26823, "s": 26647, "text": "For this we have to go to sitpackages directory in terminal or command prompt and run the command as shown below. Getting the location of sitepackages is mentioned previously." }, { "code": null, "e": 26928, "s": 26823, "text": ">>> cd “C:\\\\Users\\\\......\\\\Programs\\\\Python\\\\Python36-32\\\\lib\\\\site-packages” [Location of sitepackages]" }, { "code": null, "e": 27070, "s": 26928, "text": ">>> pyuic5 “C:\\Users\\......\\FILENAME.ui”[Exact location of .ui file] -o ” C:\\Users\\.......\\FILENAME.py” [Location where want to put .py file]" }, { "code": null, "e": 27389, "s": 27070, "text": "Finally we will add signals and slot in the python code to make it fully functional.widget.signal.connect(slot)A signal is emitted by widgets after the occurrence of a certain kind of event like a click, Double click, etc.A slot is any callable function which will perform some action after the occurrence of an event." }, { "code": null, "e": 27417, "s": 27389, "text": "widget.signal.connect(slot)" }, { "code": null, "e": 27625, "s": 27417, "text": "A signal is emitted by widgets after the occurrence of a certain kind of event like a click, Double click, etc.A slot is any callable function which will perform some action after the occurrence of an event." }, { "code": null, "e": 27659, "s": 27625, "text": "Run the app and click the button." }, { "code": null, "e": 27679, "s": 27659, "text": "Below is the code –" }, { "code": "import sysfrom PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName(\"Dialog\") Dialog.resize(400, 300) self.pushButton = QtWidgets.QPushButton(Dialog) self.pushButton.setGeometry(QtCore.QRect(150, 70, 93, 28)) self.label = QtWidgets.QLabel(Dialog) self.label.setGeometry(QtCore.QRect(130, 149, 151, 31)) self.label.setText(\"\") self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) # adding signal and slot self.pushButton.clicked.connect(self.showmsg) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate(\"Dialog\", \"Dialog\")) self.pushButton.setText(_translate(\"Dialog\", \"Click\")) def showmsg(self): # slot self.label.setText(\"You clicked me\") if __name__ == \"__main__\": app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_Dialog() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())", "e": 28815, "s": 27679, "text": null }, { "code": null, "e": 28826, "s": 28815, "text": "Python-gui" }, { "code": null, "e": 28838, "s": 28826, "text": "Python-PyQt" }, { "code": null, "e": 28845, "s": 28838, "text": "Python" }, { "code": null, "e": 28943, "s": 28845, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28952, "s": 28943, "text": "Comments" }, { "code": null, "e": 28965, "s": 28952, "text": "Old Comments" }, { "code": null, "e": 28983, "s": 28965, "text": "Python Dictionary" }, { "code": null, "e": 29018, "s": 28983, "text": "Read a file line by line in Python" }, { "code": null, "e": 29050, "s": 29018, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29092, "s": 29050, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29118, "s": 29092, "text": "Python String | replace()" }, { "code": null, "e": 29161, "s": 29118, "text": "Python program to convert a list to string" }, { "code": null, "e": 29205, "s": 29161, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29242, "s": 29205, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29267, "s": 29242, "text": "sum() function in Python" } ]
Python String center() Method - GeeksforGeeks
05 Aug, 2021 Python String center() method creates and returns a new string that is padded with the specified character. Syntax: string.center(length[, fillchar]) Parameters: length: length of the string after padding with the characters. fillchar: (optional) characters which need to be padded. If it’s not provided, space is taken as the default argument. Returns: Returns a string padded with specified fillchar and it doesn’t modify the original string. Python # Python program to illustrate# string center() in pythonstring = "geeks for geeks" new_string = string.center(24) # here filchar not provided so takes space by default.print "After padding String is: ", new_string Output: After padding String is: geeks for geeks Python # Python program to illustrate# string center() in pythonstring = "geeks for geeks" new_string = string.center(24, '#') # here fillchar is providedprint "After padding String is:", new_string Output: After padding String is: ####geeks for geeks##### AmiyaRanjanRout python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Iterate over a list in Python
[ { "code": null, "e": 23740, "s": 23712, "text": "\n05 Aug, 2021" }, { "code": null, "e": 23849, "s": 23740, "text": "Python String center() method creates and returns a new string that is padded with the specified character. " }, { "code": null, "e": 23858, "s": 23849, "text": "Syntax: " }, { "code": null, "e": 23892, "s": 23858, "text": "string.center(length[, fillchar])" }, { "code": null, "e": 23904, "s": 23892, "text": "Parameters:" }, { "code": null, "e": 23968, "s": 23904, "text": "length: length of the string after padding with the characters." }, { "code": null, "e": 24087, "s": 23968, "text": "fillchar: (optional) characters which need to be padded. If it’s not provided, space is taken as the default argument." }, { "code": null, "e": 24096, "s": 24087, "text": "Returns:" }, { "code": null, "e": 24187, "s": 24096, "text": "Returns a string padded with specified fillchar and it doesn’t modify the original string." }, { "code": null, "e": 24194, "s": 24187, "text": "Python" }, { "code": "# Python program to illustrate# string center() in pythonstring = \"geeks for geeks\" new_string = string.center(24) # here filchar not provided so takes space by default.print \"After padding String is: \", new_string", "e": 24411, "s": 24194, "text": null }, { "code": null, "e": 24420, "s": 24411, "text": "Output: " }, { "code": null, "e": 24466, "s": 24420, "text": "After padding String is: geeks for geeks" }, { "code": null, "e": 24473, "s": 24466, "text": "Python" }, { "code": "# Python program to illustrate# string center() in pythonstring = \"geeks for geeks\" new_string = string.center(24, '#') # here fillchar is providedprint \"After padding String is:\", new_string", "e": 24667, "s": 24473, "text": null }, { "code": null, "e": 24676, "s": 24667, "text": "Output: " }, { "code": null, "e": 24726, "s": 24676, "text": "After padding String is: ####geeks for geeks#####" }, { "code": null, "e": 24742, "s": 24726, "text": "AmiyaRanjanRout" }, { "code": null, "e": 24756, "s": 24742, "text": "python-string" }, { "code": null, "e": 24763, "s": 24756, "text": "Python" }, { "code": null, "e": 24861, "s": 24763, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24870, "s": 24861, "text": "Comments" }, { "code": null, "e": 24883, "s": 24870, "text": "Old Comments" }, { "code": null, "e": 24911, "s": 24883, "text": "Read JSON file using Python" }, { "code": null, "e": 24961, "s": 24911, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 24983, "s": 24961, "text": "Python map() function" }, { "code": null, "e": 25027, "s": 24983, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 25045, "s": 25027, "text": "Python Dictionary" }, { "code": null, "e": 25068, "s": 25045, "text": "Taking input in Python" }, { "code": null, "e": 25100, "s": 25068, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25135, "s": 25100, "text": "Read a file line by line in Python" }, { "code": null, "e": 25157, "s": 25135, "text": "Enumerate() in Python" } ]
Java program to find the cube root of a given number
Following is an example to find the cube root of a given number. import java.util.Scanner; public class FindingCubeRoot { public static void main(String args[]){ double i, precision = 0.000001; System.out.println("Enter a number ::"); Scanner sc = new Scanner(System.in); int num = sc.nextInt(); for(i = 1; (i*i*i) <= num; ++i); for(--i; (i*i*i) < num; i += precision); System.out.println("Cube root of the given number is "+i); } } Enter a number :: 125 Cube root of the given number is 5.0
[ { "code": null, "e": 1127, "s": 1062, "text": "Following is an example to find the cube root of a given number." }, { "code": null, "e": 1544, "s": 1127, "text": "import java.util.Scanner;\npublic class FindingCubeRoot {\n public static void main(String args[]){\n double i, precision = 0.000001;\n System.out.println(\"Enter a number ::\");\n Scanner sc = new Scanner(System.in);\n int num = sc.nextInt();\n\n for(i = 1; (i*i*i) <= num; ++i);\n for(--i; (i*i*i) < num; i += precision);\n System.out.println(\"Cube root of the given number is \"+i);\n }\n}" }, { "code": null, "e": 1603, "s": 1544, "text": "Enter a number ::\n125\nCube root of the given number is 5.0" } ]
How to add multi-language content in HTML?
The lang attribute in HTML allows you to set content for languages other than English. You can try to run the following code to implement lang attribute. Here, we have added content in French and Spanish as well. <!DOCTYPE html> <html> <body> <h2>English</h2> <p lang="en">This is demo text</p> <h2>French</h2> <p lang="fr">Ceci est un texte de démonstration</p> <h2>Spanish</h2> <p lang="es">Este es un texto de demostración</p> </body> </html>
[ { "code": null, "e": 1216, "s": 1062, "text": "The lang attribute in HTML allows you to set content for languages other than English. You can try to run the following code to implement lang attribute." }, { "code": null, "e": 1275, "s": 1216, "text": "Here, we have added content in French and Spanish as well." }, { "code": null, "e": 1564, "s": 1275, "text": "<!DOCTYPE html>\n<html>\n <body>\n <h2>English</h2>\n <p lang=\"en\">This is demo text</p>\n \n <h2>French</h2>\n <p lang=\"fr\">Ceci est un texte de démonstration</p>\n \n <h2>Spanish</h2>\n <p lang=\"es\">Este es un texto de demostración</p>\n </body>\n</html>" } ]
How to use action up event in android?
This example demonstrate about How use action up event in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:gravity="center" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> <TextView android:id="@+id/actionEvent" android:textSize="40sp" android:layout_marginTop="30dp" android:layout_width="wrap_content" android:layout_height="match_parent" /> </LinearLayout> In the above code, we have taken a text view to perform action up event. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.annotation.SuppressLint; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v4.view.MotionEventCompat; import android.support.v7.app.AppCompatActivity; import android.view.MotionEvent; import android.view.View; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { TextView textView; @SuppressLint({"RestrictedApi", "ClickableViewAccessibility"}) @RequiresApi(api = Build.VERSION_CODES.N) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView actionEvent = findViewById(R.id.actionEvent); actionEvent.setText("Action UP"); actionEvent.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int action = MotionEventCompat.getActionMasked(event); if (action == MotionEvent.ACTION_UP) { Toast.makeText(MainActivity.this, "Clicked on textview", Toast.LENGTH_LONG).show(); return true; } return false; } }); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code
[ { "code": null, "e": 1129, "s": 1062, "text": "This example demonstrate about How use action up event in android." }, { "code": null, "e": 1258, "s": 1129, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1323, "s": 1258, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1936, "s": 1323, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:gravity=\"center\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\"\n android:orientation=\"vertical\">\n <TextView\n android:id=\"@+id/actionEvent\"\n android:textSize=\"40sp\"\n android:layout_marginTop=\"30dp\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"match_parent\" />\n</LinearLayout>" }, { "code": null, "e": 2009, "s": 1936, "text": "In the above code, we have taken a text view to perform action up event." }, { "code": null, "e": 2066, "s": 2009, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3364, "s": 2066, "text": "package com.example.myapplication;\n\nimport android.annotation.SuppressLint;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v4.view.MotionEventCompat;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @SuppressLint({\"RestrictedApi\", \"ClickableViewAccessibility\"})\n @RequiresApi(api = Build.VERSION_CODES.N)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n TextView actionEvent = findViewById(R.id.actionEvent);\n actionEvent.setText(\"Action UP\");\n actionEvent.setOnTouchListener(new View.OnTouchListener() {\n @Override\n public boolean onTouch(View v, MotionEvent event) {\n int action = MotionEventCompat.getActionMasked(event);\n if (action == MotionEvent.ACTION_UP) {\n Toast.makeText(MainActivity.this, \"Clicked on textview\", Toast.LENGTH_LONG).show();\n return true;\n }\n return false;\n }\n });\n }\n}" }, { "code": null, "e": 3711, "s": 3364, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 3751, "s": 3711, "text": "Click here to download the project code" } ]
What are checked exceptions in Java?
A checked exception is an exception that occurs at the time of compilation, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation; the programmer should take care of (handle) these exceptions. if you use FileReader class in your program to read data from a file, if the file specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception. import java.io.File; import java.io.FileReader; public class FilenotFound_Demo { public static void main(String args[]) { File file = new File("E://file.txt"); FileReader fr = new FileReader(file); } } If you try to compile the above program, you will get the following exceptions. C:\>javac FilenotFound_Demo.java FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown FileReader fr = new FileReader(file); ^ 1 error
[ { "code": null, "e": 1320, "s": 1062, "text": "A checked exception is an exception that occurs at the time of compilation, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation; the programmer should take care of (handle) these exceptions." }, { "code": null, "e": 1548, "s": 1320, "text": "if you use FileReader class in your program to read data from a file, if the file specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception." }, { "code": null, "e": 1769, "s": 1548, "text": "import java.io.File;\nimport java.io.FileReader;\n\npublic class FilenotFound_Demo {\n public static void main(String args[]) {\n File file = new File(\"E://file.txt\");\n FileReader fr = new FileReader(file);\n }\n}" }, { "code": null, "e": 1849, "s": 1769, "text": "If you try to compile the above program, you will get the following exceptions." }, { "code": null, "e": 2070, "s": 1849, "text": "C:\\>javac FilenotFound_Demo.java\nFilenotFound_Demo.java:8: error: unreported exception\nFileNotFoundException; must be caught or declared to be thrown\n FileReader fr = new FileReader(file);\n ^\n1 error\n" } ]
JavaScript - Functions
A function is a group of reusable code which can be called anywhere in your program. This eliminates the need of writing the same code again and again. It helps programmers in writing modular codes. Functions allow a programmer to divide a big program into a number of small and manageable functions. Like any other advanced programming language, JavaScript also supports all the features necessary to write modular code using functions. You must have seen functions like alert() and write() in the earlier chapters. We were using these functions again and again, but they had been written in core JavaScript only once. JavaScript allows us to write our own functions as well. This section explains how to write your own functions in JavaScript. Before we use a function, we need to define it. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces. The basic syntax is shown here. <script type = "text/javascript"> <!-- function functionname(parameter-list) { statements } //--> </script> Try the following example. It defines a function called sayHello that takes no parameters − <script type = "text/javascript"> <!-- function sayHello() { alert("Hello there"); } //--> </script> To invoke a function somewhere later in the script, you would simply need to write the name of that function as shown in the following code. <html> <head> <script type = "text/javascript"> function sayHello() { document.write ("Hello there!"); } </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type = "button" onclick = "sayHello()" value = "Say Hello"> </form> <p>Use different text in write method and then try...</p> </body> </html> Click the following button to call the function Use different text in write method and then try... Till now, we have seen functions without parameters. But there is a facility to pass different parameters while calling a function. These passed parameters can be captured inside the function and any manipulation can be done over those parameters. A function can take multiple parameters separated by comma. Try the following example. We have modified our sayHello function here. Now it takes two parameters. <html> <head> <script type = "text/javascript"> function sayHello(name, age) { document.write (name + " is " + age + " years old."); } </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello"> </form> <p>Use different parameters inside the function and then try...</p> </body> </html> Click the following button to call the function Use different parameters inside the function and then try... A JavaScript function can have an optional return statement. This is required if you want to return a value from a function. This statement should be the last statement in a function. For example, you can pass two numbers in a function and then you can expect the function to return their multiplication in your calling program. Try the following example. It defines a function that takes two parameters and concatenates them before returning the resultant in the calling program. <html> <head> <script type = "text/javascript"> function concatenate(first, last) { var full; full = first + last; return full; } function secondFunction() { var result; result = concatenate('Zara', 'Ali'); document.write (result ); } </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type = "button" onclick = "secondFunction()" value = "Call Function"> </form> <p>Use different parameters inside the function and then try...</p> </body> </html> Click the following button to call the function Use different parameters inside the function and then try... There is a lot to learn about JavaScript functions, however we have covered the most important concepts in this tutorial. JavaScript Nested Functions JavaScript Nested Functions JavaScript Function( ) Constructor JavaScript Function( ) Constructor JavaScript Function Literals JavaScript Function Literals 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2767, "s": 2466, "text": "A function is a group of reusable code which can be called anywhere in your program. This eliminates the need of writing the same code again and again. It helps programmers in writing modular codes. Functions allow a programmer to divide a big program into a number of small and manageable functions." }, { "code": null, "e": 3086, "s": 2767, "text": "Like any other advanced programming language, JavaScript also supports all the features necessary to write modular code using functions. You must have seen functions like alert() and write() in the earlier chapters. We were using these functions again and again, but they had been written in core JavaScript only once." }, { "code": null, "e": 3212, "s": 3086, "text": "JavaScript allows us to write our own functions as well. This section explains how to write your own functions in JavaScript." }, { "code": null, "e": 3479, "s": 3212, "text": "Before we use a function, we need to define it. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces." }, { "code": null, "e": 3511, "s": 3479, "text": "The basic syntax is shown here." }, { "code": null, "e": 3647, "s": 3511, "text": "<script type = \"text/javascript\">\n <!--\n function functionname(parameter-list) {\n statements\n }\n //-->\n</script>\n" }, { "code": null, "e": 3739, "s": 3647, "text": "Try the following example. It defines a function called sayHello that takes no parameters −" }, { "code": null, "e": 3867, "s": 3739, "text": "<script type = \"text/javascript\">\n <!--\n function sayHello() {\n alert(\"Hello there\");\n }\n //-->\n</script>" }, { "code": null, "e": 4008, "s": 3867, "text": "To invoke a function somewhere later in the script, you would simply need to write the name of that function as shown in the following code." }, { "code": null, "e": 4462, "s": 4008, "text": "<html>\n <head> \n <script type = \"text/javascript\">\n function sayHello() {\n document.write (\"Hello there!\");\n }\n </script>\n \n </head>\n \n <body>\n <p>Click the following button to call the function</p> \n <form>\n <input type = \"button\" onclick = \"sayHello()\" value = \"Say Hello\">\n </form> \n <p>Use different text in write method and then try...</p>\n </body>\n</html>" }, { "code": null, "e": 4510, "s": 4462, "text": "Click the following button to call the function" }, { "code": null, "e": 4561, "s": 4510, "text": "Use different text in write method and then try..." }, { "code": null, "e": 4869, "s": 4561, "text": "Till now, we have seen functions without parameters. But there is a facility to pass different parameters while calling a function. These passed parameters can be captured inside the function and any manipulation can be done over those parameters. A function can take multiple parameters separated by comma." }, { "code": null, "e": 4970, "s": 4869, "text": "Try the following example. We have modified our sayHello function here. Now it takes two parameters." }, { "code": null, "e": 5472, "s": 4970, "text": "<html>\n <head> \n <script type = \"text/javascript\">\n function sayHello(name, age) {\n document.write (name + \" is \" + age + \" years old.\");\n }\n </script> \n </head>\n \n <body>\n <p>Click the following button to call the function</p> \n <form>\n <input type = \"button\" onclick = \"sayHello('Zara', 7)\" value = \"Say Hello\">\n </form> \n <p>Use different parameters inside the function and then try...</p>\n </body>\n</html>" }, { "code": null, "e": 5520, "s": 5472, "text": "Click the following button to call the function" }, { "code": null, "e": 5581, "s": 5520, "text": "Use different parameters inside the function and then try..." }, { "code": null, "e": 5765, "s": 5581, "text": "A JavaScript function can have an optional return statement. This is required if you want to return a value from a function. This statement should be the last statement in a function." }, { "code": null, "e": 5910, "s": 5765, "text": "For example, you can pass two numbers in a function and then you can expect the function to return their multiplication in your calling program." }, { "code": null, "e": 6062, "s": 5910, "text": "Try the following example. It defines a function that takes two parameters and concatenates them before returning the resultant in the calling program." }, { "code": null, "e": 6743, "s": 6062, "text": "<html>\n <head> \n <script type = \"text/javascript\">\n function concatenate(first, last) {\n var full;\n full = first + last;\n return full;\n }\n function secondFunction() {\n var result;\n result = concatenate('Zara', 'Ali');\n document.write (result );\n }\n </script> \n </head>\n \n <body>\n <p>Click the following button to call the function</p> \n <form>\n <input type = \"button\" onclick = \"secondFunction()\" value = \"Call Function\">\n </form> \n <p>Use different parameters inside the function and then try...</p> \n </body>\n</html>" }, { "code": null, "e": 6791, "s": 6743, "text": "Click the following button to call the function" }, { "code": null, "e": 6852, "s": 6791, "text": "Use different parameters inside the function and then try..." }, { "code": null, "e": 6974, "s": 6852, "text": "There is a lot to learn about JavaScript functions, however we have covered the most important concepts in this tutorial." }, { "code": null, "e": 7002, "s": 6974, "text": "JavaScript Nested Functions" }, { "code": null, "e": 7030, "s": 7002, "text": "JavaScript Nested Functions" }, { "code": null, "e": 7066, "s": 7030, "text": "JavaScript Function( ) Constructor" }, { "code": null, "e": 7102, "s": 7066, "text": "JavaScript Function( ) Constructor" }, { "code": null, "e": 7131, "s": 7102, "text": "JavaScript Function Literals" }, { "code": null, "e": 7160, "s": 7131, "text": "JavaScript Function Literals" }, { "code": null, "e": 7195, "s": 7160, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7209, "s": 7195, "text": " Anadi Sharma" }, { "code": null, "e": 7243, "s": 7209, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 7257, "s": 7243, "text": " Lets Kode It" }, { "code": null, "e": 7292, "s": 7257, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7309, "s": 7292, "text": " Frahaan Hussain" }, { "code": null, "e": 7344, "s": 7309, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7361, "s": 7344, "text": " Frahaan Hussain" }, { "code": null, "e": 7394, "s": 7361, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 7422, "s": 7394, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7456, "s": 7422, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 7484, "s": 7456, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7491, "s": 7484, "text": " Print" }, { "code": null, "e": 7502, "s": 7491, "text": " Add Notes" } ]
Mapping Word Embeddings with Word2vec | by Sam Liebman | Towards Data Science
Natural Language Processing (NLP) is an area of artificial intelligence focused on allowing computers to understand, process, and analyze human language. NLP is widely used in the tech industry, serving as a backbone to search engines, spam filters, language translation and much more. NLP enables computers to transform human language into a form that it can read and understand, such as a vector or discrete symbol. For example, NLP can take in the sentence So hungry, need food and break it down into four arbitrary symbols: so represented as K45, hungry as J83, need as Q67, and food as P21, all of which can then be processed by the computer. Each unique word is represented by a different symbol; however, the downside is that there is no apparent relationship between the symbols designated to hungry and food. This hinders the NLP model from using what it learned about hungry and applying it to food, which are semantically related. Vector Space Models (VSM) help address this issue by embedding the words in a vector space where similarly defined words are mapped near each other. This space is called a Word Embedding. Word2vec, a brainchild of a team of researchers led by Google’s Tomas Mikolov, is one of the most popular models used to create word embeddings. Word2vec has two primary methods of contextualizing words: the Continuous Bag-of-Words model (CBOW) and the Skip-Gram model, which i will summarize in this post. Both models arrive at a similar conclusion, but take nearly inverse paths to get there. CBOW, which is the less popular of the two models, uses source words to predict the target words. For example, take the sentence I want to learn python. In this instance, the target word is python, while the source words are I want to learn. CBOW is primarily used in smaller datasets, since it treats the context of the sentence as a single observation towards predicting the target word. In practice, this becomes very inefficient when working with a large set of words. The Skip-Gram model works in the opposite fashion of the CBOW model, using target words to predict the source, or context, of the surrounding words. Consider the sentence the quick brown fox jumped over the lazy dog and suppose we use a simple definition for the context of a given word as the words immediately preceding and following it. The Skip-Gram model will break the sentence into (context, target) pairs, resulting in a set of pairs in the following format: ([the, brown],quick), ([quick,fox],brown), ([brown,jumped],fox)... These pairs are winnowed further into (input, output) pairs, representing each word (input) with the word either directly before or after it. This is necessary because the Skip-Gram model works by using the target words (inputs) to predict the context, or output. These pairs are represented as follows: (quick, the), (quick, brown), (brown, quick), (brown, fox)... Now that each word is able to be represented in context, the fun begins. I won’t go into the math — this TensorFlow tutorial provides an in depth explanation — but the loss function for predicting each word given context can be optimized using stochastic gradient descent and iterating through every pair in the dataset. From there, the vectors can be reduced to two dimensions using the t-SNE dimensionality reduction technique. Once the word vectors are reduced to two-dimensions, it is possible to see relationships between certain words. Examples of a semantic relationship are male/female designations and Country/Capital relationships, while an example of syntactic relationship is past vs. present tense. The diagram below does an excellent job of visualizing these relationships: Words that share semantic or syntactic relationships will be represented by vectors of similar magnitude and be mapped in close proximity to each other in the word embredding. No longer is the case of king being represented with a arbitrary discrete symbol K93 and queen with S83. Instead, the relationship between king and queen is more apparent — in fact, it is exactly the same as the relationship between the vectors for man and woman, respectively. This allows for extremely cool and magically simple arithmetic to be performed on vectors. For example: if you subtract the vector for boy from the vector representation of brother, and then add the vector for girl, you will get sister. brother - boy + girl = sisterqueen - woman + man = kingbiking - today + yesterday = biked This opens up an entirely new dimension of possibilities for finding patterns or other insights in the data. Using a sample code showcased in TensorFlow’s tutorial, I will demonstrate how word2vec works in practice. TensorFlow is a machine learning library developed by the Google Brain team for internal use, open-sourced to the public in 2015 in an effort to accelerate the growth of AI. TensorFlow is a powerful tool for deep learning, logistic regression, and reinforcement learning, and has grown popular due to its ability to optimize computational efficiency when training large datasets. The example code provided reads a large dataset of 50,000 words, and trains a skip-gram model to vectorize the words in a contextual manner. It then iterates through the data 100,000 times in order to optimize the loss function for a randomized batch of popular words in the dataset. At first, the nearest neighbors for the popular words don’t show any syntactic or semantic relationship with each of the words. After 100,000 steps, a much clearer relationship is visible, and the loss function decreased by over 98%. As seen above, before the skip-gram model was trained, the eight nearest neighbors for the word three were: bissau, zeal, chong, salting, cooperate, quarterfinals, legislatures, ample. By the time the iterations are complete, the nearest neighbors for three are: five, four, seven, six, two, eight, nine, agouti. While not perfect — last I checked, agouti is a tropical American rodent, not a number — 7 of the 8 nearest neighbors displayed a clear semantic relationship to the word three. While word2vec can create word embeddings that illustrate semantic and syntactic relationships between words, the model is not without some flaws. A 2016 study entitled Man is to Computer Programmer as Woman is to Homemaker? Debiasing Word Embeddings (Bolukbasi, Chang, Zou, Saligrama, Kalai) demonstrated how word embeddings used by Google reinforced gender stereotypes at an alarming rate, and identified potential fixes to the issue. Data scientist and entrepreneur Emre Şarbak used Google Translate to further emphasize the gender biases exhibited by the word embedding algorithms. Şarbak, who is fluent in Turkish, tested how Google would translate sentences from Turkish, which uses gender neutral pronouns, to English. The results were a mix between fascinating and disturbing. (More examples) For the most part, when a sentence contained descriptors stereotypically attributed to women (cook, teacher, nurse), the Turkish gender-neutral pronoun o was translated to she. Conversely, sentences with terms such as hard working, lawyer, and engineer saw the pronoun translated to male form. Google is not solely to blame for this — its algorithms are based off a corpus of human words containing billions of data points, so Google is merely reflecting already existing biases. Yet, Google is still determining what millions of people see when they use Translate (or Search, YouTube and any other popular Google platform). Ultimately, this is most likely an unintended negative consequence of a powerful tool, but it raises an important issue about how easily we let computers and artificial intelligence dictate what we think and see. NLP and word embeddings are essential tools and are arguably the future of artificial intelligence; however, an open dialogue about exactly how machine learning algorithms are making their decisions is important so that marginalized voices don’t get shut out. TensorFlow Word2vec Tutorial Word2Vec (skip-gram model): PART 1 — Intuition by Manish Chablani Word2Vec Tutorial — The Skip-Gram Model by Chris McCormick
[ { "code": null, "e": 1302, "s": 172, "text": "Natural Language Processing (NLP) is an area of artificial intelligence focused on allowing computers to understand, process, and analyze human language. NLP is widely used in the tech industry, serving as a backbone to search engines, spam filters, language translation and much more. NLP enables computers to transform human language into a form that it can read and understand, such as a vector or discrete symbol. For example, NLP can take in the sentence So hungry, need food and break it down into four arbitrary symbols: so represented as K45, hungry as J83, need as Q67, and food as P21, all of which can then be processed by the computer. Each unique word is represented by a different symbol; however, the downside is that there is no apparent relationship between the symbols designated to hungry and food. This hinders the NLP model from using what it learned about hungry and applying it to food, which are semantically related. Vector Space Models (VSM) help address this issue by embedding the words in a vector space where similarly defined words are mapped near each other. This space is called a Word Embedding." }, { "code": null, "e": 1697, "s": 1302, "text": "Word2vec, a brainchild of a team of researchers led by Google’s Tomas Mikolov, is one of the most popular models used to create word embeddings. Word2vec has two primary methods of contextualizing words: the Continuous Bag-of-Words model (CBOW) and the Skip-Gram model, which i will summarize in this post. Both models arrive at a similar conclusion, but take nearly inverse paths to get there." }, { "code": null, "e": 2170, "s": 1697, "text": "CBOW, which is the less popular of the two models, uses source words to predict the target words. For example, take the sentence I want to learn python. In this instance, the target word is python, while the source words are I want to learn. CBOW is primarily used in smaller datasets, since it treats the context of the sentence as a single observation towards predicting the target word. In practice, this becomes very inefficient when working with a large set of words." }, { "code": null, "e": 2637, "s": 2170, "text": "The Skip-Gram model works in the opposite fashion of the CBOW model, using target words to predict the source, or context, of the surrounding words. Consider the sentence the quick brown fox jumped over the lazy dog and suppose we use a simple definition for the context of a given word as the words immediately preceding and following it. The Skip-Gram model will break the sentence into (context, target) pairs, resulting in a set of pairs in the following format:" }, { "code": null, "e": 2704, "s": 2637, "text": "([the, brown],quick), ([quick,fox],brown), ([brown,jumped],fox)..." }, { "code": null, "e": 3008, "s": 2704, "text": "These pairs are winnowed further into (input, output) pairs, representing each word (input) with the word either directly before or after it. This is necessary because the Skip-Gram model works by using the target words (inputs) to predict the context, or output. These pairs are represented as follows:" }, { "code": null, "e": 3070, "s": 3008, "text": "(quick, the), (quick, brown), (brown, quick), (brown, fox)..." }, { "code": null, "e": 3500, "s": 3070, "text": "Now that each word is able to be represented in context, the fun begins. I won’t go into the math — this TensorFlow tutorial provides an in depth explanation — but the loss function for predicting each word given context can be optimized using stochastic gradient descent and iterating through every pair in the dataset. From there, the vectors can be reduced to two dimensions using the t-SNE dimensionality reduction technique." }, { "code": null, "e": 3858, "s": 3500, "text": "Once the word vectors are reduced to two-dimensions, it is possible to see relationships between certain words. Examples of a semantic relationship are male/female designations and Country/Capital relationships, while an example of syntactic relationship is past vs. present tense. The diagram below does an excellent job of visualizing these relationships:" }, { "code": null, "e": 4549, "s": 3858, "text": "Words that share semantic or syntactic relationships will be represented by vectors of similar magnitude and be mapped in close proximity to each other in the word embredding. No longer is the case of king being represented with a arbitrary discrete symbol K93 and queen with S83. Instead, the relationship between king and queen is more apparent — in fact, it is exactly the same as the relationship between the vectors for man and woman, respectively. This allows for extremely cool and magically simple arithmetic to be performed on vectors. For example: if you subtract the vector for boy from the vector representation of brother, and then add the vector for girl, you will get sister." }, { "code": null, "e": 4639, "s": 4549, "text": "brother - boy + girl = sisterqueen - woman + man = kingbiking - today + yesterday = biked" }, { "code": null, "e": 4748, "s": 4639, "text": "This opens up an entirely new dimension of possibilities for finding patterns or other insights in the data." }, { "code": null, "e": 5235, "s": 4748, "text": "Using a sample code showcased in TensorFlow’s tutorial, I will demonstrate how word2vec works in practice. TensorFlow is a machine learning library developed by the Google Brain team for internal use, open-sourced to the public in 2015 in an effort to accelerate the growth of AI. TensorFlow is a powerful tool for deep learning, logistic regression, and reinforcement learning, and has grown popular due to its ability to optimize computational efficiency when training large datasets." }, { "code": null, "e": 5753, "s": 5235, "text": "The example code provided reads a large dataset of 50,000 words, and trains a skip-gram model to vectorize the words in a contextual manner. It then iterates through the data 100,000 times in order to optimize the loss function for a randomized batch of popular words in the dataset. At first, the nearest neighbors for the popular words don’t show any syntactic or semantic relationship with each of the words. After 100,000 steps, a much clearer relationship is visible, and the loss function decreased by over 98%." }, { "code": null, "e": 6243, "s": 5753, "text": "As seen above, before the skip-gram model was trained, the eight nearest neighbors for the word three were: bissau, zeal, chong, salting, cooperate, quarterfinals, legislatures, ample. By the time the iterations are complete, the nearest neighbors for three are: five, four, seven, six, two, eight, nine, agouti. While not perfect — last I checked, agouti is a tropical American rodent, not a number — 7 of the 8 nearest neighbors displayed a clear semantic relationship to the word three." }, { "code": null, "e": 7046, "s": 6243, "text": "While word2vec can create word embeddings that illustrate semantic and syntactic relationships between words, the model is not without some flaws. A 2016 study entitled Man is to Computer Programmer as Woman is to Homemaker? Debiasing Word Embeddings (Bolukbasi, Chang, Zou, Saligrama, Kalai) demonstrated how word embeddings used by Google reinforced gender stereotypes at an alarming rate, and identified potential fixes to the issue. Data scientist and entrepreneur Emre Şarbak used Google Translate to further emphasize the gender biases exhibited by the word embedding algorithms. Şarbak, who is fluent in Turkish, tested how Google would translate sentences from Turkish, which uses gender neutral pronouns, to English. The results were a mix between fascinating and disturbing. (More examples)" }, { "code": null, "e": 7671, "s": 7046, "text": "For the most part, when a sentence contained descriptors stereotypically attributed to women (cook, teacher, nurse), the Turkish gender-neutral pronoun o was translated to she. Conversely, sentences with terms such as hard working, lawyer, and engineer saw the pronoun translated to male form. Google is not solely to blame for this — its algorithms are based off a corpus of human words containing billions of data points, so Google is merely reflecting already existing biases. Yet, Google is still determining what millions of people see when they use Translate (or Search, YouTube and any other popular Google platform)." }, { "code": null, "e": 8144, "s": 7671, "text": "Ultimately, this is most likely an unintended negative consequence of a powerful tool, but it raises an important issue about how easily we let computers and artificial intelligence dictate what we think and see. NLP and word embeddings are essential tools and are arguably the future of artificial intelligence; however, an open dialogue about exactly how machine learning algorithms are making their decisions is important so that marginalized voices don’t get shut out." }, { "code": null, "e": 8173, "s": 8144, "text": "TensorFlow Word2vec Tutorial" }, { "code": null, "e": 8239, "s": 8173, "text": "Word2Vec (skip-gram model): PART 1 — Intuition by Manish Chablani" } ]
Zend Framework - Installation
To install the Zend Framework, we must first install the Composer and the latest version of PHP as shown in the following steps. Install Composer − Zend uses Composer for managing its dependencies, so make sure you have the Composer installed on your machine. If the Composer is not installed, then visit the official website of Composer and install it. Install Composer − Zend uses Composer for managing its dependencies, so make sure you have the Composer installed on your machine. If the Composer is not installed, then visit the official website of Composer and install it. Install the latest version of PHP − To get the maximum benefit of Zend Framework, install the latest version of PHP. The minimum required version for the Zend Framework 3 is PHP 5.6 or later. Install the latest version of PHP − To get the maximum benefit of Zend Framework, install the latest version of PHP. The minimum required version for the Zend Framework 3 is PHP 5.6 or later. Zend Framework can be installed in two ways. They are as follows − Manual installation Composer based installation Let us discuss both these installations in detail. Download the latest version of Zend Framework by visiting the following link – https://framework.zend.com/downloads/archives Extract the content of the downloaded archive file to the folder you would like to keep it. Once you have a copy of Zend Framework available in your local machine, your Zend Framework based web application can access the framework classes. Though there are several ways to achieve this, your PHP include_path needs to contain the path to the Zend Framework classes under the /library directory in the distribution. This method applies to Zend Framework version 2.4 and earlier only. To easily install the Zend Framework, use the Composer tool. This is the preferred method to install the latest version of Zend Framework. To install all the components of the Zend Framework, use the following Composer command − $ composer require zendframework/zendframework Each Zend Framework module / component can be installed individually as well. For example, to install the MVC component of the Zend Framework, use the following composer command − $ composer require zendframework/zend-mvc Print Add Notes Bookmark this page
[ { "code": null, "e": 2441, "s": 2312, "text": "To install the Zend Framework, we must first install the Composer and the latest version of PHP as shown in the following steps." }, { "code": null, "e": 2666, "s": 2441, "text": "Install Composer − Zend uses Composer for managing its dependencies, so make sure you have the Composer installed on your machine. If the Composer is not installed, then visit the official website of Composer and install it." }, { "code": null, "e": 2891, "s": 2666, "text": "Install Composer − Zend uses Composer for managing its dependencies, so make sure you have the Composer installed on your machine. If the Composer is not installed, then visit the official website of Composer and install it." }, { "code": null, "e": 3083, "s": 2891, "text": "Install the latest version of PHP − To get the maximum benefit of Zend Framework, install the latest version of PHP. The minimum required version for the Zend Framework 3 is PHP 5.6 or later." }, { "code": null, "e": 3275, "s": 3083, "text": "Install the latest version of PHP − To get the maximum benefit of Zend Framework, install the latest version of PHP. The minimum required version for the Zend Framework 3 is PHP 5.6 or later." }, { "code": null, "e": 3342, "s": 3275, "text": "Zend Framework can be installed in two ways. They are as follows −" }, { "code": null, "e": 3362, "s": 3342, "text": "Manual installation" }, { "code": null, "e": 3390, "s": 3362, "text": "Composer based installation" }, { "code": null, "e": 3441, "s": 3390, "text": "Let us discuss both these installations in detail." }, { "code": null, "e": 3566, "s": 3441, "text": "Download the latest version of Zend Framework by visiting the following link – https://framework.zend.com/downloads/archives" }, { "code": null, "e": 4049, "s": 3566, "text": "Extract the content of the downloaded archive file to the folder you would like to keep it. Once you have a copy of Zend Framework available in your local machine, your Zend Framework based web application can access the framework classes. Though there are several ways to achieve this, your PHP include_path needs to contain the path to the Zend Framework classes under the /library directory in the distribution. This method applies to Zend Framework version 2.4 and earlier only." }, { "code": null, "e": 4278, "s": 4049, "text": "To easily install the Zend Framework, use the Composer tool. This is the preferred method to install the latest version of Zend Framework. To install all the components of the Zend Framework, use the following Composer command −" }, { "code": null, "e": 4326, "s": 4278, "text": "$ composer require zendframework/zendframework\n" }, { "code": null, "e": 4506, "s": 4326, "text": "Each Zend Framework module / component can be installed individually as well. For example, to install the MVC component of the Zend Framework, use the following composer command −" }, { "code": null, "e": 4549, "s": 4506, "text": "$ composer require zendframework/zend-mvc\n" }, { "code": null, "e": 4556, "s": 4549, "text": " Print" }, { "code": null, "e": 4567, "s": 4556, "text": " Add Notes" } ]
What is event Bubbling and capturing in JavaScript?
Event bubbling is the order in which event handlers are called when one element is nested inside a second element, and both elements have registered a listener for the same event (a click, for example). With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements. With capturing, the event is first captured by the outermost element and propagated to the inner elements. Let's look at examples of both. For both of the following examples, create the following HTML − Live Demo <div id='outer' style='background-color:red;display:inline-block;padding:50px;'> Outer Div <div id='inner' style='background-color:yellow;display:inline-block;padding:50px;'> Inner Div </div> </div> 1. Event Bubbling document.querySelector('#outer').addEventListener('click', e => { console.log('Outer div is clicked'); }, false); document.querySelector('#inner').addEventListener('click', e => { console.log('Inner div is clicked'); }, false); If you run the above code and click in the inner div, you'll get the log − Inner div is clicked Outer div is clicked 2. Event Capturing document.querySelector('#outer').addEventListener('click', e => { console.log('Outer div is clicked'); }, true); document.querySelector('#inner').addEventListener('click', e => { console.log('Inner div is clicked'); }, true); If you run the above code and click in the inner div, you'll get the log − Outer div is clicked Inner div is clicked
[ { "code": null, "e": 1384, "s": 1062, "text": "Event bubbling is the order in which event handlers are called when one element is nested inside a second element, and both elements have registered a listener for the same event (a click, for example). With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements." }, { "code": null, "e": 1491, "s": 1384, "text": "With capturing, the event is first captured by the outermost element and propagated to the inner elements." }, { "code": null, "e": 1523, "s": 1491, "text": "Let's look at examples of both." }, { "code": null, "e": 1587, "s": 1523, "text": "For both of the following examples, create the following HTML −" }, { "code": null, "e": 1599, "s": 1587, "text": " Live Demo" }, { "code": null, "e": 1804, "s": 1599, "text": "<div id='outer' style='background-color:red;display:inline-block;padding:50px;'>\n Outer Div\n<div id='inner' style='background-color:yellow;display:inline-block;padding:50px;'>\n Inner Div\n</div>\n</div>" }, { "code": null, "e": 1822, "s": 1804, "text": "1. Event Bubbling" }, { "code": null, "e": 2056, "s": 1822, "text": "document.querySelector('#outer').addEventListener('click', e => {\n console.log('Outer div is clicked');\n}, false);\ndocument.querySelector('#inner').addEventListener('click', e => {\n console.log('Inner div is clicked');\n}, false);" }, { "code": null, "e": 2131, "s": 2056, "text": "If you run the above code and click in the inner div, you'll get the log −" }, { "code": null, "e": 2174, "s": 2131, "text": "Inner div is clicked\n\nOuter div is clicked" }, { "code": null, "e": 2193, "s": 2174, "text": "2. Event Capturing" }, { "code": null, "e": 2425, "s": 2193, "text": "document.querySelector('#outer').addEventListener('click', e => {\n console.log('Outer div is clicked');\n}, true);\ndocument.querySelector('#inner').addEventListener('click', e => {\n console.log('Inner div is clicked');\n}, true);" }, { "code": null, "e": 2500, "s": 2425, "text": "If you run the above code and click in the inner div, you'll get the log −" }, { "code": null, "e": 2543, "s": 2500, "text": "Outer div is clicked\n\nInner div is clicked" } ]
GWT - Tree Widget
The Tree widget represents a standard hierarchical tree widget. The tree contains a hierarchy of TreeItems that the user can open, close, and select. Following is the declaration for com.google.gwt.user.client.ui.Tree class − public class Tree extends Widget implements HasWidgets, SourcesTreeEvents, HasFocus, HasAnimation, HasAllKeyHandlers, HasAllFocusHandlers, HasSelectionHandlers<TreeItem>, HasOpenHandlers<TreeItem>, HasCloseHandlers<TreeItem>, SourcesMouseEvents, HasAllMouseHandlers Following default CSS Style rules will be applied to all the Tree widget. You can override it as per your requirements. .gwt-Tree {} .gwt-TreeItem {} .gwt-TreeItem-selected {} Tree() Constructs an empty tree. Tree(TreeImages images) Constructs a tree that uses the specified image bundle for images. Tree(TreeImages images, boolean useLeafImages) Constructs a tree that uses the specified image bundle for images. void add(Widget widget) Adds the widget as a root tree item. void addFocusListener(FocusListener listener) Adds a listener interface to receive mouse events. TreeItem addItem(java.lang.String itemText) Adds a simple tree item containing the specified text. void addItem(TreeItem item) Adds an item to the root level of this tree. TreeItem addItem(Widget widget) Adds a new tree item containing the specified widget. void addKeyboardListener(KeyboardListener listener) Adds a listener interface to receive keyboard events. void addMouseListener(MouseListener listener) void addTreeListener(TreeListener listener) Adds a listener interface to receive tree events. void clear() Clears all tree items from the current tree. protected void doAttachChildren() If a widget implements HasWidgets, it must override this method and call onAttach() for each of its child widgets. protected void doDetachChildren() If a widget implements HasWidgets, it must override this method and call onDetach() for each of its child widgets. void ensureSelectedItemVisible() Ensures that the currently-selected item is visible, opening its parents and scrolling the tree as necessary. java.lang.String getImageBase() Deprecated. Use Tree(TreeImages) as it provides a more efficent and manageable way to supply a set of images to be used within a tree. TreeItem getItem(int index) Gets the top-level tree item at the specified index. int getItemCount() Gets the number of items contained at the root of this tree. TreeItem getSelectedItem() Gets the currently selected item. int getTabIndex() Gets the widget's position in the tab index. boolean isAnimationEnabled() protected boolean isKeyboardNavigationEnabled(TreeItem currentItem) Indicates if keyboard navigation is enabled for the Tree and for a given TreeItem. java.util.Iterator<Widget> iterator() Gets an iterator for the contained widgets. void onBrowserEvent(Event event) Fired whenever a browser event is received. protected void onEnsureDebugId(java.lang.String baseID) Affected Elements: -root = The root TreeItem. protected void onLoad() This method is called immediately after a widget becomes attached to the browser's document. boolean remove(Widget w) Removes a child widget. void removeFocusListener(FocusListener listener) Removes a previously added listener interface. void removeItem(TreeItem item) Removes an item from the root level of this tree. void removeItems() Removes all items from the root level of this tree. void removeKeyboardListener(KeyboardListener listener) Removes a previously added listener interface. void removeTreeListener(TreeListener listener) Removes a previously added listener interface. void setAccessKey(char key) Sets the widget's 'access key'. void setAnimationEnabled(boolean enable) Enable or disable animations. void setFocus(boolean focus) Explicitly focus/unfocus this widget. void setImageBase(java.lang.String baseUrl) Deprecated. Use Tree(TreeImages) as it provides a more efficent and manageable way to supply a set of images to be used within a tree. void setSelectedItem(TreeItem item) Selects a specified item. void setSelectedItem(TreeItem item, boolean fireEvents) Selects a specified item. void setTabIndex(int index) Sets the widget's position in the tab index. java.util.Iterator<TreeItem> treeItemIterator() Iterator of tree items. This class inherits methods from the following classes − com.google.gwt.user.client.ui.UIObject com.google.gwt.user.client.ui.UIObject com.google.gwt.user.client.ui.Widget com.google.gwt.user.client.ui.Widget java.lang.Object java.lang.Object This example will take you through simple steps to show usage of a Tree Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter − Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml. <?xml version = "1.0" encoding = "UTF-8"?> <module rename-to = 'helloworld'> <!-- Inherit the core Web Toolkit stuff. --> <inherits name = 'com.google.gwt.user.User'/> <!-- Inherit the default GWT style sheet. --> <inherits name = 'com.google.gwt.user.theme.clean.Clean'/> <!-- Specify the app entry point class. --> <entry-point class = 'com.tutorialspoint.client.HelloWorld'/> <!-- Specify the paths for translatable code --> <source path = 'client'/> <source path = 'shared'/> </module> Following is the content of the modified Style Sheet file war/HelloWorld.css. body { text-align: center; font-family: verdana, sans-serif; } h1 { font-size: 2em; font-weight: bold; color: #777777; margin: 40px 0px 70px; text-align: center; } .gwt-Label { font-weight: bold; color: maroon; } .gwt-Tree .gwt-TreeItem { padding: 1px 0px; margin: 0px; white-space: nowrap; cursor: hand; cursor: pointer; } .gwt-Tree .gwt-TreeItem-selected { background: #ebeff9; } Following is the content of the modified HTML host file war/HelloWorld.html. <html> <head> <title>Hello World</title> <link rel = "stylesheet" href = "HelloWorld.css"/> <script language = "javascript" src = "helloworld/helloworld.nocache.js"> </script> </head> <body> <h1>Tree Widget Demonstration</h1> <div id = "gwtContainer"></div> </body> </html> Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of Tree widget. package com.tutorialspoint.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.Tree; import com.google.gwt.user.client.ui.TreeItem; import com.google.gwt.user.client.ui.VerticalPanel; public class HelloWorld implements EntryPoint { public void onModuleLoad() { //create a label final Label labelMessage = new Label(); labelMessage.setWidth("300"); // Create a root tree item as department TreeItem department = new TreeItem("Department"); //create other tree items as department names TreeItem salesDepartment = new TreeItem("Sales"); TreeItem marketingDepartment = new TreeItem("Marketing"); TreeItem manufacturingDepartment = new TreeItem("Manufacturing"); //create other tree items as employees TreeItem employee1 = new TreeItem("Robert"); TreeItem employee2 = new TreeItem("Joe"); TreeItem employee3 = new TreeItem("Chris"); //add employees to sales department salesDepartment.addItem(employee1); salesDepartment.addItem(employee2); salesDepartment.addItem(employee3); //create other tree items as employees TreeItem employee4 = new TreeItem("Mona"); TreeItem employee5 = new TreeItem("Tena"); //add employees to marketing department marketingDepartment.addItem(employee4); marketingDepartment.addItem(employee5); //create other tree items as employees TreeItem employee6 = new TreeItem("Rener"); TreeItem employee7 = new TreeItem("Linda"); //add employees to sales department manufacturingDepartment.addItem(employee6); manufacturingDepartment.addItem(employee7); //add departments to department item department.addItem(salesDepartment); department.addItem(marketingDepartment); department.addItem(manufacturingDepartment); //create the tree Tree tree = new Tree(); //add root item to the tree tree.addItem(department); tree.addSelectionHandler(new SelectionHandlerL<TreeItem>() { @Override public void onSelection(SelectionEvent<TreeItem> event) { labelMessage.setText("Selected Value: " + event.getSelectedItem().getText()); } }); // Add text boxes to the root panel. VerticalPanel panel = new VerticalPanel(); panel.setSpacing(10); panel.add(tree); panel.add(labelMessage); //add the tree to the root panel RootPanel.get("gwtContainer").add(panel); } } Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result − Selecting any value in tree, will update a message below the tree displaying the selected value. Print Add Notes Bookmark this page
[ { "code": null, "e": 2173, "s": 2023, "text": "The Tree widget represents a standard hierarchical tree widget. The tree contains a hierarchy of TreeItems that the user can open, close, and select." }, { "code": null, "e": 2249, "s": 2173, "text": "Following is the declaration for com.google.gwt.user.client.ui.Tree class −" }, { "code": null, "e": 2562, "s": 2249, "text": "public class Tree\n extends Widget\n implements HasWidgets, SourcesTreeEvents, HasFocus,\n HasAnimation, HasAllKeyHandlers, HasAllFocusHandlers, \n HasSelectionHandlers<TreeItem>, HasOpenHandlers<TreeItem>, \n HasCloseHandlers<TreeItem>, SourcesMouseEvents, HasAllMouseHandlers" }, { "code": null, "e": 2682, "s": 2562, "text": "Following default CSS Style rules will be applied to all the Tree widget. You can override it as per your requirements." }, { "code": null, "e": 2740, "s": 2682, "text": ".gwt-Tree {}\n\n.gwt-TreeItem {}\n\n.gwt-TreeItem-selected {}" }, { "code": null, "e": 2747, "s": 2740, "text": "Tree()" }, { "code": null, "e": 2773, "s": 2747, "text": "Constructs an empty tree." }, { "code": null, "e": 2797, "s": 2773, "text": "Tree(TreeImages images)" }, { "code": null, "e": 2864, "s": 2797, "text": "Constructs a tree that uses the specified image bundle for images." }, { "code": null, "e": 2911, "s": 2864, "text": "Tree(TreeImages images, boolean useLeafImages)" }, { "code": null, "e": 2978, "s": 2911, "text": "Constructs a tree that uses the specified image bundle for images." }, { "code": null, "e": 3002, "s": 2978, "text": "void add(Widget widget)" }, { "code": null, "e": 3039, "s": 3002, "text": "Adds the widget as a root tree item." }, { "code": null, "e": 3085, "s": 3039, "text": "void addFocusListener(FocusListener listener)" }, { "code": null, "e": 3136, "s": 3085, "text": "Adds a listener interface to receive mouse events." }, { "code": null, "e": 3180, "s": 3136, "text": "TreeItem addItem(java.lang.String itemText)" }, { "code": null, "e": 3235, "s": 3180, "text": "Adds a simple tree item containing the specified text." }, { "code": null, "e": 3263, "s": 3235, "text": "void addItem(TreeItem item)" }, { "code": null, "e": 3308, "s": 3263, "text": "Adds an item to the root level of this tree." }, { "code": null, "e": 3340, "s": 3308, "text": "TreeItem addItem(Widget widget)" }, { "code": null, "e": 3394, "s": 3340, "text": "Adds a new tree item containing the specified widget." }, { "code": null, "e": 3446, "s": 3394, "text": "void addKeyboardListener(KeyboardListener listener)" }, { "code": null, "e": 3500, "s": 3446, "text": "Adds a listener interface to receive keyboard events." }, { "code": null, "e": 3546, "s": 3500, "text": "void addMouseListener(MouseListener listener)" }, { "code": null, "e": 3590, "s": 3546, "text": "void addTreeListener(TreeListener listener)" }, { "code": null, "e": 3640, "s": 3590, "text": "Adds a listener interface to receive tree events." }, { "code": null, "e": 3653, "s": 3640, "text": "void clear()" }, { "code": null, "e": 3698, "s": 3653, "text": "Clears all tree items from the current tree." }, { "code": null, "e": 3732, "s": 3698, "text": "protected void doAttachChildren()" }, { "code": null, "e": 3847, "s": 3732, "text": "If a widget implements HasWidgets, it must override this method and call onAttach() for each of its child widgets." }, { "code": null, "e": 3881, "s": 3847, "text": "protected void doDetachChildren()" }, { "code": null, "e": 3996, "s": 3881, "text": "If a widget implements HasWidgets, it must override this method and call onDetach() for each of its child widgets." }, { "code": null, "e": 4029, "s": 3996, "text": "void ensureSelectedItemVisible()" }, { "code": null, "e": 4139, "s": 4029, "text": "Ensures that the currently-selected item is visible, opening its parents and scrolling the tree as necessary." }, { "code": null, "e": 4171, "s": 4139, "text": "java.lang.String getImageBase()" }, { "code": null, "e": 4306, "s": 4171, "text": "Deprecated. Use Tree(TreeImages) as it provides a more efficent and manageable way to supply a set of images to be used within a tree." }, { "code": null, "e": 4334, "s": 4306, "text": "TreeItem getItem(int index)" }, { "code": null, "e": 4387, "s": 4334, "text": "Gets the top-level tree item at the specified index." }, { "code": null, "e": 4406, "s": 4387, "text": "int getItemCount()" }, { "code": null, "e": 4467, "s": 4406, "text": "Gets the number of items contained at the root of this tree." }, { "code": null, "e": 4494, "s": 4467, "text": "TreeItem getSelectedItem()" }, { "code": null, "e": 4528, "s": 4494, "text": "Gets the currently selected item." }, { "code": null, "e": 4546, "s": 4528, "text": "int getTabIndex()" }, { "code": null, "e": 4591, "s": 4546, "text": "Gets the widget's position in the tab index." }, { "code": null, "e": 4620, "s": 4591, "text": "boolean isAnimationEnabled()" }, { "code": null, "e": 4688, "s": 4620, "text": "protected boolean isKeyboardNavigationEnabled(TreeItem currentItem)" }, { "code": null, "e": 4771, "s": 4688, "text": "Indicates if keyboard navigation is enabled for the Tree and for a given TreeItem." }, { "code": null, "e": 4809, "s": 4771, "text": "java.util.Iterator<Widget> iterator()" }, { "code": null, "e": 4853, "s": 4809, "text": "Gets an iterator for the contained widgets." }, { "code": null, "e": 4886, "s": 4853, "text": "void onBrowserEvent(Event event)" }, { "code": null, "e": 4930, "s": 4886, "text": "Fired whenever a browser event is received." }, { "code": null, "e": 4986, "s": 4930, "text": "protected void onEnsureDebugId(java.lang.String baseID)" }, { "code": null, "e": 5032, "s": 4986, "text": "Affected Elements: -root = The root TreeItem." }, { "code": null, "e": 5056, "s": 5032, "text": "protected void onLoad()" }, { "code": null, "e": 5149, "s": 5056, "text": "This method is called immediately after a widget becomes attached to the browser's document." }, { "code": null, "e": 5174, "s": 5149, "text": "boolean remove(Widget w)" }, { "code": null, "e": 5198, "s": 5174, "text": "Removes a child widget." }, { "code": null, "e": 5247, "s": 5198, "text": "void removeFocusListener(FocusListener listener)" }, { "code": null, "e": 5294, "s": 5247, "text": "Removes a previously added listener interface." }, { "code": null, "e": 5325, "s": 5294, "text": "void removeItem(TreeItem item)" }, { "code": null, "e": 5375, "s": 5325, "text": "Removes an item from the root level of this tree." }, { "code": null, "e": 5394, "s": 5375, "text": "void removeItems()" }, { "code": null, "e": 5446, "s": 5394, "text": "Removes all items from the root level of this tree." }, { "code": null, "e": 5501, "s": 5446, "text": "void removeKeyboardListener(KeyboardListener listener)" }, { "code": null, "e": 5548, "s": 5501, "text": "Removes a previously added listener interface." }, { "code": null, "e": 5595, "s": 5548, "text": "void removeTreeListener(TreeListener listener)" }, { "code": null, "e": 5642, "s": 5595, "text": "Removes a previously added listener interface." }, { "code": null, "e": 5670, "s": 5642, "text": "void setAccessKey(char key)" }, { "code": null, "e": 5702, "s": 5670, "text": "Sets the widget's 'access key'." }, { "code": null, "e": 5743, "s": 5702, "text": "void setAnimationEnabled(boolean enable)" }, { "code": null, "e": 5773, "s": 5743, "text": "Enable or disable animations." }, { "code": null, "e": 5802, "s": 5773, "text": "void setFocus(boolean focus)" }, { "code": null, "e": 5840, "s": 5802, "text": "Explicitly focus/unfocus this widget." }, { "code": null, "e": 5884, "s": 5840, "text": "void setImageBase(java.lang.String baseUrl)" }, { "code": null, "e": 6019, "s": 5884, "text": "Deprecated. Use Tree(TreeImages) as it provides a more efficent and manageable way to supply a set of images to be used within a tree." }, { "code": null, "e": 6055, "s": 6019, "text": "void setSelectedItem(TreeItem item)" }, { "code": null, "e": 6081, "s": 6055, "text": "Selects a specified item." }, { "code": null, "e": 6137, "s": 6081, "text": "void setSelectedItem(TreeItem item, boolean fireEvents)" }, { "code": null, "e": 6163, "s": 6137, "text": "Selects a specified item." }, { "code": null, "e": 6191, "s": 6163, "text": "void setTabIndex(int index)" }, { "code": null, "e": 6236, "s": 6191, "text": "Sets the widget's position in the tab index." }, { "code": null, "e": 6284, "s": 6236, "text": "java.util.Iterator<TreeItem> treeItemIterator()" }, { "code": null, "e": 6308, "s": 6284, "text": "Iterator of tree items." }, { "code": null, "e": 6365, "s": 6308, "text": "This class inherits methods from the following classes −" }, { "code": null, "e": 6404, "s": 6365, "text": "com.google.gwt.user.client.ui.UIObject" }, { "code": null, "e": 6443, "s": 6404, "text": "com.google.gwt.user.client.ui.UIObject" }, { "code": null, "e": 6480, "s": 6443, "text": "com.google.gwt.user.client.ui.Widget" }, { "code": null, "e": 6517, "s": 6480, "text": "com.google.gwt.user.client.ui.Widget" }, { "code": null, "e": 6534, "s": 6517, "text": "java.lang.Object" }, { "code": null, "e": 6551, "s": 6534, "text": "java.lang.Object" }, { "code": null, "e": 6745, "s": 6551, "text": "This example will take you through simple steps to show usage of a Tree Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter −" }, { "code": null, "e": 6847, "s": 6745, "text": "Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml." }, { "code": null, "e": 7456, "s": 6847, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<module rename-to = 'helloworld'>\n <!-- Inherit the core Web Toolkit stuff. -->\n <inherits name = 'com.google.gwt.user.User'/>\n\n <!-- Inherit the default GWT style sheet. -->\n <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>\n\n <!-- Specify the app entry point class. -->\n <entry-point class = 'com.tutorialspoint.client.HelloWorld'/>\n\n <!-- Specify the paths for translatable code -->\n <source path = 'client'/>\n <source path = 'shared'/>\n\n</module>" }, { "code": null, "e": 7534, "s": 7456, "text": "Following is the content of the modified Style Sheet file war/HelloWorld.css." }, { "code": null, "e": 7964, "s": 7534, "text": "body {\n text-align: center;\n font-family: verdana, sans-serif;\n}\n\nh1 {\n font-size: 2em;\n font-weight: bold;\n color: #777777;\n margin: 40px 0px 70px;\n text-align: center;\n}\n\n.gwt-Label {\n font-weight: bold;\n color: maroon;\n}\n\n.gwt-Tree .gwt-TreeItem {\n padding: 1px 0px;\n margin: 0px;\n white-space: nowrap;\n cursor: hand;\n cursor: pointer;\n}\n\n.gwt-Tree .gwt-TreeItem-selected {\n background: #ebeff9;\n}" }, { "code": null, "e": 8041, "s": 7964, "text": "Following is the content of the modified HTML host file war/HelloWorld.html." }, { "code": null, "e": 8364, "s": 8041, "text": "<html>\n <head>\n <title>Hello World</title>\n <link rel = \"stylesheet\" href = \"HelloWorld.css\"/>\n <script language = \"javascript\" src = \"helloworld/helloworld.nocache.js\">\n </script>\n </head>\n\n <body>\n <h1>Tree Widget Demonstration</h1>\n <div id = \"gwtContainer\"></div>\n </body>\n</html>" }, { "code": null, "e": 8489, "s": 8364, "text": "Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of Tree widget." }, { "code": null, "e": 11264, "s": 8489, "text": "package com.tutorialspoint.client;\n\nimport com.google.gwt.core.client.EntryPoint;\nimport com.google.gwt.event.logical.shared.SelectionEvent;\nimport com.google.gwt.event.logical.shared.SelectionHandler;\nimport com.google.gwt.user.client.ui.Label;\nimport com.google.gwt.user.client.ui.RootPanel;\nimport com.google.gwt.user.client.ui.Tree;\nimport com.google.gwt.user.client.ui.TreeItem;\nimport com.google.gwt.user.client.ui.VerticalPanel;\n\npublic class HelloWorld implements EntryPoint {\n public void onModuleLoad() {\n //create a label\n final Label labelMessage = new Label();\n labelMessage.setWidth(\"300\");\n\n // Create a root tree item as department\n TreeItem department = new TreeItem(\"Department\");\n\n //create other tree items as department names\n TreeItem salesDepartment = new TreeItem(\"Sales\");\n TreeItem marketingDepartment = new TreeItem(\"Marketing\");\n TreeItem manufacturingDepartment = new TreeItem(\"Manufacturing\");\n\n //create other tree items as employees\n TreeItem employee1 = new TreeItem(\"Robert\");\n TreeItem employee2 = new TreeItem(\"Joe\");\n TreeItem employee3 = new TreeItem(\"Chris\");\n\n //add employees to sales department\n salesDepartment.addItem(employee1);\n salesDepartment.addItem(employee2);\n salesDepartment.addItem(employee3);\n\n //create other tree items as employees\n TreeItem employee4 = new TreeItem(\"Mona\");\n TreeItem employee5 = new TreeItem(\"Tena\");\t \n\n //add employees to marketing department\n marketingDepartment.addItem(employee4);\n marketingDepartment.addItem(employee5);\t \n\n //create other tree items as employees\n TreeItem employee6 = new TreeItem(\"Rener\");\n TreeItem employee7 = new TreeItem(\"Linda\");\n\n //add employees to sales department\n manufacturingDepartment.addItem(employee6);\n manufacturingDepartment.addItem(employee7);\n\n //add departments to department item\n department.addItem(salesDepartment);\n department.addItem(marketingDepartment);\n department.addItem(manufacturingDepartment);\n\n //create the tree\n Tree tree = new Tree();\n\n //add root item to the tree\n tree.addItem(department);\t \n\n tree.addSelectionHandler(new SelectionHandlerL<TreeItem>() {\n @Override\n public void onSelection(SelectionEvent<TreeItem> event) {\n labelMessage.setText(\"Selected Value: \"\n + event.getSelectedItem().getText());\n }\n });\n\n // Add text boxes to the root panel.\n VerticalPanel panel = new VerticalPanel();\n panel.setSpacing(10);\n panel.add(tree);\n panel.add(labelMessage);\n\n //add the tree to the root panel\n RootPanel.get(\"gwtContainer\").add(panel);\n }\t\n}" }, { "code": null, "e": 11498, "s": 11264, "text": "Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result −" }, { "code": null, "e": 11595, "s": 11498, "text": "Selecting any value in tree, will update a message below the tree displaying the selected value." }, { "code": null, "e": 11602, "s": 11595, "text": " Print" }, { "code": null, "e": 11613, "s": 11602, "text": " Add Notes" } ]
Ubuntu - Quick Guide
Ubuntu is a Linux-based operating system. It is designed for computers, smartphones, and network servers. The system is developed by a UK based company called Canonical Ltd. All the principles used to develop the Ubuntu software are based on the principles of Open Source software development. Following are some of the significant features of Ubuntu − The desktop version of Ubuntu supports all the normal software on Windows such as Firefox, Chrome, VLC, etc. The desktop version of Ubuntu supports all the normal software on Windows such as Firefox, Chrome, VLC, etc. It supports the office suite called LibreOffice. It supports the office suite called LibreOffice. Ubuntu has an in-built email software called Thunderbird, which gives the user access to email such as Exchange, Gmail, Hotmail, etc. Ubuntu has an in-built email software called Thunderbird, which gives the user access to email such as Exchange, Gmail, Hotmail, etc. There are a host of free applications for users to view and edit photos. There are a host of free applications for users to view and edit photos. There are also applications to manage videos and it also allows the users to share videos. There are also applications to manage videos and it also allows the users to share videos. It is easy to find content on Ubuntu with the smart searching facility. It is easy to find content on Ubuntu with the smart searching facility. The best feature is, it is a free operating system and is backed by a huge open source community. The best feature is, it is a free operating system and is backed by a huge open source community. Every year there are 2 releases of Ubuntu, one in April and one in October, from Canonical. The version number normally denotes the year in which the software was released. For example, version 14.04 specifies that it was released in the year 2014 and in the month of April. Similarly, the version 16.04 specifies that it was released in the year 2016 and in the month of April. The April build every year is the more stable build, while the October build does a lot of experimentation on new features. The official site for Ubuntu is https://www.ubuntu.com/ The site has all information and documentation about the Ubuntu Software. It also has the download links for both the server and desktop versions of Ubuntu. Ubuntu comes in a variety of flavors. In this chapter, we will discuss briefly about some of the popular flavors of Ubuntu. This is the operating system which can be used by regular users. This comes pre-built with software that help the users perform usual basic activities. Operations such as browsing, email and multimedia are also available in this edition. The latest version as of September 2016 is 16.04.01. The server version is used for hosting applications such as web servers and databases. Each server version is supported by Ubuntu for 5 years. These operating systems have support for cloud platforms such as AWS and Azure. The latest version as of September 2016 is 16.04.1. The normal Ubuntu interface is based on a software called Unity. However, Kubuntu is based on a software called KDE Plasma desktop. This gives a different look and feel to the Ubuntu software. Kubuntu has the same features and software availability as Ubuntu. The official site for Kubuntu is https://www.kubuntu.org/ This is also based of the Ubuntu operating system. It comes pre-built with a lot of applications for the modern user in the space of photos and multimedia. This operating system is completely based on the open source community. The official site for Linux Mint is https://www.linuxmint.com/ We need to ensure we have the right hardware specifications in order to have Ubuntu installed. Ensure the following system requirements are met before proceeding with the installation. Step 1 − To download Ubuntu, go to the following url − https://www.ubuntu.com/download/desktop Step 2 − On this page, there is an option to download the older versions of Ubuntu if required. Click the Alternative downloads and torrents link. Step 3 − Go to Past releases link. It then presents a page with all the past releases of the Ubuntu software. Now let’s learn about installing the desktop version of Ubuntu. For the purpose of this tutorial, we will go with the latest version which is 16.04. The installer is a ISO image which can be mounted on a DVD drive or USB stick. Once the image is booted on the machine, following are the steps for installation. Step 1 − The first screen allows us to either install or try out Ubuntu. The try out option allows us to see the features of Ubuntu without actually installing it. However, we want to use Ubuntu, so let’s choose the Install Ubuntu option. Step 2 − The next screen gives you 2 options. One is to download updates in the background while installing and the other is to install 3rd party software. Check the option to install 3rd party software. Then click the Continue button. Step 3 − In the next screen, the following options are presented − The disk is erased and the installation is carried out. If there was another operating system already on the disk, then Ubuntu would detect it and give the user the option to install the operating system side by side. The disk is erased and the installation is carried out. If there was another operating system already on the disk, then Ubuntu would detect it and give the user the option to install the operating system side by side. There is an option to encrypt the installation. This is so that if anybody else were to steal the data, they would not be able to decrypt the data. There is an option to encrypt the installation. This is so that if anybody else were to steal the data, they would not be able to decrypt the data. Finally, Linux offers a facility called LVM, which can be used for taking snapshots of the disk. Finally, Linux offers a facility called LVM, which can be used for taking snapshots of the disk. For the moment, to make the installation simple, let’s keep the options unchecked and proceed with the installation by clicking the Install Now button. Step 4 − In the following screen, we will be prompted if we want to erase the disk. Click the Continue button to proceed. Step 5 − In this screen, we will be asked to confirm our location. Click the Continue button to proceed. Step 6 − Now, we will be asked to confirm the language and the keyboard settings. Let us select English (UK) as the preferred settings. Step 7 − In the following screen, we will need to enter the user name, computer name and password which will be used to log into the system. Fill the necessary details as shown in the following screenshot. Then, click the continue button to proceed. The system will now proceed with the installation and we will see the progress of the installation as shown in the following screenshot. At the end of the installation, the system will prompt for a restart. Step 8 − Click the Restart Now to proceed. Once the restart is complete, log in with the username and password. Once logged in, the desktop is presented as shown in the following screenshot. We now have a fully functional version of Ubuntu. In the subsequent chapters, we will look at the various features available. Let us take a quick look at the Ubuntu environment before we proceed ahead with the remaining chapters. The Control Panel on the left-hand side of the screen presents shortcuts for all of the most used applications. Using these options, we can launch the LibreOffice component, the Firefox browser, the Software Center and many other applications. When we launch any application, we will get the associated menu bar at the top of the application, which will have the different menu options for that application. We can choose to close the entire window or resize the window, if required. On the right-hand side of the screen is the task bar. The taskbar allows us to choose the change in volume settings, view the status of your internet connect, change your language and other settings, and view the battery status while working on a laptop. By default, Ubuntu comes with pre-built required drivers for the mouse, keyboard, audio and video drivers. Long gone are the days where device drivers used to be a nightmare for Linux-based operating systems. To view the options for devices, go to the settings options on the left-hand side control panel. In the hardware section, you will see the various options for the hardware devices such as the display monitor, keyboard, mouse, etc. For example, using the Display section, we can change the resolution of the screen along with other display settings as shown in the following screenshot. To install any additional drivers, we need to go to the respective driver website and download the necessary distribution for the particular device driver. Then, use the Software Center to install the required device driver. Ubuntu has a Software Center using which you can install a host of applications. The Software Center is designed to search the Internet for available software which can be downloaded and installed. Step 1 − In the control panel, the Software Center appears on the left-hand side of the screen. In the following screenshot, it is encircled in a red box. Double-click to open it. Once open, it shows the following options − View all the available software. All software currently installed on the machine. Any updates available for the software currently installed on the machine. Step 2 − We can also browse through various software categories. For example, let’s click the Audio category. We can see a list of available software for installation. As seen in the following screenshot, the application ‘Rhythmbox’ has already been installed. Step 3 − Now let us choose an application, say the Music application and see how it installs. Step 4 − Once we click the Music application, the following screenshot pops up. Click the Install button to begin the installation. We will then see the Installing progress bar to show that the Music application is being installed. Step 5 − Once the installation is complete, click the Launch button to launch the software. To see the list of already installed software on the machine, go to the Installed section of the Software Center application. This presents an option to remove the unwanted software if required, as shown in the following screenshot. To remove any unwanted software, click the Remove button associated with the required software. In the updates section, we can install critical updates available for the Ubuntu operating system. This section also shows the updates available for the software already installed on the system. Click the Install button next to the desired update that needs to be installed. The default browser for Ubuntu is Firefox and the latest version of Ubuntu always comes with the latest version of Firefox. On the desktop, you will see Firefox as the third component on the lefthand side. Double-click the icon to get started. We can type the address of the site we wish to visit in the address bar and hit enter to get the site loaded. We will get the same user-like experience as in Windows. Step 1 − Additional add-ons can be installed by going to the options and choosing the Add-ons option. Using this option, we can view the add-ons installed and install new ones. We can search for an add-on and then click the Install button to install an add-on. Step 2 − For example, let us install the “Download flash and Video” add-on as shown in the above screenshot. Click the Install button at its side. Step 3 − Once done, the browser will prompt for restart. After restarting the browser, go to the Installed Add-ons section. It will show the “Flash and Video Download” add-on installed as seen in the following screenshot. Here, we can see how the browser will adapt to various screen sizes. Step 1 − Click Options → Developer. Step 2 − Click Responsive Design View. Now, we can view the site in different browser sizes to see if they would respond as they should if they are viewed on different devices. The default application for Chrome usage on Ubuntu is called Chromium. Following are the steps to install Chromium − Step 1 − Go to the application manager for Ubuntu and go to the Internet section. Step 2 − In the following screen, click the Chromium web browser option. Step 3 − Next, click the Install button to install Chromium. Step 4 − Once the browser is installed, the chromium browser option will appear on the left-hand panel. Use it to launch Chromium. The default email client in Ubuntu is Thunderbird. The following steps show how to start using Thunderbird as the email client software. We can quickly search for any application using the Search facility in Ubuntu. Step 1 − Double-click on the search facility, enter the keyword of email and the search result of Thunderbird email will appear. Step 2 − Double-click the search result to launch the Thunderbird mail client. Once the email client is launched, there will be a request to link an email account to the mail client. Step 3 − Click “Skip this and use my existing email” button, so that we can use the current email credentials. Step 4 − Enter the required credentials and click the Continue button to proceed. Once configured, the email client will then provide the common features for any email client. Now, we will be able to view the Inbox as well as all the messages in the Inbox. Step 5 − Click any message to get more information on the received email as shown in the following screenshot. Step 1 − In the Menu option, click the Write option to create a message which needs to be sent. Step 2 − Enter the message details. Once complete, click the Send Button. Note, there is also an option to spell check and add attachments. The sent messages will be displayed in the Sent messages section as shown in the following screenshot. On the right-hand side of the screen, there are shortcuts available to view mail, compose a new message, and view contacts as seen in the following screenshot. The default messaging software used on desktops today is the Skype software. This software is distributed by Microsoft. Skype by default does not come with Ubuntu installation. It will not be present in the Software Center. We have to download and install it from the official Skype site. Following are the steps to get this in place. Step 1 − Go to the official download site for Skype − https://www.skype.com/en/downloadskype/skype-for-computer/ Step 2 − The site will automatically understand that we are working from a Linux distribution and provide options for downloading the Linux version of Skype. We will choose the Ubuntu 12.04 version, as this will work on the later distribution. Step 3 − Once the package is downloaded, it will open in the Software Center. Choose the Install option to install the package. Step 4 − Once Skype is installed, we can search for it and launch it accordingly. Step 5 − Click the ‘I Agree’ button in the following screenshot. Skype will now launch. Step 6 − Enter the required credentials to start using Skype. Ubuntu provides some options when it comes to Media Players. By default, it contains a music player called Rhythmbox. We can search for it, and launch it as shown in the following screenshot. The general user interface of Rhythmbox is as shown in the following screenshot. It can be used to play music from the computer or even download and listen to songs from the Internet. To add music, click the File menu option and choose the Add Music option. To listen to radio stations, click on the Radio option on the left hand side of the screen, click the desired radio station, and click the play button. Shotwell is the default application for managing photos. This application does a good job in offering the users all the possible options required for managing photos and photo albums. We can search for the application and launch it as shown in the following screenshot. The general user interface of the application is as shown in the following screenshot. To import the existing folders, choose the menu option of File → Import from folder. Then choose the location to which the photos are to be imported and click the OK button. It now gives an option to either copy the photos from the place or to Import in place. Let’s choose the option to copy the photos. Once done, the photos will then be visible in the source location. Enhancement tools can be used to enhance the picture. To do so, just click the picture and choose the Enhance option from the left-hand context menu. We can then enlarge the picture, auto correct it, remove red-eye along with many other adjustment features. VLC is the most widely used video player and this is also available in Ubuntu. To get VLC installed, following are the steps. Step 1 − Go to the Software Center and choose the Video option. Step 2 − Choose the option of VLC media player as shown in the following screenshot. Step 3 − Click the Install button in the following screen to begin the installation of VLC media player. Step 4 − Once complete, click the Launch button. VLC media player will now launch. The media player can be normally used as on a Windows machine. Ubuntu provides the facility to create new users who can be authorized to log on to the system. Let’s look at the different functions that can be performed with the help of user management. The following steps need to be performed for the creation of users. Step 1 − Launch the user management console from the search menu. In the search menu, enter the keyword of users. The User Accounts icon will then appear. Double-click on the User Accounts icon. Step 2 − The user management screen will then pop up as shown in the following screenshot. To perform any sort of user management, we first need to press the Unlock button and enter our administrator credentials. Step 3 − Enter the administrator credentials in the pop-up box which comes up and click the Authenticate button. Once we click Authenticate, all the user management functions on the screen will become enabled. Step 4 − Click the plus button to create a user. Step 5 − Enter the user details. We can only create Standard and Administrator account types. Step 6 − Click the Add button to complete the operation of adding the user. When the user is created, the user account is disabled. This is because a password has not been associated with the account. Following are the steps to enable the user account. Step 1 − Click the Account disabled option. This will prompt for the password dialog box. We have the option to either set a password, log in without a password, or enable the account. A good practice is to always set a password for an account. Step 2 − To set the password and click the Change button. Step 3 − The account will now be enabled. Log in using the newly created account. To manage user permissions and groups, an additional package needs to be installed. Following are the steps to manage user permissions and groups. Step 1 − Go to the search option and type the command keyword. Step 2 − The search result of Terminal appears. Click it to open the command prompt. Step 3 − Next, issue the following command. sudo apt-get install gnome-system-tools The apt-get command line is used to install additional packages from the Internet for the Ubuntu system. Here, we are telling Ubuntu that we want to install additional system tools so that we can manage user permissions and groups. Step 4 − We will then be prompted for the password of the current logged in account and to also confirm to download the necessary packages for the installation. Enter the ‘Y’ option to proceed. Step 5 − Once the installation is complete, when we search for users in the search option in Ubuntu, we can see an additional option of Users and Groups. Step 6 − Click the Users and Groups option. Now, there will be an additional option of user and groups. Step 7 − Click the Advanced settings button. We will be prompted to enter the password of the current logged on user to authenticate. Enter the password and click the Authenticate button. Step 8 − In the next dialog box which appears, we will then be able to assign the required user privileges to the user. Step 9 − Now, if we click on the Groups option, we will see that it has the option to create and delete groups. Step 10 − Click on the Add button to add a group. Step 11 − In the next dialog box, we can provide a group name and assign members to that group. Step 12 − Finally, click the OK button to create the group. To open the file like explorer in Ubuntu, click the Files option in the software launcher. In the following screenshot the Files icon is encircled in red. On clicking the icon, the following screen which is the File like explorer in Ubuntu opens up. Step 1 − To create a folder, choose a location where the folder needs to be created. Step 2 − Then right-click and choose the option of New Folder. Step 3 − Provide a name for the folder accordingly. Step 1 − To rename a folder, right-click the folder which needs to be renamed. Step 2 − Right-click and choose the rename option from the context menu. Step 3 − Provide the new name of the folder accordingly. Note − There are other options such as move or copy the folder or move the folder to trash. To see the properties of a file, right-click the file and choose the Properties option from the context menu. Using the option, we can view the properties of the file and modify the permissions of the file accordingly as shown in the following screenshot. The Word Writer comes in-built in Ubuntu and is available in the Software launcher. The icon is encircled in red in the above screenshot. Once we click on the icon, the writer will launch. We can start typing in the Writer as we normally would do in Microsoft Word. To save a document, just click on the save menu option as shown in the following screenshot. Specify the location, the name of the file and then click the Save button. To create a new document, choose the new menu option as shown in the following screenshot. It shows an option to create various types of documents. To open an existing document, choose the option of opening an existing document from the file menu options as shown in the following screenshot. The option icon is encircled in red. Once the open menu option is clicked, it presents a dialog box with an option to choose the file which needs to be opened. Click on the desired file and then click Open. Tables can be inserted using the Insert table option as shown in the following screenshot. Once the table has been added, we can then work on the table as we would on Microsoft Word. To add additional rows and columns work to the table, right-click on the table and choose the various table options available. You can also work with the format of the text using the various font options in the toolbar of Word Writer. The default application for spreadsheets in Ubuntu is called Calc. This is also available in the software launcher. Once we click on the icon, the spreadsheet application will launch. We can edit the cells as we would normally do in a Microsoft Excel application. Formulas can be added in the same manner as in Microsoft Excel. The following example shows an excel sheet which has 3 columns. The 3rd column is the multiplication of the Units and Unit price column. The columns can be dragged to ensure the same formula is repeated for each row. To save a sheet, go to the Save As menu option as shown in the following screenshot. Provide the name, location of the spreadsheet and click the Save button to save the sheet. There are various other formatting options available in the toolbar in the Calc application as shown in the following screenshot. On the right-hand side of the Calc application, there are various other options. One of them is to insert a chart in the spreadsheet. Once we click the Chart option, it will prompt for the type of Chart to be inserted. Choose a chart type and click the Finish button. Now, we can see the Chart in the spreadsheet. LibreOffice is a suite of office products available in Ubuntu. It is similar to the Microsoft suite of products although there are some features of Microsoft Office that does not work with LibreOffice and vice versa. LibreOffice was first introduced in the year 1985 by a company called StarOffice. In the year 2002, the suite was taken by OpenOffice.org with Sun Microsystems being a major contributor to the product. From the year 2010 onwards, a separate branch of the source code of the product was taken which is now known as LibreOffice. We will look at the LibreOffice writer and Calc in subsequent chapters. In this chapter, we will look at LibreOffice Impress which is the PowerPoint version of Microsoft. The LibreOffice suite comes in-built in Ubuntu and is available in the Software launcher. The icon of LibreOffice is encircled in red in the above screenshot. Once we click on the icon, the Impress Software will launch and the following screen will pop up. The interface looks quite similar to Microsoft PowerPoint. We can then modify the content on the slides as required. Adding slides to Impress is pretty similar to Microsoft PowerPoint. There are multiple ways of adding slides. One way is to use the Duplicate Slide option. We can decide on the slide layout of the new slide by choosing the layout from the layout panel that appears on the right-hand side of the screen. To save the presentation, choose the ‘Save As’ menu option. Provide the name and location of the slide and click the Save button. To open an existing presentation, click the Open menu option. Choose the location and name of the file. Click the Open button to open the presentation. 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 Since we have the ability to work with the command line which we covered in the previous chapter, it is common to create scripts which can perform simple jobs. Scripting is normally used to automate administrative tasks. Let’s create a simple script using the following steps. The script will be used to display the IP address assigned to the machine. Step 1 − Open the editor. Just like notepad in Windows, Ubuntu has a text editor. In the search dialog box, enter the keyword of editor. Then double-click on the Text Editor option. The following editor screen pops up. Step 2 − Enter the following text in the editor. originalAddress=@(ifconfig | grep “inet addr” | head –n 1 | cut –d “:” –f 2 | cut –d “ “ –f 1) echo $originalAddress Step 3 − Save the file as write-ip.sh. Now once you have saved the file, we need to assign the file some execute rights. Otherwise, we will not be able to execute the file. Step 4 − Go to the command prompt, navigate to the Desktop location and issue the following command. chmod a+x write-ip.sh The above command will provide execute permissions to the file. Step 5 − Now, we can execute the file by issuing the following command. ./write-ip.sh The output will be the IP address assigned to the machine as shown in the following screenshot. Ubuntu provides the options to view the network details of the workstation. Following are the steps to view the network details of the machine. Step 1 − In the search dialog box, type the keyword ‘network’. Step 2 − Double-click the Network icon. We can see the hostname assigned to the machine. Step 3 − Click the Network folder option and we can see the IP address assigned to the machine. Step 4 − Click the Options button and we can modify the details of the network connection. Ubuntu also comes in a server version. This version is used for hosting applications such as webbased applications. The server version can be downloaded from the Ubuntu site in the same way as the desktop version of Ubuntu. For the purpose of this tutorial, let’s look at the installation of the server version 14.04, which is one of the most popular versions of Ubuntu. Following are the steps for installation. Step 1 − Download for the server version from the link − http://releases.ubuntu.com/14.04/ Step 2 − Once the download of the server version is complete, put it on a USB device or bootable DVD. Boot the hardware from the bootable device. Step 3 − The system prompts to select a language for the Installation. Select English and press the Enter button. Step 4 − In the next step, choose the option to install Ubuntu server and press the Enter button. Step 5 − The system again prompts to select a language for the installation. Choose the English language and press the Enter button. Step 6 − In the next screen, select the desired region and then press the Enter button. Step 7 − The next step includes the detection of the Keyboard layout. Choose the ‘No’ option and press the Enter button. Step 8 − In the next screen, click the English(US) as the keyboard layout and press the Enter button. Step 9 − After performing a set of initial configuration steps, we will be prompted to enter a name for the system. Enter Ubuntuserver and press the Enter key. Step 10 − You will then be prompted to enter a real name and the username for an account to be created. Enter the name ‘demo’ and press Enter on both screens. Step 11 − Now we need to enter a password for the new account. Enter a password and press the Enter button. The system will ask to verify the password. Step 12 − The system then asks if we want to encrypt the home directory. For the moment, let us say ‘No’ and press Enter to proceed. The encryption is such that if anyone does hack into the system, they will not be able steal the data as it is encrypted. Once we are an advanced user of Ubuntu server, we can choose ‘Yes’ as the option. But for now let’s leave this as unencrypted. Step 13 − The Ubuntu server installation will then set the time settings. Choose ‘Yes’ and press the Enter button to proceed. Step 14 − Next the disk setup will take place. Choose the option ‘Guided – use entire disk and set up LVM’ and press the Enter button to proceed. Step 15 − The installation will erase all the data on the disk. Since this is a fresh installation, this is not an issue. Click the Enter button to proceed. Step 16 − We will be asked to confirm all the changes to the disk. Choose the ‘Yes’ option and Press the Enter button to proceed. Step 17 − The installation will detect the size of the hard disk. Hit the Enter button to proceed. Step 18 − The system then asks to finalize the changes to the disk. Choose the ‘Yes’ option and press the ‘Enter’ button to proceed. The system will then start performing a series of steps for the installation. Step 19 − It will then ask to configure the Proxy setting. We can leave this setting as is and press the Enter button. The installation will then start configuring the apt package manager. The installation of the necessary software will then start. Step 20 − The system then asks if we want to configure automatic updates. For now, select ‘No automatic updates’ and press the Enter button. Step 21 − The next step is to install any additional software. Select ‘OpenSSH’ server which allows one to remotely connect to the server. Press the Enter button to proceed. The system will start installing the remaining software on the system. Step 22 − The system now requests to install the GRUB boot loader. Choose the ‘Yes’ option and press the Enter button to proceed. Step 23 − Once the installation is complete, press the Continue option to proceed. The system will then reboot after the installation. Step 24 − We will then be requested to log into the system. Enter the credentials which were entered at the time of installation. We will finally be logged into the system. We have successfully installed the server version of Ubuntu. The Secure Shell (SSH) in Linux is used to log into the machine in an encrypted and safe manner. This helps in providing a secure channel to streamline all requests to the Ubuntu server. SSH uses cryptographic keys to log into the server. On Windows, the most common tool to perform a secure shell to a Linux server is putty. In this chapter, we will learn how to use putty to Secure Shell into a server. Step 1 − Download putty from the http://www.putty.org/ site. Step 2 − Before connecting to use putty, we need to know the IP address of our Ubuntu box. To do this, type ifconfig in the command shell of the Ubuntu server. From the above screenshot, we know that the IP address of the server is 192.168.0.20 Step 3 − Next step is installing SSH on the server. In order to SSH to a server, you need to make sure it is installed. Run the following command in the Ubuntu server command prompt session. sudo apt-get install openssh-server Step 4 − Launch PuTTY. Enter the IP address of the Ubuntu server and click the Open button. Step 5 − The next screen requests to accept the encrypted key sent from the server. Step 6 − Finally, enter the username and password to log into the server. We have successfully established a secure shell to the server. The Ubuntu desktop edition can be used to develop web applications. One of the most famous software which can be used for development on Ubuntu is Aptana. Let’s see the steps on how to get Aptana and get a simple web project up and running. Step 1 − On Ubuntu desktop, open Firefox and go to the url − http://www.aptana.com/products/studio3/download Step 2 − Click the Download Aptana Studio 3 button. Step 3 − Once downloaded, extract the zip file to a suitable location. Once extracted, click the AptanaStudio3 link. The following interface pops up. We can then choose to create a new web project, if required. The required development can be carried out on the web project. Nginx is a much lighter web server than Apache. This web server has become quite popular in the recent years. The Apache web server can be quite complex to configure and use. However, Nginx is much simpler. This chapter will focus on how to install this light web server. To install Nginx, following are the steps − Step 1 − Open the command terminal on Ubuntu desktop and run the following command. sudo apt-get update This first ensures that all packages on the operating system are up to date. Step 2 − Next enter the following command to install the nginx server. sudo apt-get install nginx Step 3 − Once done, if we run ps –ef | grep nginx, we can see the process for the web server in a running state. We now have nginx run as a web server on Ubuntu. Ubuntu can also be installed as virtual machines. Some of the software which support virtual machines are − Microsoft Hyper-V VMWare Workstation Oracle VirtualBox Let’s use Oracle VirtualBox to create our Ubuntu virtual machine. Oracle VirtualBox is a free tool from Oracle. Following are the steps to have the virtual machine in place. Step 1 − Download Oracle VirtualBox from the oracle site − https://www.virtualbox.org/ Step 2 − Go to the downloads section and download the Windows version. Step 3 − Once download is complete, install VirtualBox. Launch the installer. Click the Run button on the following screen. Step 4 − Click the Next button on the subsequent screen. Step 5 − Choose the appropriate folder location and click the Next button. Step 6 − Click Next on the subsequent screen. Step 7 − Click the ‘Yes’ button on the next screen to proceed ahead with the installation. Step 8 − Click Install on the next screen. Step 9 − After the installation is complete, launch Oracle VirtualBox. On the Launch screen, click the ‘New’ menu option. Step 10 − Give a name for the virtual machine and give the type as Ubuntu and then click the Next button. Step 11 − In the next screen, keep the recommended RAM as it is and click the Next button. Step 12 − Accept the default setting for the virtual hard disk and click the Create button. Step 13 − Accept the hard disk type and click the Next button. Step 14 − Accept the default type of physical hard disk allocation and click the Next button. Step 15 − Accept the default file location and click the Create button. Step 16 − Now that the Virtual Machine has been created, click the Settings Menu option. Step 17 − Go to the Storage option, click the Empty disk icon and browse for the Ubuntu iso image. Then click the OK button. Finally click the Start button. The system prompts to install Ubuntu. Follow the steps in the Installation chapter and we will have a Virtual Machine hosting Ubuntu. MySQL and Python are famous database and development software respectively. These are normally installed on Linux-based systems. Let’s see how we can get them installed on Ubuntu server environments. The first thing to do is to find out what is the version of Python installed on the system. We can find this issuing the following command. Python –v Where the –v option specifies to show what is the version of Python installed. The following screenshot shows a sample of the output of the above command. From the above output, we can see that the version of Python installed is version 2.7. There is another way to see if Python is installed via the following commands. Python –V Python3 –V The later command is used to see the version 3 of Python installed. If we want to have the latest version of Python installed, then we need to issue the following statement. sudo apt-get install python3 The above command will download the necessary packages for Python and have it installed. To install MySQL, the following steps need to be followed. Step 1 − Issue the apt-get command to ensure all operating system packages are up to date. sudo apt-get update Step 2 − Once all the packages have been updated, it is time to get the packages for MySQL. sudo apt-get install mysql-server The above command will start the download of all the relevant packages for MySQL. Once the download completes and the installation starts, the installer will first ask to configure a root password. Step 3 − Enter the required password and click the OK button. It will also prompt to re-enter the password. Step 4 − To see the MySQL process running, run the following command. ps –ef | grep mysql The following screenshot shows mysqld which is the daemon process for mysql running in the background. Step 5 − To configure mysql, run the following command. /usr/bin/mysql_secure_installation It prompts to enter the root password which was entered during the installation process. Step 6 − Enter the password and hit Enter. Now, it prompts on whether we want to change the root password. Step 7 − Enter ‘N’ for No and proceed. Again, it prompts on whether we want to remove the Anonymous access. Step 8 − When connecting from other machines on this database, it is advised to keep the default options as ‘N’ for both anonymous users and disallow root login remotely. Step 9 − It is advised to provide the option as No for the options of Remove test database as well. We can enter ‘Y’ to reload the privileges table. Finally, the configuration of MySQL will be complete. Node.js is a popular JavaScript framework used for developing server side applications. In this chapter, we will see how to get Node.js installed on Ubuntu. Following are the steps to get Node.js installed. Step 1 − Run the following command. sudo apt-get install nodejs This will install all the necessary packages for Node.js Next, we need to install the Node package manager which is required for Node.js applications. Step 2 − Run the following command. sudo apt-get install npm All the necessary packages for the node package manager will be installed. Step 3 − Next, create a symbolic link to the Node.js folder. Then, run the Node –v command and npm –v to see the Node and npm version installed. Docker is a container service which allows one to run applications or even operating systems on a host operating system as containers. Containers are a new and exciting technology that has evolved over the last couple of years and being adopted by a lot of key organizations. Docker is a company that develops these special containers for applications. The official website for Docker is https://www.docker.com/ As an exercise, let’s install a CentOS container on an Ubuntu system. CentOS is a Linux-based operating system from Red Hat. Thus, we will be running the CentOS system on top of Ubuntu. Following are the steps to have this in place. Step 1 − The first step is to install the Docker application on Ubuntu server. Thus on the Ubuntu test server, run the following command to ensure that OS updates are in place. sudo apt-get update Step 2 − Once all updates have been processed, issue the following command to get Docker installed. sudo apt-get install -y docker.io Step 3 − Once the Docker packages are installed, we should receive an output message stating that the Docker process has started and is running. The Docker process is known as the Docker engine or Docker daemon. Step 4 − To view the version of Docker running, issue the Docker info command. Step 5 − The next step is to install our CentOS image on Ubuntu. Docker has a special site called the Docker hub, which is used to store pre-built images for Docker. The link to the site is https://hub.docker.com/ Step 6 − Do a quick and simple sign-in process to be able to log into the site and see all the available Docker images. Step 7 − Once logged in, click the Explore button to see all the available Docker images. The two important points to note are − The Docker pull command. This is the command to install the Docker image on Linux box. The Docker pull command. This is the command to install the Docker image on Linux box. The Docker details for the various versions of CentOS. The Docker details for the various versions of CentOS. Step 8 − On Ubuntu box, run the command. sudo docker pull centos:latest The download of the Docker component starts and the CentOS Docker is downloaded. The name of the Docker image is centos:latest, which means that we have the latest Docker image for CentOS. Step 9 − To see all the Docker images installed, issue the command sudo docker images In the following screenshot, we can see that the Docker image is just 196.8 MB in size, and this is the subset of the CentOS which now runs on Ubuntu system. Step 10 − To start CentOS, we need to issue a command to the OS to get a thread started. We can do this by running the following command. sudo docker run -it centos /bin/bash The above command does the following things − Runs the CentOS Docker image. Runs the CentOS Docker image. Runs the image in interactive mode by using the -it option. Runs the image in interactive mode by using the -it option. Runs the /bin/bash command as the initial process. Runs the /bin/bash command as the initial process. We can also install Ubuntu on various cloud environments such as Google Cloud, Amazon web services, and Azure web services. In this chapter, we will see how to get Ubuntu up and running on Amazon web services. Following are the steps to get this in place. Step 1 − One can get a free account with Amazon web services. All we need to do is register with AWS on the following url − https://aws.amazon.com/ Step 2 − Click the Sign in to the Console and it presents the following dialog box. Step 3 − Click the option ‘I am a new user’ and enter the required email id of an existing Gmail account. Then click the ‘Sign in using our secure server’ button. We will then need to give some information in the subsequent screen to create an account. Step 4 − Once an account has been created, we can log into the console. Once logged in, click the EC2 option. This option is used for creating virtual machines on the cloud. Step 5 − In the following screenshot, click the Launch Instance button. Step 6 − The next screen prompts to select an appropriate AMI. An AMI is a pre-built image for an operating system in Amazon. Scroll down until to the Ubuntu option and click the Select button. Step 7 − In the next screen, choose the configuration of the machine. Choose the General purpose – t2.micro option and then click the ‘Next: Configure Instance Details’ button. Step 8 − In the next screen, enter the following details as shown in the screenshot. The number of instances to launch – Keep 1 as the default. The number of instances to launch – Keep 1 as the default. VPC – If there is no existing VPC, choose the option to create a new one. VPC – If there is no existing VPC, choose the option to create a new one. Now, if we choose the option to create a new subnet, we need to perform the following sub steps. Click the Create VPC button. (Note: The VPC is known as a virtual private network which is used to store all AWS objects in an isolated environment.) In the Create VPC dialog box, enter the following details and click the ‘Yes Create’ button. For the subnet, keep the default setting as it is. For the Auto-assign Public IP option, choose ‘use subnet setting(Enable)’. Keep the IAM Role as ‘none’. Keep the Shutdown behavior as ‘none’. The remaining settings can remain as by default. Click the Next: Add Storage button. Step 9 − In the next screen, keep the default storage as is and click the Review and Launch button. Step 10 − The review screen will pop up. Click the Launch button. Step 11 − The next screen prompts to create a new key pair. This is required to log into the instance when it is created. Enter a key name and click the download Key pair button. Step 12 − Once download is complete, click the Launch Instances button. Step 13 − Click the ‘View Instances’ button. Step 14 − Once the state of the instance is running, click the Connect button. The next dialog box presents the steps to log into the Ubuntu server machine. Step 15 − Perform the steps as we would normally do, using a SSH client to log into the machine. 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": 2427, "s": 2133, "text": "Ubuntu is a Linux-based operating system. It is designed for computers, smartphones, and network servers. The system is developed by a UK based company called Canonical Ltd. All the principles used to develop the Ubuntu software are based on the principles of Open Source software development." }, { "code": null, "e": 2486, "s": 2427, "text": "Following are some of the significant features of Ubuntu −" }, { "code": null, "e": 2595, "s": 2486, "text": "The desktop version of Ubuntu supports all the normal software on Windows such as Firefox, Chrome, VLC, etc." }, { "code": null, "e": 2704, "s": 2595, "text": "The desktop version of Ubuntu supports all the normal software on Windows such as Firefox, Chrome, VLC, etc." }, { "code": null, "e": 2753, "s": 2704, "text": "It supports the office suite called LibreOffice." }, { "code": null, "e": 2802, "s": 2753, "text": "It supports the office suite called LibreOffice." }, { "code": null, "e": 2936, "s": 2802, "text": "Ubuntu has an in-built email software called Thunderbird, which gives the user access to email such as Exchange, Gmail, Hotmail, etc." }, { "code": null, "e": 3070, "s": 2936, "text": "Ubuntu has an in-built email software called Thunderbird, which gives the user access to email such as Exchange, Gmail, Hotmail, etc." }, { "code": null, "e": 3143, "s": 3070, "text": "There are a host of free applications for users to view and edit photos." }, { "code": null, "e": 3216, "s": 3143, "text": "There are a host of free applications for users to view and edit photos." }, { "code": null, "e": 3307, "s": 3216, "text": "There are also applications to manage videos and it also allows the users to share videos." }, { "code": null, "e": 3398, "s": 3307, "text": "There are also applications to manage videos and it also allows the users to share videos." }, { "code": null, "e": 3470, "s": 3398, "text": "It is easy to find content on Ubuntu with the smart searching facility." }, { "code": null, "e": 3542, "s": 3470, "text": "It is easy to find content on Ubuntu with the smart searching facility." }, { "code": null, "e": 3640, "s": 3542, "text": "The best feature is, it is a free operating system and is backed by a huge open source community." }, { "code": null, "e": 3738, "s": 3640, "text": "The best feature is, it is a free operating system and is backed by a huge open source community." }, { "code": null, "e": 4241, "s": 3738, "text": "Every year there are 2 releases of Ubuntu, one in April and one in October, from Canonical. The version number normally denotes the year in which the software was released. For example, version 14.04 specifies that it was released in the year 2014 and in the month of April. Similarly, the version 16.04 specifies that it was released in the year 2016 and in the month of April. The April build every year is the more stable build, while the October build does a lot of experimentation on new features." }, { "code": null, "e": 4297, "s": 4241, "text": "The official site for Ubuntu is https://www.ubuntu.com/" }, { "code": null, "e": 4454, "s": 4297, "text": "The site has all information and documentation about the Ubuntu Software. It also has the download links for both the server and desktop versions of Ubuntu." }, { "code": null, "e": 4578, "s": 4454, "text": "Ubuntu comes in a variety of flavors. In this chapter, we will discuss briefly about some of the popular flavors of Ubuntu." }, { "code": null, "e": 4869, "s": 4578, "text": "This is the operating system which can be used by regular users. This comes pre-built with software that help the users perform usual basic activities. Operations such as browsing, email and multimedia are also available in this edition. The latest version as of September 2016 is 16.04.01." }, { "code": null, "e": 5144, "s": 4869, "text": "The server version is used for hosting applications such as web servers and databases. Each server version is supported by Ubuntu for 5 years. These operating systems have support for cloud platforms such as AWS and Azure. The latest version as of September 2016 is 16.04.1." }, { "code": null, "e": 5462, "s": 5144, "text": "The normal Ubuntu interface is based on a software called Unity. However, Kubuntu is based on a software called KDE Plasma desktop. This gives a different look and feel to the Ubuntu software. Kubuntu has the same features and software availability as Ubuntu. The official site for Kubuntu is https://www.kubuntu.org/" }, { "code": null, "e": 5690, "s": 5462, "text": "This is also based of the Ubuntu operating system. It comes pre-built with a lot of applications for the modern user in the space of photos and multimedia. This operating system is completely based on the open source community." }, { "code": null, "e": 5753, "s": 5690, "text": "The official site for Linux Mint is https://www.linuxmint.com/" }, { "code": null, "e": 5848, "s": 5753, "text": "We need to ensure we have the right hardware specifications in order to have Ubuntu installed." }, { "code": null, "e": 5938, "s": 5848, "text": "Ensure the following system requirements are met before proceeding with the installation." }, { "code": null, "e": 6033, "s": 5938, "text": "Step 1 − To download Ubuntu, go to the following url − https://www.ubuntu.com/download/desktop" }, { "code": null, "e": 6180, "s": 6033, "text": "Step 2 − On this page, there is an option to download the older versions of Ubuntu if required. Click the Alternative downloads and torrents link." }, { "code": null, "e": 6290, "s": 6180, "text": "Step 3 − Go to Past releases link. It then presents a page with all the past releases of the Ubuntu software." }, { "code": null, "e": 6601, "s": 6290, "text": "Now let’s learn about installing the desktop version of Ubuntu. For the purpose of this tutorial, we will go with the latest version which is 16.04. The installer is a ISO image which can be mounted on a DVD drive or USB stick. Once the image is booted on the machine, following are the steps for installation." }, { "code": null, "e": 6840, "s": 6601, "text": "Step 1 − The first screen allows us to either install or try out Ubuntu. The try out option allows us to see the features of Ubuntu without actually installing it. However, we want to use Ubuntu, so let’s choose the Install Ubuntu option." }, { "code": null, "e": 7076, "s": 6840, "text": "Step 2 − The next screen gives you 2 options. One is to download updates in the background while installing and the other is to install 3rd party software. Check the option to install 3rd party software. Then click the Continue button." }, { "code": null, "e": 7143, "s": 7076, "text": "Step 3 − In the next screen, the following options are presented −" }, { "code": null, "e": 7361, "s": 7143, "text": "The disk is erased and the installation is carried out. If there was another operating system already on the disk, then Ubuntu would detect it and give the user the option to install the operating system side by side." }, { "code": null, "e": 7579, "s": 7361, "text": "The disk is erased and the installation is carried out. If there was another operating system already on the disk, then Ubuntu would detect it and give the user the option to install the operating system side by side." }, { "code": null, "e": 7727, "s": 7579, "text": "There is an option to encrypt the installation. This is so that if anybody else were to steal the data, they would not be able to decrypt the data." }, { "code": null, "e": 7875, "s": 7727, "text": "There is an option to encrypt the installation. This is so that if anybody else were to steal the data, they would not be able to decrypt the data." }, { "code": null, "e": 7972, "s": 7875, "text": "Finally, Linux offers a facility called LVM, which can be used for taking snapshots of the disk." }, { "code": null, "e": 8069, "s": 7972, "text": "Finally, Linux offers a facility called LVM, which can be used for taking snapshots of the disk." }, { "code": null, "e": 8221, "s": 8069, "text": "For the moment, to make the installation simple, let’s keep the options unchecked and proceed with the installation by clicking the Install Now button." }, { "code": null, "e": 8343, "s": 8221, "text": "Step 4 − In the following screen, we will be prompted if we want to erase the disk. Click the Continue button to proceed." }, { "code": null, "e": 8448, "s": 8343, "text": "Step 5 − In this screen, we will be asked to confirm our location. Click the Continue button to proceed." }, { "code": null, "e": 8584, "s": 8448, "text": "Step 6 − Now, we will be asked to confirm the language and the keyboard settings. Let us select English (UK) as the preferred settings." }, { "code": null, "e": 8834, "s": 8584, "text": "Step 7 − In the following screen, we will need to enter the user name, computer name and password which will be used to log into the system. Fill the necessary details as shown in the following screenshot. Then, click the continue button to proceed." }, { "code": null, "e": 8971, "s": 8834, "text": "The system will now proceed with the installation and we will see the progress of the installation as shown in the following screenshot." }, { "code": null, "e": 9041, "s": 8971, "text": "At the end of the installation, the system will prompt for a restart." }, { "code": null, "e": 9084, "s": 9041, "text": "Step 8 − Click the Restart Now to proceed." }, { "code": null, "e": 9153, "s": 9084, "text": "Once the restart is complete, log in with the username and password." }, { "code": null, "e": 9232, "s": 9153, "text": "Once logged in, the desktop is presented as shown in the following screenshot." }, { "code": null, "e": 9358, "s": 9232, "text": "We now have a fully functional version of Ubuntu. In the subsequent chapters, we will look at the various features available." }, { "code": null, "e": 9462, "s": 9358, "text": "Let us take a quick look at the Ubuntu environment before we proceed ahead with the remaining chapters." }, { "code": null, "e": 9706, "s": 9462, "text": "The Control Panel on the left-hand side of the screen presents shortcuts for all of the most used applications. Using these options, we can launch the LibreOffice component, the Firefox browser, the Software Center and many other applications." }, { "code": null, "e": 9946, "s": 9706, "text": "When we launch any application, we will get the associated menu bar at the top of the application, which will have the different menu options for that application. We can choose to close the entire window or resize the window, if required." }, { "code": null, "e": 10201, "s": 9946, "text": "On the right-hand side of the screen is the task bar. The taskbar allows us to choose the change in volume settings, view the status of your internet connect, change your language and other settings, and view the battery status while working on a laptop." }, { "code": null, "e": 10410, "s": 10201, "text": "By default, Ubuntu comes with pre-built required drivers for the mouse, keyboard, audio and video drivers. Long gone are the days where device drivers used to be a nightmare for Linux-based operating systems." }, { "code": null, "e": 10507, "s": 10410, "text": "To view the options for devices, go to the settings options on the left-hand side control panel." }, { "code": null, "e": 10641, "s": 10507, "text": "In the hardware section, you will see the various options for the hardware devices such as the display monitor, keyboard, mouse, etc." }, { "code": null, "e": 10796, "s": 10641, "text": "For example, using the Display section, we can change the resolution of the screen along with other display settings as shown in the following screenshot." }, { "code": null, "e": 11021, "s": 10796, "text": "To install any additional drivers, we need to go to the respective driver website and download the necessary distribution for the particular device driver. Then, use the Software Center to install the required device driver." }, { "code": null, "e": 11219, "s": 11021, "text": "Ubuntu has a Software Center using which you can install a host of applications. The Software Center is designed to search the Internet for available software which can be downloaded and installed." }, { "code": null, "e": 11399, "s": 11219, "text": "Step 1 − In the control panel, the Software Center appears on the left-hand side of the screen. In the following screenshot, it is encircled in a red box. Double-click to open it." }, { "code": null, "e": 11443, "s": 11399, "text": "Once open, it shows the following options −" }, { "code": null, "e": 11476, "s": 11443, "text": "View all the available software." }, { "code": null, "e": 11525, "s": 11476, "text": "All software currently installed on the machine." }, { "code": null, "e": 11600, "s": 11525, "text": "Any updates available for the software currently installed on the machine." }, { "code": null, "e": 11861, "s": 11600, "text": "Step 2 − We can also browse through various software categories. For example, let’s click the Audio category. We can see a list of available software for installation. As seen in the following screenshot, the application ‘Rhythmbox’ has already been installed." }, { "code": null, "e": 11955, "s": 11861, "text": "Step 3 − Now let us choose an application, say the Music application and see how it installs." }, { "code": null, "e": 12087, "s": 11955, "text": "Step 4 − Once we click the Music application, the following screenshot pops up. Click the Install button to begin the installation." }, { "code": null, "e": 12187, "s": 12087, "text": "We will then see the Installing progress bar to show that the Music application is being installed." }, { "code": null, "e": 12279, "s": 12187, "text": "Step 5 − Once the installation is complete, click the Launch button to launch the software." }, { "code": null, "e": 12512, "s": 12279, "text": "To see the list of already installed software on the machine, go to the Installed section of the Software Center application. This presents an option to remove the unwanted software if required, as shown in the following screenshot." }, { "code": null, "e": 12608, "s": 12512, "text": "To remove any unwanted software, click the Remove button associated with the required software." }, { "code": null, "e": 12803, "s": 12608, "text": "In the updates section, we can install critical updates available for the Ubuntu operating system. This section also shows the updates available for the software already installed on the system." }, { "code": null, "e": 12883, "s": 12803, "text": "Click the Install button next to the desired update that needs to be installed." }, { "code": null, "e": 13127, "s": 12883, "text": "The default browser for Ubuntu is Firefox and the latest version of Ubuntu always comes with the latest version of Firefox. On the desktop, you will see Firefox as the third component on the lefthand side. Double-click the icon to get started." }, { "code": null, "e": 13294, "s": 13127, "text": "We can type the address of the site we wish to visit in the address bar and hit enter to get the site loaded. We will get the same user-like experience as in Windows." }, { "code": null, "e": 13396, "s": 13294, "text": "Step 1 − Additional add-ons can be installed by going to the options and choosing the Add-ons option." }, { "code": null, "e": 13471, "s": 13396, "text": "Using this option, we can view the add-ons installed and install new ones." }, { "code": null, "e": 13555, "s": 13471, "text": "We can search for an add-on and then click the Install button to install an add-on." }, { "code": null, "e": 13702, "s": 13555, "text": "Step 2 − For example, let us install the “Download flash and Video” add-on as shown in the above screenshot. Click the Install button at its side." }, { "code": null, "e": 13924, "s": 13702, "text": "Step 3 − Once done, the browser will prompt for restart. After restarting the browser, go to the Installed Add-ons section. It will show the “Flash and Video Download” add-on installed as seen in the following screenshot." }, { "code": null, "e": 13993, "s": 13924, "text": "Here, we can see how the browser will adapt to various screen sizes." }, { "code": null, "e": 14029, "s": 13993, "text": "Step 1 − Click Options → Developer." }, { "code": null, "e": 14068, "s": 14029, "text": "Step 2 − Click Responsive Design View." }, { "code": null, "e": 14206, "s": 14068, "text": "Now, we can view the site in different browser sizes to see if they would respond as they should if they are viewed on different devices." }, { "code": null, "e": 14323, "s": 14206, "text": "The default application for Chrome usage on Ubuntu is called Chromium. Following are the steps to install Chromium −" }, { "code": null, "e": 14405, "s": 14323, "text": "Step 1 − Go to the application manager for Ubuntu and go to the Internet section." }, { "code": null, "e": 14478, "s": 14405, "text": "Step 2 − In the following screen, click the Chromium web browser option." }, { "code": null, "e": 14539, "s": 14478, "text": "Step 3 − Next, click the Install button to install Chromium." }, { "code": null, "e": 14670, "s": 14539, "text": "Step 4 − Once the browser is installed, the chromium browser option will appear on the left-hand panel. Use it to launch Chromium." }, { "code": null, "e": 14807, "s": 14670, "text": "The default email client in Ubuntu is Thunderbird. The following steps show how to start using Thunderbird as the email client software." }, { "code": null, "e": 14886, "s": 14807, "text": "We can quickly search for any application using the Search facility in Ubuntu." }, { "code": null, "e": 15015, "s": 14886, "text": "Step 1 − Double-click on the search facility, enter the keyword of email and the search result of Thunderbird email will appear." }, { "code": null, "e": 15198, "s": 15015, "text": "Step 2 − Double-click the search result to launch the Thunderbird mail client. Once the email client is launched, there will be a request to link an email account to the mail client." }, { "code": null, "e": 15309, "s": 15198, "text": "Step 3 − Click “Skip this and use my existing email” button, so that we can use the current email credentials." }, { "code": null, "e": 15566, "s": 15309, "text": "Step 4 − Enter the required credentials and click the Continue button to proceed. Once configured, the email client will then provide the common features for any email client. Now, we will be able to view the Inbox as well as all the messages in the Inbox." }, { "code": null, "e": 15677, "s": 15566, "text": "Step 5 − Click any message to get more information on the received email as shown in the following screenshot." }, { "code": null, "e": 15773, "s": 15677, "text": "Step 1 − In the Menu option, click the Write option to create a message which needs to be sent." }, { "code": null, "e": 15913, "s": 15773, "text": "Step 2 − Enter the message details. Once complete, click the Send Button. Note, there is also an option to spell check and add attachments." }, { "code": null, "e": 16016, "s": 15913, "text": "The sent messages will be displayed in the Sent messages section as shown in the following screenshot." }, { "code": null, "e": 16176, "s": 16016, "text": "On the right-hand side of the screen, there are shortcuts available to view mail, compose a new message, and view contacts as seen in the following screenshot." }, { "code": null, "e": 16511, "s": 16176, "text": "The default messaging software used on desktops today is the Skype software. This software is distributed by Microsoft. Skype by default does not come with Ubuntu installation. It will not be present in the Software Center. We have to download and install it from the official Skype site. Following are the steps to get this in place." }, { "code": null, "e": 16624, "s": 16511, "text": "Step 1 − Go to the official download site for Skype − https://www.skype.com/en/downloadskype/skype-for-computer/" }, { "code": null, "e": 16868, "s": 16624, "text": "Step 2 − The site will automatically understand that we are working from a Linux distribution and provide options for downloading the Linux version of Skype. We will choose the Ubuntu 12.04 version, as this will work on the later distribution." }, { "code": null, "e": 16996, "s": 16868, "text": "Step 3 − Once the package is downloaded, it will open in the Software Center. Choose the Install option to install the package." }, { "code": null, "e": 17078, "s": 16996, "text": "Step 4 − Once Skype is installed, we can search for it and launch it accordingly." }, { "code": null, "e": 17143, "s": 17078, "text": "Step 5 − Click the ‘I Agree’ button in the following screenshot." }, { "code": null, "e": 17166, "s": 17143, "text": "Skype will now launch." }, { "code": null, "e": 17228, "s": 17166, "text": "Step 6 − Enter the required credentials to start using Skype." }, { "code": null, "e": 17289, "s": 17228, "text": "Ubuntu provides some options when it comes to Media Players." }, { "code": null, "e": 17346, "s": 17289, "text": "By default, it contains a music player called Rhythmbox." }, { "code": null, "e": 17420, "s": 17346, "text": "We can search for it, and launch it as shown in the following screenshot." }, { "code": null, "e": 17604, "s": 17420, "text": "The general user interface of Rhythmbox is as shown in the following screenshot. It can be used to play music from the computer or even download and listen to songs from the Internet." }, { "code": null, "e": 17678, "s": 17604, "text": "To add music, click the File menu option and choose the Add Music option." }, { "code": null, "e": 17830, "s": 17678, "text": "To listen to radio stations, click on the Radio option on the left hand side of the screen, click the desired radio station, and click the play button." }, { "code": null, "e": 18014, "s": 17830, "text": "Shotwell is the default application for managing photos. This application does a good job in offering the users all the possible options required for managing photos and photo albums." }, { "code": null, "e": 18100, "s": 18014, "text": "We can search for the application and launch it as shown in the following screenshot." }, { "code": null, "e": 18187, "s": 18100, "text": "The general user interface of the application is as shown in the following screenshot." }, { "code": null, "e": 18272, "s": 18187, "text": "To import the existing folders, choose the menu option of File → Import from folder." }, { "code": null, "e": 18361, "s": 18272, "text": "Then choose the location to which the photos are to be imported and click the OK button." }, { "code": null, "e": 18492, "s": 18361, "text": "It now gives an option to either copy the photos from the place or to Import in place. Let’s choose the option to copy the photos." }, { "code": null, "e": 18559, "s": 18492, "text": "Once done, the photos will then be visible in the source location." }, { "code": null, "e": 18709, "s": 18559, "text": "Enhancement tools can be used to enhance the picture. To do so, just click the picture and choose the Enhance option from the left-hand context menu." }, { "code": null, "e": 18817, "s": 18709, "text": "We can then enlarge the picture, auto correct it, remove red-eye along with many other adjustment features." }, { "code": null, "e": 18896, "s": 18817, "text": "VLC is the most widely used video player and this is also available in Ubuntu." }, { "code": null, "e": 18943, "s": 18896, "text": "To get VLC installed, following are the steps." }, { "code": null, "e": 19007, "s": 18943, "text": "Step 1 − Go to the Software Center and choose the Video option." }, { "code": null, "e": 19092, "s": 19007, "text": "Step 2 − Choose the option of VLC media player as shown in the following screenshot." }, { "code": null, "e": 19197, "s": 19092, "text": "Step 3 − Click the Install button in the following screen to begin the installation of VLC media player." }, { "code": null, "e": 19246, "s": 19197, "text": "Step 4 − Once complete, click the Launch button." }, { "code": null, "e": 19343, "s": 19246, "text": "VLC media player will now launch. The media player can be normally used as on a Windows machine." }, { "code": null, "e": 19533, "s": 19343, "text": "Ubuntu provides the facility to create new users who can be authorized to log on to the system. Let’s look at the different functions that can be performed with the help of user management." }, { "code": null, "e": 19601, "s": 19533, "text": "The following steps need to be performed for the creation of users." }, { "code": null, "e": 19796, "s": 19601, "text": "Step 1 − Launch the user management console from the search menu. In the search menu, enter the keyword of users. The User Accounts icon will then appear. Double-click on the User Accounts icon." }, { "code": null, "e": 20009, "s": 19796, "text": "Step 2 − The user management screen will then pop up as shown in the following screenshot. To perform any sort of user management, we first need to press the Unlock button and enter our administrator credentials." }, { "code": null, "e": 20122, "s": 20009, "text": "Step 3 − Enter the administrator credentials in the pop-up box which comes up and click the Authenticate button." }, { "code": null, "e": 20219, "s": 20122, "text": "Once we click Authenticate, all the user management functions on the screen will become enabled." }, { "code": null, "e": 20268, "s": 20219, "text": "Step 4 − Click the plus button to create a user." }, { "code": null, "e": 20362, "s": 20268, "text": "Step 5 − Enter the user details. We can only create Standard and Administrator account types." }, { "code": null, "e": 20438, "s": 20362, "text": "Step 6 − Click the Add button to complete the operation of adding the user." }, { "code": null, "e": 20563, "s": 20438, "text": "When the user is created, the user account is disabled. This is because a password has not been associated with the account." }, { "code": null, "e": 20615, "s": 20563, "text": "Following are the steps to enable the user account." }, { "code": null, "e": 20705, "s": 20615, "text": "Step 1 − Click the Account disabled option. This will prompt for the password dialog box." }, { "code": null, "e": 20860, "s": 20705, "text": "We have the option to either set a password, log in without a password, or enable the account. A good practice is to always set a password for an account." }, { "code": null, "e": 20918, "s": 20860, "text": "Step 2 − To set the password and click the Change button." }, { "code": null, "e": 21000, "s": 20918, "text": "Step 3 − The account will now be enabled. Log in using the newly created account." }, { "code": null, "e": 21147, "s": 21000, "text": "To manage user permissions and groups, an additional package needs to be installed. Following are the steps to manage user permissions and groups." }, { "code": null, "e": 21210, "s": 21147, "text": "Step 1 − Go to the search option and type the command keyword." }, { "code": null, "e": 21295, "s": 21210, "text": "Step 2 − The search result of Terminal appears. Click it to open the command prompt." }, { "code": null, "e": 21339, "s": 21295, "text": "Step 3 − Next, issue the following command." }, { "code": null, "e": 21380, "s": 21339, "text": "sudo apt-get install gnome-system-tools\n" }, { "code": null, "e": 21612, "s": 21380, "text": "The apt-get command line is used to install additional packages from the Internet for the Ubuntu system. Here, we are telling Ubuntu that we want to install additional system tools so that we can manage user permissions and groups." }, { "code": null, "e": 21806, "s": 21612, "text": "Step 4 − We will then be prompted for the password of the current logged in account and to also confirm to download the necessary packages for the installation. Enter the ‘Y’ option to proceed." }, { "code": null, "e": 21960, "s": 21806, "text": "Step 5 − Once the installation is complete, when we search for users in the search option in Ubuntu, we can see an additional option of Users and Groups." }, { "code": null, "e": 22064, "s": 21960, "text": "Step 6 − Click the Users and Groups option. Now, there will be an additional option of user and groups." }, { "code": null, "e": 22252, "s": 22064, "text": "Step 7 − Click the Advanced settings button. We will be prompted to enter the password of the current logged on user to authenticate. Enter the password and click the Authenticate button." }, { "code": null, "e": 22372, "s": 22252, "text": "Step 8 − In the next dialog box which appears, we will then be able to assign the required user privileges to the user." }, { "code": null, "e": 22484, "s": 22372, "text": "Step 9 − Now, if we click on the Groups option, we will see that it has the option to create and delete groups." }, { "code": null, "e": 22534, "s": 22484, "text": "Step 10 − Click on the Add button to add a group." }, { "code": null, "e": 22630, "s": 22534, "text": "Step 11 − In the next dialog box, we can provide a group name and assign members to that group." }, { "code": null, "e": 22690, "s": 22630, "text": "Step 12 − Finally, click the OK button to create the group." }, { "code": null, "e": 22845, "s": 22690, "text": "To open the file like explorer in Ubuntu, click the Files option in the software launcher. In the following screenshot the Files icon is encircled in red." }, { "code": null, "e": 22940, "s": 22845, "text": "On clicking the icon, the following screen which is the File like explorer in Ubuntu opens up." }, { "code": null, "e": 23025, "s": 22940, "text": "Step 1 − To create a folder, choose a location where the folder needs to be created." }, { "code": null, "e": 23088, "s": 23025, "text": "Step 2 − Then right-click and choose the option of New Folder." }, { "code": null, "e": 23140, "s": 23088, "text": "Step 3 − Provide a name for the folder accordingly." }, { "code": null, "e": 23219, "s": 23140, "text": "Step 1 − To rename a folder, right-click the folder which needs to be renamed." }, { "code": null, "e": 23292, "s": 23219, "text": "Step 2 − Right-click and choose the rename option from the context menu." }, { "code": null, "e": 23349, "s": 23292, "text": "Step 3 − Provide the new name of the folder accordingly." }, { "code": null, "e": 23441, "s": 23349, "text": "Note − There are other options such as move or copy the folder or move the folder to trash." }, { "code": null, "e": 23551, "s": 23441, "text": "To see the properties of a file, right-click the file and choose the Properties option from the context menu." }, { "code": null, "e": 23697, "s": 23551, "text": "Using the option, we can view the properties of the file and modify the permissions of the file accordingly as shown in the following screenshot." }, { "code": null, "e": 23781, "s": 23697, "text": "The Word Writer comes in-built in Ubuntu and is available in the Software launcher." }, { "code": null, "e": 23886, "s": 23781, "text": "The icon is encircled in red in the above screenshot. Once we click on the icon, the writer will launch." }, { "code": null, "e": 23963, "s": 23886, "text": "We can start typing in the Writer as we normally would do in Microsoft Word." }, { "code": null, "e": 24056, "s": 23963, "text": "To save a document, just click on the save menu option as shown in the following screenshot." }, { "code": null, "e": 24131, "s": 24056, "text": "Specify the location, the name of the file and then click the Save button." }, { "code": null, "e": 24279, "s": 24131, "text": "To create a new document, choose the new menu option as shown in the following screenshot. It shows an option to create various types of documents." }, { "code": null, "e": 24461, "s": 24279, "text": "To open an existing document, choose the option of opening an existing document from the file menu options as shown in the following screenshot. The option icon is encircled in red." }, { "code": null, "e": 24631, "s": 24461, "text": "Once the open menu option is clicked, it presents a dialog box with an option to choose the file which needs to be opened. Click on the desired file and then click Open." }, { "code": null, "e": 24722, "s": 24631, "text": "Tables can be inserted using the Insert table option as shown in the following screenshot." }, { "code": null, "e": 24814, "s": 24722, "text": "Once the table has been added, we can then work on the table as we would on Microsoft Word." }, { "code": null, "e": 24941, "s": 24814, "text": "To add additional rows and columns work to the table, right-click on the table and choose the various table options available." }, { "code": null, "e": 25049, "s": 24941, "text": "You can also work with the format of the text using the various font options in the toolbar of Word Writer." }, { "code": null, "e": 25165, "s": 25049, "text": "The default application for spreadsheets in Ubuntu is called Calc. This is also available in the software launcher." }, { "code": null, "e": 25233, "s": 25165, "text": "Once we click on the icon, the spreadsheet application will launch." }, { "code": null, "e": 25313, "s": 25233, "text": "We can edit the cells as we would normally do in a Microsoft Excel application." }, { "code": null, "e": 25514, "s": 25313, "text": "Formulas can be added in the same manner as in Microsoft Excel. The following example shows an excel sheet which has 3 columns. The 3rd column is the multiplication of the Units and Unit price column." }, { "code": null, "e": 25594, "s": 25514, "text": "The columns can be dragged to ensure the same formula is repeated for each row." }, { "code": null, "e": 25679, "s": 25594, "text": "To save a sheet, go to the Save As menu option as shown in the following screenshot." }, { "code": null, "e": 25770, "s": 25679, "text": "Provide the name, location of the spreadsheet and click the Save button to save the sheet." }, { "code": null, "e": 25900, "s": 25770, "text": "There are various other formatting options available in the toolbar in the Calc application as shown in the following screenshot." }, { "code": null, "e": 26034, "s": 25900, "text": "On the right-hand side of the Calc application, there are various other options. One of them is to insert a chart in the spreadsheet." }, { "code": null, "e": 26168, "s": 26034, "text": "Once we click the Chart option, it will prompt for the type of Chart to be inserted. Choose a chart type and click the Finish button." }, { "code": null, "e": 26214, "s": 26168, "text": "Now, we can see the Chart in the spreadsheet." }, { "code": null, "e": 26431, "s": 26214, "text": "LibreOffice is a suite of office products available in Ubuntu. It is similar to the Microsoft suite of products although there are some features of Microsoft Office that does not work with LibreOffice and vice versa." }, { "code": null, "e": 26758, "s": 26431, "text": "LibreOffice was first introduced in the year 1985 by a company called StarOffice. In the year 2002, the suite was taken by OpenOffice.org with Sun Microsystems being a major contributor to the product. From the year 2010 onwards, a separate branch of the source code of the product was taken which is now known as LibreOffice." }, { "code": null, "e": 26929, "s": 26758, "text": "We will look at the LibreOffice writer and Calc in subsequent chapters. In this chapter, we will look at LibreOffice Impress which is the PowerPoint version of Microsoft." }, { "code": null, "e": 27019, "s": 26929, "text": "The LibreOffice suite comes in-built in Ubuntu and is available in the Software launcher." }, { "code": null, "e": 27186, "s": 27019, "text": "The icon of LibreOffice is encircled in red in the above screenshot. Once we click on the icon, the Impress Software will launch and the following screen will pop up." }, { "code": null, "e": 27303, "s": 27186, "text": "The interface looks quite similar to Microsoft PowerPoint. We can then modify the content on the slides as required." }, { "code": null, "e": 27459, "s": 27303, "text": "Adding slides to Impress is pretty similar to Microsoft PowerPoint. There are multiple ways of adding slides. One way is to use the Duplicate Slide option." }, { "code": null, "e": 27606, "s": 27459, "text": "We can decide on the slide layout of the new slide by choosing the layout from the layout panel that appears on the right-hand side of the screen." }, { "code": null, "e": 27666, "s": 27606, "text": "To save the presentation, choose the ‘Save As’ menu option." }, { "code": null, "e": 27736, "s": 27666, "text": "Provide the name and location of the slide and click the Save button." }, { "code": null, "e": 27798, "s": 27736, "text": "To open an existing presentation, click the Open menu option." }, { "code": null, "e": 27888, "s": 27798, "text": "Choose the location and name of the file. Click the Open button to open the presentation." }, { "code": null, "e": 28088, "s": 27888, "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": 28189, "s": 28088, "text": "To invoke the command line, go to the search option and enter the command keyword in the search box." }, { "code": null, "e": 28312, "s": 28189, "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": 28426, "s": 28312, "text": "The easiest command to start with, is the directory listing command which is used to list the directory contents." }, { "code": null, "e": 28452, "s": 28426, "text": "ls –option directoryname\n" }, { "code": null, "e": 28520, "s": 28452, "text": "Option − These are the options to be specified with the ls command." }, { "code": null, "e": 28588, "s": 28520, "text": "Option − These are the options to be specified with the ls command." }, { "code": null, "e": 28689, "s": 28588, "text": "Directoryname − This is the optional directory name that can be specified along with the ls command." }, { "code": null, "e": 28790, "s": 28689, "text": "Directoryname − This is the optional directory name that can be specified along with the ls command." }, { "code": null, "e": 28848, "s": 28790, "text": "The output will be the listing of the directory contents." }, { "code": null, "e": 28935, "s": 28848, "text": "In the following example, we just issue the ls command to list the directory contents." }, { "code": null, "e": 29011, "s": 28935, "text": "The directory listing of the current directory will be shown as the output." }, { "code": null, "e": 29178, "s": 29011, "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": 29229, "s": 29178, "text": "To clear the screen, we can use the clear command." }, { "code": null, "e": 29236, "s": 29229, "text": "clear\n" }, { "code": null, "e": 29241, "s": 29236, "text": "None" }, { "code": null, "e": 29282, "s": 29241, "text": "The command line screen will be cleared." }, { "code": null, "e": 29350, "s": 29282, "text": "To get more information on a command, we can use the ‘man’ command." }, { "code": null, "e": 29367, "s": 29350, "text": "man commandname\n" }, { "code": null, "e": 29453, "s": 29367, "text": "Commandname − This is the name of the command for which more information is required." }, { "code": null, "e": 29503, "s": 29453, "text": "The information on the command will be displayed." }, { "code": null, "e": 29672, "s": 29503, "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": 29719, "s": 29672, "text": "We can use the find command to find for files." }, { "code": null, "e": 29737, "s": 29719, "text": "find filepattern\n" }, { "code": null, "e": 29795, "s": 29737, "text": "Filepattern − This is the pattern used to find for files." }, { "code": null, "e": 29850, "s": 29795, "text": "The files based on the file pattern will be displayed." }, { "code": null, "e": 29904, "s": 29850, "text": "In this example, we will issue the following command." }, { "code": null, "e": 29919, "s": 29904, "text": "find Sample.*\n" }, { "code": null, "e": 29992, "s": 29919, "text": "This command will list all the files which start with the word ‘Sample’." }, { "code": null, "e": 30059, "s": 29992, "text": "This command is used to display who is the current logged on user." }, { "code": null, "e": 30067, "s": 30059, "text": "whoami\n" }, { "code": null, "e": 30072, "s": 30067, "text": "None" }, { "code": null, "e": 30130, "s": 30072, "text": "The name of the current logged on user will be displayed." }, { "code": null, "e": 30184, "s": 30130, "text": "In this example, we will issue the following command." }, { "code": null, "e": 30192, "s": 30184, "text": "whoami\n" }, { "code": null, "e": 30249, "s": 30192, "text": "This command will display the current working directory." }, { "code": null, "e": 30254, "s": 30249, "text": "pwd\n" }, { "code": null, "e": 30259, "s": 30254, "text": "None" }, { "code": null, "e": 30308, "s": 30259, "text": "The current working directory will be displayed." }, { "code": null, "e": 30362, "s": 30308, "text": "In this example, we will issue the following command." }, { "code": null, "e": 30367, "s": 30362, "text": "Pwd\n" }, { "code": null, "e": 30719, "s": 30367, "text": "Since we have the ability to work with the command line which we covered in the previous chapter, it is common to create scripts which can perform simple jobs. Scripting is normally used to automate administrative tasks. Let’s create a simple script using the following steps. The script will be used to display the IP address assigned to the machine." }, { "code": null, "e": 30901, "s": 30719, "text": "Step 1 − Open the editor. Just like notepad in Windows, Ubuntu has a text editor. In the search dialog box, enter the keyword of editor. Then double-click on the Text Editor option." }, { "code": null, "e": 30938, "s": 30901, "text": "The following editor screen pops up." }, { "code": null, "e": 30987, "s": 30938, "text": "Step 2 − Enter the following text in the editor." }, { "code": null, "e": 31107, "s": 30987, "text": "originalAddress=@(ifconfig | grep “inet addr” | head –n 1 | cut –d “:” –f 2 | cut –d “ “ –f 1)\n \necho $originalAddress\n" }, { "code": null, "e": 31146, "s": 31107, "text": "Step 3 − Save the file as write-ip.sh." }, { "code": null, "e": 31280, "s": 31146, "text": "Now once you have saved the file, we need to assign the file some execute rights. Otherwise, we will not be able to execute the file." }, { "code": null, "e": 31381, "s": 31280, "text": "Step 4 − Go to the command prompt, navigate to the Desktop location and issue the following command." }, { "code": null, "e": 31405, "s": 31381, "text": "chmod a+x write-ip.sh \n" }, { "code": null, "e": 31469, "s": 31405, "text": "The above command will provide execute permissions to the file." }, { "code": null, "e": 31541, "s": 31469, "text": "Step 5 − Now, we can execute the file by issuing the following command." }, { "code": null, "e": 31556, "s": 31541, "text": "./write-ip.sh\n" }, { "code": null, "e": 31652, "s": 31556, "text": "The output will be the IP address assigned to the machine as shown in the following screenshot." }, { "code": null, "e": 31796, "s": 31652, "text": "Ubuntu provides the options to view the network details of the workstation. Following are the steps to view the network details of the machine." }, { "code": null, "e": 31859, "s": 31796, "text": "Step 1 − In the search dialog box, type the keyword ‘network’." }, { "code": null, "e": 31948, "s": 31859, "text": "Step 2 − Double-click the Network icon. We can see the hostname assigned to the machine." }, { "code": null, "e": 32044, "s": 31948, "text": "Step 3 − Click the Network folder option and we can see the IP address assigned to the machine." }, { "code": null, "e": 32135, "s": 32044, "text": "Step 4 − Click the Options button and we can modify the details of the network connection." }, { "code": null, "e": 32359, "s": 32135, "text": "Ubuntu also comes in a server version. This version is used for hosting applications such as webbased applications. The server version can be downloaded from the Ubuntu site in the same way as the desktop version of Ubuntu." }, { "code": null, "e": 32548, "s": 32359, "text": "For the purpose of this tutorial, let’s look at the installation of the server version 14.04, which is one of the most popular versions of Ubuntu. Following are the steps for installation." }, { "code": null, "e": 32639, "s": 32548, "text": "Step 1 − Download for the server version from the link − http://releases.ubuntu.com/14.04/" }, { "code": null, "e": 32785, "s": 32639, "text": "Step 2 − Once the download of the server version is complete, put it on a USB device or bootable DVD. Boot the hardware from the bootable device." }, { "code": null, "e": 32899, "s": 32785, "text": "Step 3 − The system prompts to select a language for the Installation. Select English and press the Enter button." }, { "code": null, "e": 32997, "s": 32899, "text": "Step 4 − In the next step, choose the option to install Ubuntu server and press the Enter button." }, { "code": null, "e": 33130, "s": 32997, "text": "Step 5 − The system again prompts to select a language for the installation. Choose the English language and press the Enter button." }, { "code": null, "e": 33218, "s": 33130, "text": "Step 6 − In the next screen, select the desired region and then press the Enter button." }, { "code": null, "e": 33339, "s": 33218, "text": "Step 7 − The next step includes the detection of the Keyboard layout. Choose the ‘No’ option and press the Enter button." }, { "code": null, "e": 33441, "s": 33339, "text": "Step 8 − In the next screen, click the English(US) as the keyboard layout and press the Enter button." }, { "code": null, "e": 33601, "s": 33441, "text": "Step 9 − After performing a set of initial configuration steps, we will be prompted to enter a name for the system. Enter Ubuntuserver and press the Enter key." }, { "code": null, "e": 33760, "s": 33601, "text": "Step 10 − You will then be prompted to enter a real name and the username for an account to be created. Enter the name ‘demo’ and press Enter on both screens." }, { "code": null, "e": 33912, "s": 33760, "text": "Step 11 − Now we need to enter a password for the new account. Enter a password and press the Enter button. The system will ask to verify the password." }, { "code": null, "e": 34167, "s": 33912, "text": "Step 12 − The system then asks if we want to encrypt the home directory. For the moment, let us say ‘No’ and press Enter to proceed. The encryption is such that if anyone does hack into the system, they will not be able steal the data as it is encrypted." }, { "code": null, "e": 34294, "s": 34167, "text": "Once we are an advanced user of Ubuntu server, we can choose ‘Yes’ as the option. But for now let’s leave this as unencrypted." }, { "code": null, "e": 34420, "s": 34294, "text": "Step 13 − The Ubuntu server installation will then set the time settings. Choose ‘Yes’ and press the Enter button to proceed." }, { "code": null, "e": 34566, "s": 34420, "text": "Step 14 − Next the disk setup will take place. Choose the option ‘Guided – use entire disk and set up LVM’ and press the Enter button to proceed." }, { "code": null, "e": 34723, "s": 34566, "text": "Step 15 − The installation will erase all the data on the disk. Since this is a fresh installation, this is not an issue. Click the Enter button to proceed." }, { "code": null, "e": 34853, "s": 34723, "text": "Step 16 − We will be asked to confirm all the changes to the disk. Choose the ‘Yes’ option and Press the Enter button to proceed." }, { "code": null, "e": 34952, "s": 34853, "text": "Step 17 − The installation will detect the size of the hard disk. Hit the Enter button to proceed." }, { "code": null, "e": 35085, "s": 34952, "text": "Step 18 − The system then asks to finalize the changes to the disk. Choose the ‘Yes’ option and press the ‘Enter’ button to proceed." }, { "code": null, "e": 35163, "s": 35085, "text": "The system will then start performing a series of steps for the installation." }, { "code": null, "e": 35282, "s": 35163, "text": "Step 19 − It will then ask to configure the Proxy setting. We can leave this setting as is and press the Enter button." }, { "code": null, "e": 35352, "s": 35282, "text": "The installation will then start configuring the apt package manager." }, { "code": null, "e": 35412, "s": 35352, "text": "The installation of the necessary software will then start." }, { "code": null, "e": 35553, "s": 35412, "text": "Step 20 − The system then asks if we want to configure automatic updates. For now, select ‘No automatic updates’ and press the Enter button." }, { "code": null, "e": 35727, "s": 35553, "text": "Step 21 − The next step is to install any additional software. Select ‘OpenSSH’ server which allows one to remotely connect to the server. Press the Enter button to proceed." }, { "code": null, "e": 35798, "s": 35727, "text": "The system will start installing the remaining software on the system." }, { "code": null, "e": 35928, "s": 35798, "text": "Step 22 − The system now requests to install the GRUB boot loader. Choose the ‘Yes’ option and press the Enter button to proceed." }, { "code": null, "e": 36011, "s": 35928, "text": "Step 23 − Once the installation is complete, press the Continue option to proceed." }, { "code": null, "e": 36063, "s": 36011, "text": "The system will then reboot after the installation." }, { "code": null, "e": 36193, "s": 36063, "text": "Step 24 − We will then be requested to log into the system. Enter the credentials which were entered at the time of installation." }, { "code": null, "e": 36236, "s": 36193, "text": "We will finally be logged into the system." }, { "code": null, "e": 36297, "s": 36236, "text": "We have successfully installed the server version of Ubuntu." }, { "code": null, "e": 36536, "s": 36297, "text": "The Secure Shell (SSH) in Linux is used to log into the machine in an encrypted and safe manner. This helps in providing a secure channel to streamline all requests to the Ubuntu server. SSH uses cryptographic keys to log into the server." }, { "code": null, "e": 36702, "s": 36536, "text": "On Windows, the most common tool to perform a secure shell to a Linux server is putty. In this chapter, we will learn how to use putty to Secure Shell into a server." }, { "code": null, "e": 36763, "s": 36702, "text": "Step 1 − Download putty from the http://www.putty.org/ site." }, { "code": null, "e": 36923, "s": 36763, "text": "Step 2 − Before connecting to use putty, we need to know the IP address of our Ubuntu box. To do this, type ifconfig in the command shell of the Ubuntu server." }, { "code": null, "e": 37008, "s": 36923, "text": "From the above screenshot, we know that the IP address of the server is 192.168.0.20" }, { "code": null, "e": 37199, "s": 37008, "text": "Step 3 − Next step is installing SSH on the server. In order to SSH to a server, you need to make sure it is installed. Run the following command in the Ubuntu server command prompt session." }, { "code": null, "e": 37236, "s": 37199, "text": "sudo apt-get install openssh-server\n" }, { "code": null, "e": 37328, "s": 37236, "text": "Step 4 − Launch PuTTY. Enter the IP address of the Ubuntu server and click the Open button." }, { "code": null, "e": 37412, "s": 37328, "text": "Step 5 − The next screen requests to accept the encrypted key sent from the server." }, { "code": null, "e": 37549, "s": 37412, "text": "Step 6 − Finally, enter the username and password to log into the server. We have successfully established a secure shell to the server." }, { "code": null, "e": 37790, "s": 37549, "text": "The Ubuntu desktop edition can be used to develop web applications. One of the most famous software which can be used for development on Ubuntu is Aptana. Let’s see the steps on how to get Aptana and get a simple web project up and running." }, { "code": null, "e": 37899, "s": 37790, "text": "Step 1 − On Ubuntu desktop, open Firefox and go to the url − http://www.aptana.com/products/studio3/download" }, { "code": null, "e": 37951, "s": 37899, "text": "Step 2 − Click the Download Aptana Studio 3 button." }, { "code": null, "e": 38068, "s": 37951, "text": "Step 3 − Once downloaded, extract the zip file to a suitable location. Once extracted, click the AptanaStudio3 link." }, { "code": null, "e": 38162, "s": 38068, "text": "The following interface pops up. We can then choose to create a new web project, if required." }, { "code": null, "e": 38226, "s": 38162, "text": "The required development can be carried out on the web project." }, { "code": null, "e": 38498, "s": 38226, "text": "Nginx is a much lighter web server than Apache. This web server has become quite popular in the recent years. The Apache web server can be quite complex to configure and use. However, Nginx is much simpler. This chapter will focus on how to install this light web server." }, { "code": null, "e": 38542, "s": 38498, "text": "To install Nginx, following are the steps −" }, { "code": null, "e": 38626, "s": 38542, "text": "Step 1 − Open the command terminal on Ubuntu desktop and run the following command." }, { "code": null, "e": 38649, "s": 38626, "text": "sudo apt-get update \n" }, { "code": null, "e": 38726, "s": 38649, "text": "This first ensures that all packages on the operating system are up to date." }, { "code": null, "e": 38797, "s": 38726, "text": "Step 2 − Next enter the following command to install the nginx server." }, { "code": null, "e": 38825, "s": 38797, "text": "sudo apt-get install nginx\n" }, { "code": null, "e": 38938, "s": 38825, "text": "Step 3 − Once done, if we run ps –ef | grep nginx, we can see the process for the web server in a running state." }, { "code": null, "e": 38987, "s": 38938, "text": "We now have nginx run as a web server on Ubuntu." }, { "code": null, "e": 39095, "s": 38987, "text": "Ubuntu can also be installed as virtual machines. Some of the software which support virtual machines are −" }, { "code": null, "e": 39113, "s": 39095, "text": "Microsoft Hyper-V" }, { "code": null, "e": 39132, "s": 39113, "text": "VMWare Workstation" }, { "code": null, "e": 39150, "s": 39132, "text": "Oracle VirtualBox" }, { "code": null, "e": 39324, "s": 39150, "text": "Let’s use Oracle VirtualBox to create our Ubuntu virtual machine. Oracle VirtualBox is a free tool from Oracle. Following are the steps to have the virtual machine in place." }, { "code": null, "e": 39411, "s": 39324, "text": "Step 1 − Download Oracle VirtualBox from the oracle site − https://www.virtualbox.org/" }, { "code": null, "e": 39482, "s": 39411, "text": "Step 2 − Go to the downloads section and download the Windows version." }, { "code": null, "e": 39606, "s": 39482, "text": "Step 3 − Once download is complete, install VirtualBox. Launch the installer. Click the Run button on the following screen." }, { "code": null, "e": 39663, "s": 39606, "text": "Step 4 − Click the Next button on the subsequent screen." }, { "code": null, "e": 39738, "s": 39663, "text": "Step 5 − Choose the appropriate folder location and click the Next button." }, { "code": null, "e": 39784, "s": 39738, "text": "Step 6 − Click Next on the subsequent screen." }, { "code": null, "e": 39875, "s": 39784, "text": "Step 7 − Click the ‘Yes’ button on the next screen to proceed ahead with the installation." }, { "code": null, "e": 39918, "s": 39875, "text": "Step 8 − Click Install on the next screen." }, { "code": null, "e": 40040, "s": 39918, "text": "Step 9 − After the installation is complete, launch Oracle VirtualBox. On the Launch screen, click the ‘New’ menu option." }, { "code": null, "e": 40146, "s": 40040, "text": "Step 10 − Give a name for the virtual machine and give the type as Ubuntu and then click the Next button." }, { "code": null, "e": 40237, "s": 40146, "text": "Step 11 − In the next screen, keep the recommended RAM as it is and click the Next button." }, { "code": null, "e": 40329, "s": 40237, "text": "Step 12 − Accept the default setting for the virtual hard disk and click the Create button." }, { "code": null, "e": 40392, "s": 40329, "text": "Step 13 − Accept the hard disk type and click the Next button." }, { "code": null, "e": 40486, "s": 40392, "text": "Step 14 − Accept the default type of physical hard disk allocation and click the Next button." }, { "code": null, "e": 40558, "s": 40486, "text": "Step 15 − Accept the default file location and click the Create button." }, { "code": null, "e": 40647, "s": 40558, "text": "Step 16 − Now that the Virtual Machine has been created, click the Settings Menu option." }, { "code": null, "e": 40772, "s": 40647, "text": "Step 17 − Go to the Storage option, click the Empty disk icon and browse for the Ubuntu iso image. Then click the OK button." }, { "code": null, "e": 40938, "s": 40772, "text": "Finally click the Start button. The system prompts to install Ubuntu. Follow the steps in the Installation chapter and we will have a Virtual Machine hosting Ubuntu." }, { "code": null, "e": 41138, "s": 40938, "text": "MySQL and Python are famous database and development software respectively. These are normally installed on Linux-based systems. Let’s see how we can get them installed on Ubuntu server environments." }, { "code": null, "e": 41278, "s": 41138, "text": "The first thing to do is to find out what is the version of Python installed on the system. We can find this issuing the following command." }, { "code": null, "e": 41289, "s": 41278, "text": "Python –v\n" }, { "code": null, "e": 41444, "s": 41289, "text": "Where the –v option specifies to show what is the version of Python installed. The following screenshot shows a sample of the output of the above command." }, { "code": null, "e": 41531, "s": 41444, "text": "From the above output, we can see that the version of Python installed is version 2.7." }, { "code": null, "e": 41610, "s": 41531, "text": "There is another way to see if Python is installed via the following commands." }, { "code": null, "e": 41621, "s": 41610, "text": "Python –V\n" }, { "code": null, "e": 41633, "s": 41621, "text": "Python3 –V\n" }, { "code": null, "e": 41701, "s": 41633, "text": "The later command is used to see the version 3 of Python installed." }, { "code": null, "e": 41807, "s": 41701, "text": "If we want to have the latest version of Python installed, then we need to issue the following statement." }, { "code": null, "e": 41837, "s": 41807, "text": "sudo apt-get install python3\n" }, { "code": null, "e": 41926, "s": 41837, "text": "The above command will download the necessary packages for Python and have it installed." }, { "code": null, "e": 41985, "s": 41926, "text": "To install MySQL, the following steps need to be followed." }, { "code": null, "e": 42076, "s": 41985, "text": "Step 1 − Issue the apt-get command to ensure all operating system packages are up to date." }, { "code": null, "e": 42099, "s": 42076, "text": "sudo apt-get update \n" }, { "code": null, "e": 42191, "s": 42099, "text": "Step 2 − Once all the packages have been updated, it is time to get the packages for MySQL." }, { "code": null, "e": 42226, "s": 42191, "text": "sudo apt-get install mysql-server\n" }, { "code": null, "e": 42308, "s": 42226, "text": "The above command will start the download of all the relevant packages for MySQL." }, { "code": null, "e": 42424, "s": 42308, "text": "Once the download completes and the installation starts, the installer will first ask to configure a root password." }, { "code": null, "e": 42532, "s": 42424, "text": "Step 3 − Enter the required password and click the OK button. It will also prompt to re-enter the password." }, { "code": null, "e": 42602, "s": 42532, "text": "Step 4 − To see the MySQL process running, run the following command." }, { "code": null, "e": 42623, "s": 42602, "text": "ps –ef | grep mysql\n" }, { "code": null, "e": 42726, "s": 42623, "text": "The following screenshot shows mysqld which is the daemon process for mysql running in the background." }, { "code": null, "e": 42782, "s": 42726, "text": "Step 5 − To configure mysql, run the following command." }, { "code": null, "e": 42818, "s": 42782, "text": "/usr/bin/mysql_secure_installation\n" }, { "code": null, "e": 42907, "s": 42818, "text": "It prompts to enter the root password which was entered during the installation process." }, { "code": null, "e": 42950, "s": 42907, "text": "Step 6 − Enter the password and hit Enter." }, { "code": null, "e": 43014, "s": 42950, "text": "Now, it prompts on whether we want to change the root password." }, { "code": null, "e": 43053, "s": 43014, "text": "Step 7 − Enter ‘N’ for No and proceed." }, { "code": null, "e": 43122, "s": 43053, "text": "Again, it prompts on whether we want to remove the Anonymous access." }, { "code": null, "e": 43293, "s": 43122, "text": "Step 8 − When connecting from other machines on this database, it is advised to keep the default options as ‘N’ for both anonymous users and disallow root login remotely." }, { "code": null, "e": 43442, "s": 43293, "text": "Step 9 − It is advised to provide the option as No for the options of Remove test database as well. We can enter ‘Y’ to reload the privileges table." }, { "code": null, "e": 43496, "s": 43442, "text": "Finally, the configuration of MySQL will be complete." }, { "code": null, "e": 43653, "s": 43496, "text": "Node.js is a popular JavaScript framework used for developing server side applications. In this chapter, we will see how to get Node.js installed on Ubuntu." }, { "code": null, "e": 43703, "s": 43653, "text": "Following are the steps to get Node.js installed." }, { "code": null, "e": 43739, "s": 43703, "text": "Step 1 − Run the following command." }, { "code": null, "e": 43768, "s": 43739, "text": "sudo apt-get install nodejs\n" }, { "code": null, "e": 43825, "s": 43768, "text": "This will install all the necessary packages for Node.js" }, { "code": null, "e": 43919, "s": 43825, "text": "Next, we need to install the Node package manager which is required for Node.js applications." }, { "code": null, "e": 43955, "s": 43919, "text": "Step 2 − Run the following command." }, { "code": null, "e": 43981, "s": 43955, "text": "sudo apt-get install npm\n" }, { "code": null, "e": 44056, "s": 43981, "text": "All the necessary packages for the node package manager will be installed." }, { "code": null, "e": 44201, "s": 44056, "text": "Step 3 − Next, create a symbolic link to the Node.js folder. Then, run the Node –v command and npm –v to see the Node and npm version installed." }, { "code": null, "e": 44477, "s": 44201, "text": "Docker is a container service which allows one to run applications or even operating systems on a host operating system as containers. Containers are a new and exciting technology that has evolved over the last couple of years and being adopted by a lot of key organizations." }, { "code": null, "e": 44613, "s": 44477, "text": "Docker is a company that develops these special containers for applications. The official website for Docker is https://www.docker.com/" }, { "code": null, "e": 44846, "s": 44613, "text": "As an exercise, let’s install a CentOS container on an Ubuntu system. CentOS is a Linux-based operating system from Red Hat. Thus, we will be running the CentOS system on top of Ubuntu. Following are the steps to have this in place." }, { "code": null, "e": 45023, "s": 44846, "text": "Step 1 − The first step is to install the Docker application on Ubuntu server. Thus on the Ubuntu test server, run the following command to ensure that OS updates are in place." }, { "code": null, "e": 45057, "s": 45023, "text": "sudo apt-get update \n" }, { "code": null, "e": 45157, "s": 45057, "text": "Step 2 − Once all updates have been processed, issue the following command to get Docker installed." }, { "code": null, "e": 45192, "s": 45157, "text": "sudo apt-get install -y docker.io\n" }, { "code": null, "e": 45404, "s": 45192, "text": "Step 3 − Once the Docker packages are installed, we should receive an output message stating that the Docker process has started and is running. The Docker process is known as the Docker engine or Docker daemon." }, { "code": null, "e": 45483, "s": 45404, "text": "Step 4 − To view the version of Docker running, issue the Docker info command." }, { "code": null, "e": 45548, "s": 45483, "text": "Step 5 − The next step is to install our CentOS image on Ubuntu." }, { "code": null, "e": 45697, "s": 45548, "text": "Docker has a special site called the Docker hub, which is used to store pre-built images for Docker. The link to the site is https://hub.docker.com/" }, { "code": null, "e": 45817, "s": 45697, "text": "Step 6 − Do a quick and simple sign-in process to be able to log into the site and see all the available Docker images." }, { "code": null, "e": 45907, "s": 45817, "text": "Step 7 − Once logged in, click the Explore button to see all the available Docker images." }, { "code": null, "e": 45946, "s": 45907, "text": "The two important points to note are −" }, { "code": null, "e": 46033, "s": 45946, "text": "The Docker pull command. This is the command to install the Docker image on Linux box." }, { "code": null, "e": 46120, "s": 46033, "text": "The Docker pull command. This is the command to install the Docker image on Linux box." }, { "code": null, "e": 46175, "s": 46120, "text": "The Docker details for the various versions of CentOS." }, { "code": null, "e": 46230, "s": 46175, "text": "The Docker details for the various versions of CentOS." }, { "code": null, "e": 46271, "s": 46230, "text": "Step 8 − On Ubuntu box, run the command." }, { "code": null, "e": 46303, "s": 46271, "text": "sudo docker pull centos:latest\n" }, { "code": null, "e": 46492, "s": 46303, "text": "The download of the Docker component starts and the CentOS Docker is downloaded. The name of the Docker image is centos:latest, which means that we have the latest Docker image for CentOS." }, { "code": null, "e": 46559, "s": 46492, "text": "Step 9 − To see all the Docker images installed, issue the command" }, { "code": null, "e": 46579, "s": 46559, "text": "sudo docker images\n" }, { "code": null, "e": 46737, "s": 46579, "text": "In the following screenshot, we can see that the Docker image is just 196.8 MB in size, and this is the subset of the CentOS which now runs on Ubuntu system." }, { "code": null, "e": 46875, "s": 46737, "text": "Step 10 − To start CentOS, we need to issue a command to the OS to get a thread started. We can do this by running the following command." }, { "code": null, "e": 46913, "s": 46875, "text": "sudo docker run -it centos /bin/bash\n" }, { "code": null, "e": 46959, "s": 46913, "text": "The above command does the following things −" }, { "code": null, "e": 46989, "s": 46959, "text": "Runs the CentOS Docker image." }, { "code": null, "e": 47019, "s": 46989, "text": "Runs the CentOS Docker image." }, { "code": null, "e": 47079, "s": 47019, "text": "Runs the image in interactive mode by using the -it option." }, { "code": null, "e": 47139, "s": 47079, "text": "Runs the image in interactive mode by using the -it option." }, { "code": null, "e": 47190, "s": 47139, "text": "Runs the /bin/bash command as the initial process." }, { "code": null, "e": 47241, "s": 47190, "text": "Runs the /bin/bash command as the initial process." }, { "code": null, "e": 47497, "s": 47241, "text": "We can also install Ubuntu on various cloud environments such as Google Cloud, Amazon web services, and Azure web services. In this chapter, we will see how to get Ubuntu up and running on Amazon web services. Following are the steps to get this in place." }, { "code": null, "e": 47645, "s": 47497, "text": "Step 1 − One can get a free account with Amazon web services. All we need to do is register with AWS on the following url − https://aws.amazon.com/" }, { "code": null, "e": 47729, "s": 47645, "text": "Step 2 − Click the Sign in to the Console and it presents the following dialog box." }, { "code": null, "e": 47982, "s": 47729, "text": "Step 3 − Click the option ‘I am a new user’ and enter the required email id of an existing Gmail account. Then click the ‘Sign in using our secure server’ button. We will then need to give some information in the subsequent screen to create an account." }, { "code": null, "e": 48156, "s": 47982, "text": "Step 4 − Once an account has been created, we can log into the console. Once logged in, click the EC2 option. This option is used for creating virtual machines on the cloud." }, { "code": null, "e": 48228, "s": 48156, "text": "Step 5 − In the following screenshot, click the Launch Instance button." }, { "code": null, "e": 48422, "s": 48228, "text": "Step 6 − The next screen prompts to select an appropriate AMI. An AMI is a pre-built image for an operating system in Amazon. Scroll down until to the Ubuntu option and click the Select button." }, { "code": null, "e": 48599, "s": 48422, "text": "Step 7 − In the next screen, choose the configuration of the machine. Choose the General purpose – t2.micro option and then click the ‘Next: Configure Instance Details’ button." }, { "code": null, "e": 48684, "s": 48599, "text": "Step 8 − In the next screen, enter the following details as shown in the screenshot." }, { "code": null, "e": 48743, "s": 48684, "text": "The number of instances to launch – Keep 1 as the default." }, { "code": null, "e": 48802, "s": 48743, "text": "The number of instances to launch – Keep 1 as the default." }, { "code": null, "e": 48876, "s": 48802, "text": "VPC – If there is no existing VPC, choose the option to create a new one." }, { "code": null, "e": 48950, "s": 48876, "text": "VPC – If there is no existing VPC, choose the option to create a new one." }, { "code": null, "e": 49047, "s": 48950, "text": "Now, if we choose the option to create a new subnet, we need to perform the following sub steps." }, { "code": null, "e": 49197, "s": 49047, "text": "Click the Create VPC button. (Note: The VPC is known as a virtual private network which is used to store all AWS objects in an isolated environment.)" }, { "code": null, "e": 49290, "s": 49197, "text": "In the Create VPC dialog box, enter the following details and click the ‘Yes Create’ button." }, { "code": null, "e": 49341, "s": 49290, "text": "For the subnet, keep the default setting as it is." }, { "code": null, "e": 49416, "s": 49341, "text": "For the Auto-assign Public IP option, choose ‘use subnet setting(Enable)’." }, { "code": null, "e": 49445, "s": 49416, "text": "Keep the IAM Role as ‘none’." }, { "code": null, "e": 49483, "s": 49445, "text": "Keep the Shutdown behavior as ‘none’." }, { "code": null, "e": 49532, "s": 49483, "text": "The remaining settings can remain as by default." }, { "code": null, "e": 49568, "s": 49532, "text": "Click the Next: Add Storage button." }, { "code": null, "e": 49668, "s": 49568, "text": "Step 9 − In the next screen, keep the default storage as is and click the Review and Launch button." }, { "code": null, "e": 49734, "s": 49668, "text": "Step 10 − The review screen will pop up. Click the Launch button." }, { "code": null, "e": 49913, "s": 49734, "text": "Step 11 − The next screen prompts to create a new key pair. This is required to log into the instance when it is created. Enter a key name and click the download Key pair button." }, { "code": null, "e": 49985, "s": 49913, "text": "Step 12 − Once download is complete, click the Launch Instances button." }, { "code": null, "e": 50030, "s": 49985, "text": "Step 13 − Click the ‘View Instances’ button." }, { "code": null, "e": 50109, "s": 50030, "text": "Step 14 − Once the state of the instance is running, click the Connect button." }, { "code": null, "e": 50187, "s": 50109, "text": "The next dialog box presents the steps to log into the Ubuntu server machine." }, { "code": null, "e": 50284, "s": 50187, "text": "Step 15 − Perform the steps as we would normally do, using a SSH client to log into the machine." }, { "code": null, "e": 50315, "s": 50284, "text": "\n 8 Lectures \n 31 mins\n" }, { "code": null, "e": 50331, "s": 50315, "text": " Musab Zayadneh" }, { "code": null, "e": 50366, "s": 50331, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 50374, "s": 50366, "text": " Satish" }, { "code": null, "e": 50409, "s": 50374, "text": "\n 26 Lectures \n 1.5 hours \n" }, { "code": null, "e": 50419, "s": 50409, "text": " YouAccel" }, { "code": null, "e": 50426, "s": 50419, "text": " Print" }, { "code": null, "e": 50437, "s": 50426, "text": " Add Notes" } ]
Stop Using CSVs for Storage — Pickle is an 80 Times Faster Alternative | by Dario Radečić | Towards Data Science
Storing data in the cloud can cost you a pretty penny. Naturally, you’ll want to stay away from the most widely known data storage format — CSV — and pick something a little lighter. That is, if you don’t care about viewing and editing data files on the fly. Today you’ll learn about one of the simplest ways to store almost anything in Python — Pickle. Pickling isn’t limited to datasets only, as you’ll see shortly, but every example in the article is based on datasets. In Python, you can use the pickle module to serialize objects and save them to a file. You can then deserialize the serialized file to load them back when needed. Pickle has one major advantage over other formats — you can use it to store any Python object. That’s correct, you’re not limited to data. One of the most widely used functionalities is saving machine learning models after the training is complete. That way, you don’t have to retrain the model every time you run the script. I’ve also used Pickle numerous times to store Numpy arrays. It’s a no-brainer solution for setting checkpoints of some sort in your code. Sounds like a perfect storage format? Well, hold your horses. Pickle has a couple of shortcomings you should be aware of: Cross-language support isn’t guaranteed — Pickle is Python-specific, so no one can guarantee you’ll be able to read pickled files in another programming language. Pickled files are Python-version-specific — You might encounter issues when saving files in one Python version and reading them in the other. Try to work in identical Python versions, if possible. Pickling doesn’t compress data — Pickling an object won’t compress it. Sure, the file will be smaller when compared to CSV, but you can compress the data manually for maximum efficiency. You’ll see a work-around for compressing data shortly. Let’s see how to work with Pickle in Python next. Let’s start by importing the required libraries and creating a relatively large dataset. You’ll need Numpy, Pandas, Pickle, and BZ2. You’ll use the last one for data compression: import numpy as npimport pandas as pdimport pickleimport bz2np.random.seed = 42df_size = 10_000_000df = pd.DataFrame({ 'a': np.random.rand(df_size), 'b': np.random.rand(df_size), 'c': np.random.rand(df_size), 'd': np.random.rand(df_size), 'e': np.random.rand(df_size)})df.head() Here’s how the dataset looks like: Let’s save it locally next. You can use the following command to pickle the DataFrame: with open('10M.pkl', 'wb') as f: pickle.dump(df, f) The file is saved locally now. You can read it in a similar manner — just change the mode from wb to rb with open('10M.pkl', 'rb') as f: df = pickle.load(f) Awesome! As mentioned earlier, Pickle won’t do any compression by default. You’ll have to take care of that manually. Python makes it stupidly easy with the bz2 module: with open('10M_compressed.pkl', 'wb') as f: compressed_file = bz2.BZ2File(f, 'w') pickle.dump(df, compressed_file) It’s just an additional line of code, but it can save you some disk time. The saving process will be significantly longer, but that’s a tradeoff you’ll have to live with. Reading a compressed file requires an additional line of code: with open('10M_compressed.pkl', 'rb') as f: compressed_file = bz2.BZ2File(f, 'r') df = pickle.load(compressed_file) Just make sure not to mess up the file modes, as providing wb when reading a file will delete all its contents. It would be best to write the helper functions for read and write operations, so you never mess them up. The following section covers the comparison with the CSV file format — in file size, read, and write times. Answering this question isn’t as easy as it seems. Sure, CSVs provide view and edit privileges, as anyone can open them. That could also be considered as a downside, for obvious reasons. Moreover, you can’t save machine learning models to a CSV file. Still, let’s compare the two in file size, read, and write times. The following chart shows the time needed to save the DataFrame from the last section locally: That’s around 80 times speed increase, if you don’t care about compression. Next, let’s compare the read times — how long does it take to read identical datasets in different formats: Pickle is around 11 times faster this time, when not compressed. The compression is a huge pain point when reading and saving files. But, let’s see how much disk space does it save. That’s what the following visualization answers: The file size decrease when compared to CSV is significant, but the compression doesn’t save that much disk space in this case. To recap, going from CSV to Pickle offers obvious advantages. What’s not 100% obvious is that Pickle lets you store other objects — anything built into Python, Numpy arrays, and even machine learning models. CSVs and other data-only formats don’t have that capability. What are your thoughts and experiences with Pickle? Is it your go-to format for the Python ecosystem? Let me know in the comments below. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you. medium.com Follow me on Medium for more stories like this Sign up for my newsletter Connect on LinkedIn
[ { "code": null, "e": 431, "s": 172, "text": "Storing data in the cloud can cost you a pretty penny. Naturally, you’ll want to stay away from the most widely known data storage format — CSV — and pick something a little lighter. That is, if you don’t care about viewing and editing data files on the fly." }, { "code": null, "e": 645, "s": 431, "text": "Today you’ll learn about one of the simplest ways to store almost anything in Python — Pickle. Pickling isn’t limited to datasets only, as you’ll see shortly, but every example in the article is based on datasets." }, { "code": null, "e": 808, "s": 645, "text": "In Python, you can use the pickle module to serialize objects and save them to a file. You can then deserialize the serialized file to load them back when needed." }, { "code": null, "e": 1134, "s": 808, "text": "Pickle has one major advantage over other formats — you can use it to store any Python object. That’s correct, you’re not limited to data. One of the most widely used functionalities is saving machine learning models after the training is complete. That way, you don’t have to retrain the model every time you run the script." }, { "code": null, "e": 1272, "s": 1134, "text": "I’ve also used Pickle numerous times to store Numpy arrays. It’s a no-brainer solution for setting checkpoints of some sort in your code." }, { "code": null, "e": 1394, "s": 1272, "text": "Sounds like a perfect storage format? Well, hold your horses. Pickle has a couple of shortcomings you should be aware of:" }, { "code": null, "e": 1557, "s": 1394, "text": "Cross-language support isn’t guaranteed — Pickle is Python-specific, so no one can guarantee you’ll be able to read pickled files in another programming language." }, { "code": null, "e": 1754, "s": 1557, "text": "Pickled files are Python-version-specific — You might encounter issues when saving files in one Python version and reading them in the other. Try to work in identical Python versions, if possible." }, { "code": null, "e": 1941, "s": 1754, "text": "Pickling doesn’t compress data — Pickling an object won’t compress it. Sure, the file will be smaller when compared to CSV, but you can compress the data manually for maximum efficiency." }, { "code": null, "e": 2046, "s": 1941, "text": "You’ll see a work-around for compressing data shortly. Let’s see how to work with Pickle in Python next." }, { "code": null, "e": 2225, "s": 2046, "text": "Let’s start by importing the required libraries and creating a relatively large dataset. You’ll need Numpy, Pandas, Pickle, and BZ2. You’ll use the last one for data compression:" }, { "code": null, "e": 2519, "s": 2225, "text": "import numpy as npimport pandas as pdimport pickleimport bz2np.random.seed = 42df_size = 10_000_000df = pd.DataFrame({ 'a': np.random.rand(df_size), 'b': np.random.rand(df_size), 'c': np.random.rand(df_size), 'd': np.random.rand(df_size), 'e': np.random.rand(df_size)})df.head()" }, { "code": null, "e": 2554, "s": 2519, "text": "Here’s how the dataset looks like:" }, { "code": null, "e": 2641, "s": 2554, "text": "Let’s save it locally next. You can use the following command to pickle the DataFrame:" }, { "code": null, "e": 2696, "s": 2641, "text": "with open('10M.pkl', 'wb') as f: pickle.dump(df, f)" }, { "code": null, "e": 2800, "s": 2696, "text": "The file is saved locally now. You can read it in a similar manner — just change the mode from wb to rb" }, { "code": null, "e": 2856, "s": 2800, "text": "with open('10M.pkl', 'rb') as f: df = pickle.load(f)" }, { "code": null, "e": 3025, "s": 2856, "text": "Awesome! As mentioned earlier, Pickle won’t do any compression by default. You’ll have to take care of that manually. Python makes it stupidly easy with the bz2 module:" }, { "code": null, "e": 3146, "s": 3025, "text": "with open('10M_compressed.pkl', 'wb') as f: compressed_file = bz2.BZ2File(f, 'w') pickle.dump(df, compressed_file)" }, { "code": null, "e": 3317, "s": 3146, "text": "It’s just an additional line of code, but it can save you some disk time. The saving process will be significantly longer, but that’s a tradeoff you’ll have to live with." }, { "code": null, "e": 3380, "s": 3317, "text": "Reading a compressed file requires an additional line of code:" }, { "code": null, "e": 3502, "s": 3380, "text": "with open('10M_compressed.pkl', 'rb') as f: compressed_file = bz2.BZ2File(f, 'r') df = pickle.load(compressed_file)" }, { "code": null, "e": 3719, "s": 3502, "text": "Just make sure not to mess up the file modes, as providing wb when reading a file will delete all its contents. It would be best to write the helper functions for read and write operations, so you never mess them up." }, { "code": null, "e": 3827, "s": 3719, "text": "The following section covers the comparison with the CSV file format — in file size, read, and write times." }, { "code": null, "e": 4078, "s": 3827, "text": "Answering this question isn’t as easy as it seems. Sure, CSVs provide view and edit privileges, as anyone can open them. That could also be considered as a downside, for obvious reasons. Moreover, you can’t save machine learning models to a CSV file." }, { "code": null, "e": 4144, "s": 4078, "text": "Still, let’s compare the two in file size, read, and write times." }, { "code": null, "e": 4239, "s": 4144, "text": "The following chart shows the time needed to save the DataFrame from the last section locally:" }, { "code": null, "e": 4315, "s": 4239, "text": "That’s around 80 times speed increase, if you don’t care about compression." }, { "code": null, "e": 4423, "s": 4315, "text": "Next, let’s compare the read times — how long does it take to read identical datasets in different formats:" }, { "code": null, "e": 4605, "s": 4423, "text": "Pickle is around 11 times faster this time, when not compressed. The compression is a huge pain point when reading and saving files. But, let’s see how much disk space does it save." }, { "code": null, "e": 4654, "s": 4605, "text": "That’s what the following visualization answers:" }, { "code": null, "e": 4782, "s": 4654, "text": "The file size decrease when compared to CSV is significant, but the compression doesn’t save that much disk space in this case." }, { "code": null, "e": 5051, "s": 4782, "text": "To recap, going from CSV to Pickle offers obvious advantages. What’s not 100% obvious is that Pickle lets you store other objects — anything built into Python, Numpy arrays, and even machine learning models. CSVs and other data-only formats don’t have that capability." }, { "code": null, "e": 5188, "s": 5051, "text": "What are your thoughts and experiences with Pickle? Is it your go-to format for the Python ecosystem? Let me know in the comments below." }, { "code": null, "e": 5371, "s": 5188, "text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you." }, { "code": null, "e": 5382, "s": 5371, "text": "medium.com" }, { "code": null, "e": 5429, "s": 5382, "text": "Follow me on Medium for more stories like this" }, { "code": null, "e": 5455, "s": 5429, "text": "Sign up for my newsletter" } ]
HTML - <nobr> Tag
The HTML <nobr> tag is used to instruct the browser not to break the specified text (such as the usual line wrap that occurs at the right edge of the browser window). This is used with the <wbr> tag, <wbr> advises the extended browser when it may insert a line break in an otherwise nonbreakable sequence of text. Unlike the <br> tag, which always causes a line break, even within a <nobr>- tagged segment, the <wbr> tag works only when placed inside a <nobr>- tagged content segment and causes a line break only if the current line has already extended beyond the browser's display window margins. <!DOCTYPE html> <html> <head> <title>HTML nobr Tag</title> </head> <body> <nobr>This is a very long sequence of text that is forced to be on a single line, even if doing so causes <wbr /> the browser to extend the document window beyond the size of the viewing pane and the poor user must scroll right <wbr /> to read the entire line. </nobr> </body> </html> This tag supports all the global attributes described in HTML Attribute Reference This tag is available in Netscape 4 and higher version only. 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2541, "s": 2374, "text": "The HTML <nobr> tag is used to instruct the browser not to break the specified text (such as the usual line wrap that occurs at the right edge of the browser window)." }, { "code": null, "e": 2973, "s": 2541, "text": "This is used with the <wbr> tag, <wbr> advises the extended browser when it may insert a line break in an otherwise nonbreakable sequence of text. Unlike the <br> tag, which always causes a line break, even within a <nobr>- tagged segment, the <wbr> tag works only when placed inside a <nobr>- tagged content segment and causes a line break only if the current line has already extended beyond the browser's display window margins." }, { "code": null, "e": 3405, "s": 2973, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML nobr Tag</title>\n </head>\n\n <body>\n <nobr>This is a very long sequence of text that is forced to be \n on a single line, even if doing so causes <wbr />\n \n the browser to extend the document window beyond the size of the \n viewing pane and the poor user must scroll right <wbr />\n \n to read the entire line.\n </nobr>\n </body>\n\n</html>" }, { "code": null, "e": 3487, "s": 3405, "text": "This tag supports all the global attributes described in HTML Attribute Reference" }, { "code": null, "e": 3548, "s": 3487, "text": "This tag is available in Netscape 4 and higher version only." }, { "code": null, "e": 3581, "s": 3548, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 3595, "s": 3581, "text": " Anadi Sharma" }, { "code": null, "e": 3630, "s": 3595, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3644, "s": 3630, "text": " Anadi Sharma" }, { "code": null, "e": 3679, "s": 3644, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3696, "s": 3679, "text": " Frahaan Hussain" }, { "code": null, "e": 3731, "s": 3696, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3762, "s": 3731, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3795, "s": 3762, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3826, "s": 3795, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3861, "s": 3826, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3892, "s": 3861, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3899, "s": 3892, "text": " Print" }, { "code": null, "e": 3910, "s": 3899, "text": " Add Notes" } ]
Abstract Classes in Dart - GeeksforGeeks
02 Sep, 2020 An Abstract class in Dart is defined for those classes which contain one or more than one abstract method (methods without implementation) in them. Whereas, to declare abstract class we make use of the abstract keyword. So, it must be noted that a class declared abstract may or may not include abstract methods but if it includes an abstract method then it must be an abstract class.Features of Abstract Class: A class containing an abstract method must be declared abstract whereas the class declared abstract may or may not have abstract methods i.e. it can have either abstract or concrete methods A class can be declared abstract by using abstract keyword only. A class declared as abstract can’t be initialised. An abstract class can be extended, but if you inherit an abstract class then you have to make sure that all the abstract methods in it are provided with implementation. Generally, abstract classes are used to implement the abstract methods to the extended subclasses.Syntax: abstract class class_name { // Body of the abstract class } Overriding abstract method of an abstract class – Dart // Understanding Abstract class in Dart // Creating Abstract Classabstract class Gfg { // Creating Abstract Methods void say(); void write();} class Geeksforgeeks extends Gfg{ @override void say() { print("Yo Geek!!"); } @override void write() { print("Geeks For Geeks"); }} main(){ Geeksforgeeks geek = new Geeksforgeeks(); geek.say(); geek.write();} Output: Yo Geek!! Geeks For Geeks Explanation: First, we declare an abstract class Gfg and create an abstract method geek_info inside it. After that, we extend the Gfg class to the second class and override the methods say() and write(), which result in their respective output.Note: It is not mandatory to override the method when there is only one class extending the abstract class, because override is used to change the pre-defined code and as in the above case, nothing is defined inside the method so the above code will work just fine without override.Overriding abstract method of an abstract class in two different classes – Dart // Understanding Abstract Class In Dart// Creating Abstract Classabstract class Gfg { // Creating Abstract Method void geek_info();} // Class Geek1 Inheriting Gfg classclass Geek1 extends Gfg { // Overriding method @override void geek_info() { print("This is Class Geek1."); }} // Class Geek2 Inheriting Gfg classclass Geek2 extends Gfg { // Overriding method again @override void geek_info() { print("This is Class Geek2."); }} void main(){ Geek1 g1 = new Geek1(); g1.geek_info(); Geek2 g2 = new Geek2(); g2.geek_info();} Output: This is Class Geek1. This is Class Geek2. Explanation: First, we declare an abstract class Gfg and create an abstract method geek_info inside it. After that, we extend the Gfg class to two other classes and override the method geek_info, which results in two different output strings.In this code, we have to use override as we are redefining the method in two different class. If we don’t use the override in the above example will give result as: This is Class Geek1 This is Class Geek1 The same result was printed twice because the method not redefined in the next class. mehmet1 Dart Class-object Dart-OOPs Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Dart Tutorial Flutter - Checkbox Widget ListView Class in Flutter Flutter - Stack Widget Flutter - BoxShadow Widget What is widgets in Flutter? How to Append or Concatenate Strings in Dart? Flutter - Carousel Slider
[ { "code": null, "e": 23970, "s": 23942, "text": "\n02 Sep, 2020" }, { "code": null, "e": 24384, "s": 23970, "text": "An Abstract class in Dart is defined for those classes which contain one or more than one abstract method (methods without implementation) in them. Whereas, to declare abstract class we make use of the abstract keyword. So, it must be noted that a class declared abstract may or may not include abstract methods but if it includes an abstract method then it must be an abstract class.Features of Abstract Class: " }, { "code": null, "e": 24574, "s": 24384, "text": "A class containing an abstract method must be declared abstract whereas the class declared abstract may or may not have abstract methods i.e. it can have either abstract or concrete methods" }, { "code": null, "e": 24639, "s": 24574, "text": "A class can be declared abstract by using abstract keyword only." }, { "code": null, "e": 24690, "s": 24639, "text": "A class declared as abstract can’t be initialised." }, { "code": null, "e": 24859, "s": 24690, "text": "An abstract class can be extended, but if you inherit an abstract class then you have to make sure that all the abstract methods in it are provided with implementation." }, { "code": null, "e": 24967, "s": 24859, "text": "Generally, abstract classes are used to implement the abstract methods to the extended subclasses.Syntax: " }, { "code": null, "e": 25033, "s": 24967, "text": "abstract class class_name {\n\n // Body of the abstract class\n}\n" }, { "code": null, "e": 25085, "s": 25033, "text": "Overriding abstract method of an abstract class – " }, { "code": null, "e": 25090, "s": 25085, "text": "Dart" }, { "code": "// Understanding Abstract class in Dart // Creating Abstract Classabstract class Gfg { // Creating Abstract Methods void say(); void write();} class Geeksforgeeks extends Gfg{ @override void say() { print(\"Yo Geek!!\"); } @override void write() { print(\"Geeks For Geeks\"); }} main(){ Geeksforgeeks geek = new Geeksforgeeks(); geek.say(); geek.write();}", "e": 25499, "s": 25090, "text": null }, { "code": null, "e": 25509, "s": 25499, "text": "Output: " }, { "code": null, "e": 25536, "s": 25509, "text": "Yo Geek!!\nGeeks For Geeks\n" }, { "code": null, "e": 26139, "s": 25536, "text": "Explanation: First, we declare an abstract class Gfg and create an abstract method geek_info inside it. After that, we extend the Gfg class to the second class and override the methods say() and write(), which result in their respective output.Note: It is not mandatory to override the method when there is only one class extending the abstract class, because override is used to change the pre-defined code and as in the above case, nothing is defined inside the method so the above code will work just fine without override.Overriding abstract method of an abstract class in two different classes – " }, { "code": null, "e": 26144, "s": 26139, "text": "Dart" }, { "code": "// Understanding Abstract Class In Dart// Creating Abstract Classabstract class Gfg { // Creating Abstract Method void geek_info();} // Class Geek1 Inheriting Gfg classclass Geek1 extends Gfg { // Overriding method @override void geek_info() { print(\"This is Class Geek1.\"); }} // Class Geek2 Inheriting Gfg classclass Geek2 extends Gfg { // Overriding method again @override void geek_info() { print(\"This is Class Geek2.\"); }} void main(){ Geek1 g1 = new Geek1(); g1.geek_info(); Geek2 g2 = new Geek2(); g2.geek_info();}", "e": 26729, "s": 26144, "text": null }, { "code": null, "e": 26739, "s": 26729, "text": "Output: " }, { "code": null, "e": 26782, "s": 26739, "text": "This is Class Geek1.\nThis is Class Geek2.\n" }, { "code": null, "e": 27191, "s": 26782, "text": "Explanation: First, we declare an abstract class Gfg and create an abstract method geek_info inside it. After that, we extend the Gfg class to two other classes and override the method geek_info, which results in two different output strings.In this code, we have to use override as we are redefining the method in two different class. If we don’t use the override in the above example will give result as: " }, { "code": null, "e": 27232, "s": 27191, "text": "This is Class Geek1\nThis is Class Geek1\n" }, { "code": null, "e": 27319, "s": 27232, "text": "The same result was printed twice because the method not redefined in the next class. " }, { "code": null, "e": 27327, "s": 27319, "text": "mehmet1" }, { "code": null, "e": 27345, "s": 27327, "text": "Dart Class-object" }, { "code": null, "e": 27355, "s": 27345, "text": "Dart-OOPs" }, { "code": null, "e": 27360, "s": 27355, "text": "Dart" }, { "code": null, "e": 27458, "s": 27360, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27467, "s": 27458, "text": "Comments" }, { "code": null, "e": 27480, "s": 27467, "text": "Old Comments" }, { "code": null, "e": 27512, "s": 27480, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 27551, "s": 27512, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 27565, "s": 27551, "text": "Dart Tutorial" }, { "code": null, "e": 27591, "s": 27565, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 27617, "s": 27591, "text": "ListView Class in Flutter" }, { "code": null, "e": 27640, "s": 27617, "text": "Flutter - Stack Widget" }, { "code": null, "e": 27667, "s": 27640, "text": "Flutter - BoxShadow Widget" }, { "code": null, "e": 27695, "s": 27667, "text": "What is widgets in Flutter?" }, { "code": null, "e": 27741, "s": 27695, "text": "How to Append or Concatenate Strings in Dart?" } ]
Java Bitwise Operators
Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte. Bitwise operator works on bits and performs the bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows − a = 0011 1100 b = 0000 1101 ----------------- a&b = 0000 1100 a|b = 0011 1101 a^b = 0011 0001 ~a = 1100 0011 The following table lists the bitwise operators − Assume integer variable A holds 60 and variable B holds 13 then −
[ { "code": null, "e": 1179, "s": 1062, "text": "Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte." }, { "code": null, "e": 1326, "s": 1179, "text": "Bitwise operator works on bits and performs the bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows − " }, { "code": null, "e": 1438, "s": 1326, "text": "a = 0011 1100\nb = 0000 1101\n-----------------\na&b = 0000 1100\n\na|b = 0011 1101\n\na^b = 0011 0001\n\n~a = 1100 0011" }, { "code": null, "e": 1488, "s": 1438, "text": "The following table lists the bitwise operators −" }, { "code": null, "e": 1554, "s": 1488, "text": "Assume integer variable A holds 60 and variable B holds 13 then −" } ]
6 Pandas tricks you should know to speed up your data analysis | by B. Chen | Towards Data Science
In this article, you’ll learn some of the most helpful Pandas tricks to speed up your data analysis. Select columns by data typesConvert strings to numbersDetect and handle missing valuesConvert a continuous numerical feature into a categorical featureCreate a DataFrame from the clipboardBuild a DataFrame from multiple files Select columns by data types Convert strings to numbers Detect and handle missing values Convert a continuous numerical feature into a categorical feature Create a DataFrame from the clipboard Build a DataFrame from multiple files Please check out my Github repo for the source code. Here are the data types of the Titanic DataFrame df.dtypesPassengerId int64Survived int64Pclass int64Name objectSex objectAge float64SibSp int64Parch int64Ticket objectFare float64Cabin objectEmbarked objectdtype: object Let’s say you need to select the numeric columns. df.select_dtypes(include='number').head() This includes both int and float columns. You could also use this method to select just object columns select multiple data types exclude certain data types # select just object columnsdf.select_dtypes(include='object')# select multiple data typesdf.select_dtypes(include=['int', 'datetime', 'object'])# exclude certain data typesdf.select_dtypes(exclude='int') There are two methods to convert a string into numbers in Pandas: the astype() method the to_numeric() method Let’s create an example DataFrame to have a look at the difference. df = pd.DataFrame({ 'product': ['A','B','C','D'], 'price': ['10','20','30','40'], 'sales': ['20','-','60','-'] }) The price and sales columns are stored as strings and so result in object columns: df.dtypesproduct objectprice objectsales objectdtype: object We can use the first method astype() to perform the conversion on the price column as follows # Use Python typedf['price'] = df['price'].astype(int)# alternatively, pass { col: dtype }df = df.astype({'price': 'int'}) However, this would have resulted in an error if we tried to use it on the sales column. To fix that, we can use to_numeric() with argument errors='coerce' df['sales'] = pd.to_numeric(df['sales'], errors='coerce') Now, invalid values - get converted into NaN and the data type is float. One way to detect missing values is by using info() method and take a look at the column Non-Null Count. df.info()RangeIndex: 891 entries, 0 to 890Data columns (total 12 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 PassengerId 891 non-null int64 1 Survived 891 non-null int64 2 Pclass 891 non-null int64 3 Name 891 non-null object 4 Sex 891 non-null object 5 Age 714 non-null float64 6 SibSp 891 non-null int64 7 Parch 891 non-null int64 8 Ticket 891 non-null object 9 Fare 891 non-null float64 10 Cabin 204 non-null object 11 Embarked 889 non-null object dtypes: float64(2), int64(5), object(5)memory usage: 83.7+ KB When the dataset is large, we can count the number of missing values instead. df.isnull().sum() returns the number of missing values for each column df.isnull().sum()PassengerId 0Survived 0Pclass 0Name 0Sex 0Age 177SibSp 0Parch 0Ticket 0Fare 0Cabin 687Embarked 2dtype: int64 df.isnull().sum().sum() returns the total number of missing values. df.isnull().sum().sum()886 In addition, we can also find out the percentage of values that are missing by running df.isna().mean() ufo.isna().mean()PassengerId 0.000000Survived 0.000000Pclass 0.000000Name 0.000000Sex 0.000000Age 0.198653SibSp 0.000000Parch 0.000000Ticket 0.000000Fare 0.000000Cabin 0.771044Embarked 0.002245dtype: float64 To drop rows if any NaN values are present df.dropna(axis = 0) To drop columns if any NaN values are present df.dropna(axis = 1) To drop columns in which more than 10% of values are missing df.dropna(thresh=len(df)*0.9, axis=1) To replace all NaN values with a scalar df.fillna(value=10) To replace NaN values with the values in the previous row. df.fillna(axis=0, method='ffill') To replace NaN values with the values in the previous column. df.fillna(axis=1, method='ffill') The same, you can also replace NaN values with the values in the next row or column. # Replace with the values in the next rowdf.fillna(axis=0, method='bfill')# Replace with the values in the next columndf.fillna(axis=1, method='bfill') The other common replacement is to replace NaN values with the mean. For example to replace NaN values in column Age with the mean. df['Age'].fillna(value=df['Age'].mean(), inplace=True) For more about missing values in Pandas, please check out Working with missing values in Pandas. In the step of data preparation, it is quite common to combine or transform existing features to create a more useful one. One of the most popular ways is to create a categorical feature from a continuous numerical feature. Let’s take a look at the Age column from the Titanic dataset df['Age'].head(8)0 22.01 38.02 26.03 35.04 35.05 NaN6 54.07 2.0Name: Age, dtype: float64 Age is a continuous numerical attribute, but what if you want to convert it into a categorical attribute, for example, convert ages to groups of age ranges: ≤12, Teen (≤18), Adult (≤60), and Older (>60) The best way to do this is by using the Pandas cut() function: import sysdf['ageGroup']=pd.cut( df['Age'], bins=[0, 13, 19, 61, sys.maxsize], labels=['<12', 'Teen', 'Adult', 'Older']) And calling head() on the ageGroup column should also display the column information. df['ageGroup'].head(8)0 Adult1 Adult2 Adult3 Adult4 Adult5 NaN6 Adult7 <12Name: ageGroup, dtype: categoryCategories (4, object): [<12 < Teen < Adult < Older] Pandas read_clipboard() function is a very handy way to get data into a DataFrame as quickly as possible. Suppose we have the following data and we want to create a data frame from it: product price0 A 101 B 202 C 304 D 40 We just need to select the data and copy it to the clipboard. Then, we can use the function to read it into a DataFrame. df = pd.read_clipboard()df Your dataset might spread across multiple files, but you want to read the dataset into a single DataFrame. One way to this is to read each file into its own DataFrame, combine them together, and then delete the original DataFrame, but that would be memory inefficient. A better solution is to use the built-in glob module (Thanks to Data School Pandas Tricks). In this case, glob() is looking in the data directory for all CSV files that begin with the word “data_row_”. glob() returns filenames in an arbitrary order, which is why we sorted the list using sort() the function. Let’s say that our dataset is spread across 2 files, data_row_1.csv and data_row_2.csv, in row-wise To create a DataFrame from the 2 files. files = sorted(glob('data/data_row_*.csv'))pd.concat((pd.read_csv(file) for file in files), ignore_index=True) sorted(glob('data/data_row_*.csv')) returns filenames. After that, we read each of the files using read_csv() and pass the results to the concat() function, which will concatenate the rows into a single DataFrame. In addition, to avoid duplicate value in the index, we tell the concat() to ignore the index (ignore_index=True) and instead use the default integer index. Let’s say that our dataset is spread across 2 files, data_col_1.csv and data_col_2.csv, in column-wise. To create a DataFrame from the 2 files. files = sorted(glob('data/data_col_*.csv'))pd.concat((pd.read_csv(file) for file in files), axis=1) This time, we tell the concat() function to concatenate along the columns axis. Thanks for reading. Please checkout the notebook on my Github for the source code. Stay tuned if you are interested in the practical aspect of machine learning.
[ { "code": null, "e": 273, "s": 172, "text": "In this article, you’ll learn some of the most helpful Pandas tricks to speed up your data analysis." }, { "code": null, "e": 499, "s": 273, "text": "Select columns by data typesConvert strings to numbersDetect and handle missing valuesConvert a continuous numerical feature into a categorical featureCreate a DataFrame from the clipboardBuild a DataFrame from multiple files" }, { "code": null, "e": 528, "s": 499, "text": "Select columns by data types" }, { "code": null, "e": 555, "s": 528, "text": "Convert strings to numbers" }, { "code": null, "e": 588, "s": 555, "text": "Detect and handle missing values" }, { "code": null, "e": 654, "s": 588, "text": "Convert a continuous numerical feature into a categorical feature" }, { "code": null, "e": 692, "s": 654, "text": "Create a DataFrame from the clipboard" }, { "code": null, "e": 730, "s": 692, "text": "Build a DataFrame from multiple files" }, { "code": null, "e": 783, "s": 730, "text": "Please check out my Github repo for the source code." }, { "code": null, "e": 832, "s": 783, "text": "Here are the data types of the Titanic DataFrame" }, { "code": null, "e": 1119, "s": 832, "text": "df.dtypesPassengerId int64Survived int64Pclass int64Name objectSex objectAge float64SibSp int64Parch int64Ticket objectFare float64Cabin objectEmbarked objectdtype: object" }, { "code": null, "e": 1169, "s": 1119, "text": "Let’s say you need to select the numeric columns." }, { "code": null, "e": 1211, "s": 1169, "text": "df.select_dtypes(include='number').head()" }, { "code": null, "e": 1287, "s": 1211, "text": "This includes both int and float columns. You could also use this method to" }, { "code": null, "e": 1314, "s": 1287, "text": "select just object columns" }, { "code": null, "e": 1341, "s": 1314, "text": "select multiple data types" }, { "code": null, "e": 1368, "s": 1341, "text": "exclude certain data types" }, { "code": null, "e": 1573, "s": 1368, "text": "# select just object columnsdf.select_dtypes(include='object')# select multiple data typesdf.select_dtypes(include=['int', 'datetime', 'object'])# exclude certain data typesdf.select_dtypes(exclude='int')" }, { "code": null, "e": 1639, "s": 1573, "text": "There are two methods to convert a string into numbers in Pandas:" }, { "code": null, "e": 1659, "s": 1639, "text": "the astype() method" }, { "code": null, "e": 1683, "s": 1659, "text": "the to_numeric() method" }, { "code": null, "e": 1751, "s": 1683, "text": "Let’s create an example DataFrame to have a look at the difference." }, { "code": null, "e": 1919, "s": 1751, "text": "df = pd.DataFrame({ 'product': ['A','B','C','D'], 'price': ['10','20','30','40'], 'sales': ['20','-','60','-'] })" }, { "code": null, "e": 2002, "s": 1919, "text": "The price and sales columns are stored as strings and so result in object columns:" }, { "code": null, "e": 2076, "s": 2002, "text": "df.dtypesproduct objectprice objectsales objectdtype: object" }, { "code": null, "e": 2170, "s": 2076, "text": "We can use the first method astype() to perform the conversion on the price column as follows" }, { "code": null, "e": 2293, "s": 2170, "text": "# Use Python typedf['price'] = df['price'].astype(int)# alternatively, pass { col: dtype }df = df.astype({'price': 'int'})" }, { "code": null, "e": 2449, "s": 2293, "text": "However, this would have resulted in an error if we tried to use it on the sales column. To fix that, we can use to_numeric() with argument errors='coerce'" }, { "code": null, "e": 2507, "s": 2449, "text": "df['sales'] = pd.to_numeric(df['sales'], errors='coerce')" }, { "code": null, "e": 2580, "s": 2507, "text": "Now, invalid values - get converted into NaN and the data type is float." }, { "code": null, "e": 2685, "s": 2580, "text": "One way to detect missing values is by using info() method and take a look at the column Non-Null Count." }, { "code": null, "e": 3395, "s": 2685, "text": "df.info()RangeIndex: 891 entries, 0 to 890Data columns (total 12 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 PassengerId 891 non-null int64 1 Survived 891 non-null int64 2 Pclass 891 non-null int64 3 Name 891 non-null object 4 Sex 891 non-null object 5 Age 714 non-null float64 6 SibSp 891 non-null int64 7 Parch 891 non-null int64 8 Ticket 891 non-null object 9 Fare 891 non-null float64 10 Cabin 204 non-null object 11 Embarked 889 non-null object dtypes: float64(2), int64(5), object(5)memory usage: 83.7+ KB" }, { "code": null, "e": 3544, "s": 3395, "text": "When the dataset is large, we can count the number of missing values instead. df.isnull().sum() returns the number of missing values for each column" }, { "code": null, "e": 3790, "s": 3544, "text": "df.isnull().sum()PassengerId 0Survived 0Pclass 0Name 0Sex 0Age 177SibSp 0Parch 0Ticket 0Fare 0Cabin 687Embarked 2dtype: int64" }, { "code": null, "e": 3858, "s": 3790, "text": "df.isnull().sum().sum() returns the total number of missing values." }, { "code": null, "e": 3885, "s": 3858, "text": "df.isnull().sum().sum()886" }, { "code": null, "e": 3989, "s": 3885, "text": "In addition, we can also find out the percentage of values that are missing by running df.isna().mean()" }, { "code": null, "e": 4297, "s": 3989, "text": "ufo.isna().mean()PassengerId 0.000000Survived 0.000000Pclass 0.000000Name 0.000000Sex 0.000000Age 0.198653SibSp 0.000000Parch 0.000000Ticket 0.000000Fare 0.000000Cabin 0.771044Embarked 0.002245dtype: float64" }, { "code": null, "e": 4340, "s": 4297, "text": "To drop rows if any NaN values are present" }, { "code": null, "e": 4360, "s": 4340, "text": "df.dropna(axis = 0)" }, { "code": null, "e": 4406, "s": 4360, "text": "To drop columns if any NaN values are present" }, { "code": null, "e": 4426, "s": 4406, "text": "df.dropna(axis = 1)" }, { "code": null, "e": 4487, "s": 4426, "text": "To drop columns in which more than 10% of values are missing" }, { "code": null, "e": 4525, "s": 4487, "text": "df.dropna(thresh=len(df)*0.9, axis=1)" }, { "code": null, "e": 4565, "s": 4525, "text": "To replace all NaN values with a scalar" }, { "code": null, "e": 4585, "s": 4565, "text": "df.fillna(value=10)" }, { "code": null, "e": 4644, "s": 4585, "text": "To replace NaN values with the values in the previous row." }, { "code": null, "e": 4678, "s": 4644, "text": "df.fillna(axis=0, method='ffill')" }, { "code": null, "e": 4740, "s": 4678, "text": "To replace NaN values with the values in the previous column." }, { "code": null, "e": 4774, "s": 4740, "text": "df.fillna(axis=1, method='ffill')" }, { "code": null, "e": 4859, "s": 4774, "text": "The same, you can also replace NaN values with the values in the next row or column." }, { "code": null, "e": 5011, "s": 4859, "text": "# Replace with the values in the next rowdf.fillna(axis=0, method='bfill')# Replace with the values in the next columndf.fillna(axis=1, method='bfill')" }, { "code": null, "e": 5143, "s": 5011, "text": "The other common replacement is to replace NaN values with the mean. For example to replace NaN values in column Age with the mean." }, { "code": null, "e": 5198, "s": 5143, "text": "df['Age'].fillna(value=df['Age'].mean(), inplace=True)" }, { "code": null, "e": 5295, "s": 5198, "text": "For more about missing values in Pandas, please check out Working with missing values in Pandas." }, { "code": null, "e": 5519, "s": 5295, "text": "In the step of data preparation, it is quite common to combine or transform existing features to create a more useful one. One of the most popular ways is to create a categorical feature from a continuous numerical feature." }, { "code": null, "e": 5580, "s": 5519, "text": "Let’s take a look at the Age column from the Titanic dataset" }, { "code": null, "e": 5695, "s": 5580, "text": "df['Age'].head(8)0 22.01 38.02 26.03 35.04 35.05 NaN6 54.07 2.0Name: Age, dtype: float64" }, { "code": null, "e": 5898, "s": 5695, "text": "Age is a continuous numerical attribute, but what if you want to convert it into a categorical attribute, for example, convert ages to groups of age ranges: ≤12, Teen (≤18), Adult (≤60), and Older (>60)" }, { "code": null, "e": 5961, "s": 5898, "text": "The best way to do this is by using the Pandas cut() function:" }, { "code": null, "e": 6093, "s": 5961, "text": "import sysdf['ageGroup']=pd.cut( df['Age'], bins=[0, 13, 19, 61, sys.maxsize], labels=['<12', 'Teen', 'Adult', 'Older'])" }, { "code": null, "e": 6179, "s": 6093, "text": "And calling head() on the ageGroup column should also display the column information." }, { "code": null, "e": 6365, "s": 6179, "text": "df['ageGroup'].head(8)0 Adult1 Adult2 Adult3 Adult4 Adult5 NaN6 Adult7 <12Name: ageGroup, dtype: categoryCategories (4, object): [<12 < Teen < Adult < Older]" }, { "code": null, "e": 6471, "s": 6365, "text": "Pandas read_clipboard() function is a very handy way to get data into a DataFrame as quickly as possible." }, { "code": null, "e": 6550, "s": 6471, "text": "Suppose we have the following data and we want to create a data frame from it:" }, { "code": null, "e": 6639, "s": 6550, "text": " product price0 A 101 B 202 C 304 D 40" }, { "code": null, "e": 6760, "s": 6639, "text": "We just need to select the data and copy it to the clipboard. Then, we can use the function to read it into a DataFrame." }, { "code": null, "e": 6787, "s": 6760, "text": "df = pd.read_clipboard()df" }, { "code": null, "e": 6894, "s": 6787, "text": "Your dataset might spread across multiple files, but you want to read the dataset into a single DataFrame." }, { "code": null, "e": 7056, "s": 6894, "text": "One way to this is to read each file into its own DataFrame, combine them together, and then delete the original DataFrame, but that would be memory inefficient." }, { "code": null, "e": 7148, "s": 7056, "text": "A better solution is to use the built-in glob module (Thanks to Data School Pandas Tricks)." }, { "code": null, "e": 7365, "s": 7148, "text": "In this case, glob() is looking in the data directory for all CSV files that begin with the word “data_row_”. glob() returns filenames in an arbitrary order, which is why we sorted the list using sort() the function." }, { "code": null, "e": 7465, "s": 7365, "text": "Let’s say that our dataset is spread across 2 files, data_row_1.csv and data_row_2.csv, in row-wise" }, { "code": null, "e": 7505, "s": 7465, "text": "To create a DataFrame from the 2 files." }, { "code": null, "e": 7616, "s": 7505, "text": "files = sorted(glob('data/data_row_*.csv'))pd.concat((pd.read_csv(file) for file in files), ignore_index=True)" }, { "code": null, "e": 7986, "s": 7616, "text": "sorted(glob('data/data_row_*.csv')) returns filenames. After that, we read each of the files using read_csv() and pass the results to the concat() function, which will concatenate the rows into a single DataFrame. In addition, to avoid duplicate value in the index, we tell the concat() to ignore the index (ignore_index=True) and instead use the default integer index." }, { "code": null, "e": 8090, "s": 7986, "text": "Let’s say that our dataset is spread across 2 files, data_col_1.csv and data_col_2.csv, in column-wise." }, { "code": null, "e": 8130, "s": 8090, "text": "To create a DataFrame from the 2 files." }, { "code": null, "e": 8230, "s": 8130, "text": "files = sorted(glob('data/data_col_*.csv'))pd.concat((pd.read_csv(file) for file in files), axis=1)" }, { "code": null, "e": 8310, "s": 8230, "text": "This time, we tell the concat() function to concatenate along the columns axis." }, { "code": null, "e": 8330, "s": 8310, "text": "Thanks for reading." }, { "code": null, "e": 8393, "s": 8330, "text": "Please checkout the notebook on my Github for the source code." } ]
Reading Tabular Data from Files in Julia - GeeksforGeeks
10 Jun, 2021 Julia is a high level, high performance, dynamic programming language which allows users to load, save, and manipulate data in various types of files for data science, analysis, and machine learning purposes. Tabular data is data that has a structure of a table and it can be easily read from various files like text, CSV, Excel, etc. To perform such operations on data and files with ease, we add the Queryverse.jl package which provides us ease of use for other useful packages such as Query.jl, FileIO.jl, CSVFiles.jl, etc. Julia # Adding the Queryverse packageusing PkgPkg.add("Queryverse") To read data from a text file we have to open it first using the open() function. And to read the tabular data in the file we have to read data in the file line by line using readline() function as shown below: Julia # read file contents, line by line open("geek.txt") do f # line_number line = 0 # read till end of file while ! eof(f) # read a new / next line for every iteration s = readline(f) line += 1 println("$(line-1). $s") endend DataFrames are used to store data in a tabular form and these DataFrames can be read from CSV or Excel files by using the Queryverse.jl package and the load() function. Queryverse.jl package lets the FileIO.jl package use the CSVFiles.jl package to implement this. Julia # using necessary packagesusing DataFrames, Queryverse # reading dataframedf = load("marks.csv") |> DataFrame Sometimes in CSV files, data is separated by different characters like semicolons. The semicolon can be specified in the load() function to read data in normal tabular form, i.e. without the semicolons. Julia # reading data without semicolonsdf = load("marks_sc.csv", ';') |> DataFrame The column names of the DataFrame take up the first row of the file. To change this we can use the header keyword argument and equate it to false to remove the column names and change the first row into elements of the table in the file. Julia # reading data without headersdf = load("marks.csv", header_exists = false) |> DataFrame While loading the data of the file, we can also change the column names using the colnames keyword as shown below: Julia # reading data by changing column namesdf = load("marks.csv", colnames = ["class", "score"]) |> DataFrame Tabular data from a CSV file can be loaded without a specific number of rows using the skiplines_begin keyword. Julia # reading data without specific rowsdf = load("marks.csv", skiplines_begin = 1) |> DataFrame The process for reading data from excel sheets is the same as that of CSV files, which has been discussed above, but we have to specify a file with the extension ‘*.xlsx’ instead of a ‘.csv’ in the load() function and the specific sheet we want to read. Julia # reading sheet 1 of an excel filedf = load("marks.xlsx", "Sheet1") |> DataFrame We can also read specific rows and columns of the data in an excel file using the skipstartrows and skipstartcols keywords which skip specified rows and columns as shown below: Julia # reading by skipping specific rows and columnsdf = load("marks.xlsx", "Sheet1", skipstartrows = 1, skipstartcols = 1) |> DataFrame sooda367 julia-FileHandling Picked Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Reshaping array dimensions in Julia | Array reshape() Method Working with DataFrames in Julia Getting the maximum value from a list in Julia - max() Method Importing data from Files in Julia Find maximum element along with its index in Julia - findmax() Method Creating a view of parent array in Julia - view(), @view and @views Methods Functions in Julia Get array dimensions and size of a dimension in Julia - size() Method Julia global Keyword | Creating a global variable in Julia How to Install Julia on Windows ?
[ { "code": null, "e": 24061, "s": 24033, "text": "\n10 Jun, 2021" }, { "code": null, "e": 24397, "s": 24061, "text": "Julia is a high level, high performance, dynamic programming language which allows users to load, save, and manipulate data in various types of files for data science, analysis, and machine learning purposes. Tabular data is data that has a structure of a table and it can be easily read from various files like text, CSV, Excel, etc. " }, { "code": null, "e": 24589, "s": 24397, "text": "To perform such operations on data and files with ease, we add the Queryverse.jl package which provides us ease of use for other useful packages such as Query.jl, FileIO.jl, CSVFiles.jl, etc." }, { "code": null, "e": 24595, "s": 24589, "text": "Julia" }, { "code": "# Adding the Queryverse packageusing PkgPkg.add(\"Queryverse\")", "e": 24657, "s": 24595, "text": null }, { "code": null, "e": 24873, "s": 24662, "text": "To read data from a text file we have to open it first using the open() function. And to read the tabular data in the file we have to read data in the file line by line using readline() function as shown below:" }, { "code": null, "e": 24881, "s": 24875, "text": "Julia" }, { "code": "# read file contents, line by line open(\"geek.txt\") do f # line_number line = 0 # read till end of file while ! eof(f) # read a new / next line for every iteration s = readline(f) line += 1 println(\"$(line-1). $s\") endend", "e": 25127, "s": 24881, "text": null }, { "code": null, "e": 25397, "s": 25132, "text": "DataFrames are used to store data in a tabular form and these DataFrames can be read from CSV or Excel files by using the Queryverse.jl package and the load() function. Queryverse.jl package lets the FileIO.jl package use the CSVFiles.jl package to implement this." }, { "code": null, "e": 25405, "s": 25399, "text": "Julia" }, { "code": "# using necessary packagesusing DataFrames, Queryverse # reading dataframedf = load(\"marks.csv\") |> DataFrame", "e": 25515, "s": 25405, "text": null }, { "code": null, "e": 25604, "s": 25520, "text": "Sometimes in CSV files, data is separated by different characters like semicolons. " }, { "code": null, "e": 25728, "s": 25608, "text": "The semicolon can be specified in the load() function to read data in normal tabular form, i.e. without the semicolons." }, { "code": null, "e": 25736, "s": 25730, "text": "Julia" }, { "code": "# reading data without semicolonsdf = load(\"marks_sc.csv\", ';') |> DataFrame", "e": 25813, "s": 25736, "text": null }, { "code": null, "e": 26056, "s": 25818, "text": "The column names of the DataFrame take up the first row of the file. To change this we can use the header keyword argument and equate it to false to remove the column names and change the first row into elements of the table in the file." }, { "code": null, "e": 26064, "s": 26058, "text": "Julia" }, { "code": "# reading data without headersdf = load(\"marks.csv\", header_exists = false) |> DataFrame", "e": 26163, "s": 26064, "text": null }, { "code": null, "e": 26283, "s": 26168, "text": "While loading the data of the file, we can also change the column names using the colnames keyword as shown below:" }, { "code": null, "e": 26291, "s": 26285, "text": "Julia" }, { "code": "# reading data by changing column namesdf = load(\"marks.csv\", colnames = [\"class\", \"score\"]) |> DataFrame", "e": 26432, "s": 26291, "text": null }, { "code": null, "e": 26549, "s": 26437, "text": "Tabular data from a CSV file can be loaded without a specific number of rows using the skiplines_begin keyword." }, { "code": null, "e": 26557, "s": 26551, "text": "Julia" }, { "code": "# reading data without specific rowsdf = load(\"marks.csv\", skiplines_begin = 1) |> DataFrame", "e": 26660, "s": 26557, "text": null }, { "code": null, "e": 26919, "s": 26665, "text": "The process for reading data from excel sheets is the same as that of CSV files, which has been discussed above, but we have to specify a file with the extension ‘*.xlsx’ instead of a ‘.csv’ in the load() function and the specific sheet we want to read." }, { "code": null, "e": 26927, "s": 26921, "text": "Julia" }, { "code": "# reading sheet 1 of an excel filedf = load(\"marks.xlsx\", \"Sheet1\") |> DataFrame", "e": 27008, "s": 26927, "text": null }, { "code": null, "e": 27190, "s": 27013, "text": "We can also read specific rows and columns of the data in an excel file using the skipstartrows and skipstartcols keywords which skip specified rows and columns as shown below:" }, { "code": null, "e": 27198, "s": 27192, "text": "Julia" }, { "code": "# reading by skipping specific rows and columnsdf = load(\"marks.xlsx\", \"Sheet1\", skipstartrows = 1, skipstartcols = 1) |> DataFrame", "e": 27358, "s": 27198, "text": null }, { "code": null, "e": 27367, "s": 27358, "text": "sooda367" }, { "code": null, "e": 27386, "s": 27367, "text": "julia-FileHandling" }, { "code": null, "e": 27393, "s": 27386, "text": "Picked" }, { "code": null, "e": 27399, "s": 27393, "text": "Julia" }, { "code": null, "e": 27497, "s": 27399, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27506, "s": 27497, "text": "Comments" }, { "code": null, "e": 27519, "s": 27506, "text": "Old Comments" }, { "code": null, "e": 27580, "s": 27519, "text": "Reshaping array dimensions in Julia | Array reshape() Method" }, { "code": null, "e": 27613, "s": 27580, "text": "Working with DataFrames in Julia" }, { "code": null, "e": 27675, "s": 27613, "text": "Getting the maximum value from a list in Julia - max() Method" }, { "code": null, "e": 27710, "s": 27675, "text": "Importing data from Files in Julia" }, { "code": null, "e": 27780, "s": 27710, "text": "Find maximum element along with its index in Julia - findmax() Method" }, { "code": null, "e": 27856, "s": 27780, "text": "Creating a view of parent array in Julia - view(), @view and @views Methods" }, { "code": null, "e": 27875, "s": 27856, "text": "Functions in Julia" }, { "code": null, "e": 27945, "s": 27875, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 28004, "s": 27945, "text": "Julia global Keyword | Creating a global variable in Julia" } ]
File createTempFile() method in Java with Examples - GeeksforGeeks
20 Jun, 2021 The createTempFile() function creates a temporary file in a given directory ( if directory is not mentioned then a default directory is selected ), the function generates the filename by using the prefix and suffix passed as the parameters . If the suffix is null then the function uses “.tmp” as suffix. The function then returns the created fileFunction signature: 1. public static File createTempFile(String PREFIX, String SUFFIX)OR2. public static File createTempFile(String PREFIX, String SUFFIX, File DIR) Syntax: 1. File.createTempFile(String, String, FILE); 2. File.createTempFile(String, String); Parameters:The function is a overloaded function so one function takes suffix, prefix and a File object, whereas other function takes only suffix and prefix.The prefix must not be less than three characters but the suffix might be null and if the directory is not specified or a null value is passed then the function uses an default directory.Return Type: The function returns the abstract file name denoting the newly created temporary fileException: This method throws: IllegalArgumentException: if the prefix argument contains less than three characters IOExcetion: if there is any IO error(File could not be created) SecurityException: if the method does not allow file to be created Below programs illustrates the use of createTempFile() function:Example 1: If we provide the prefix string and provide null suffix string Java // Java program to demonstrate// createTempFile() method of File Class import java.io.*; public class solution { public static void main(String args[]) { try { // create a temp file File f = File.createTempFile("geeks", null); // check if the file is created if (f.exists()) { // the file is created // as the function returned true System.out.println("Temp File created: " + f.getName()); } else { // display the file cannot be created // as the function returned false System.out.println("Temp File cannot be created: " + f.getName()); } } catch (Exception e) { // display the error message System.err.println(e); } }} Output: Temp File created: geeks7503529537487244659.tmp Example 2: If we provide the prefix string and a definite suffix string Java // Java Program to demonstrate// createTempFile() method import java.io.*; public class solution { public static void main(String args[]) { try { // create a temp file File f = File.createTempFile("geeks", ".SVP"); // check if the file is created if (f.exists()) { // the file is created // as the function returned true System.out.println("Temp File created: " + f.getName()); } else { // display the file cannot be created // as the function returned false System.out.println("Temp File cannot be created: " + f.getName()); } } catch (Exception e) { // display the error message System.err.println(e); } }} Output: Temp File created: geeks4425780422923344328.SVP Example 3: If we provide the prefix string, a definite suffix string and a directory Java // Java Program to demonstrate// createTempFile() method import java.io.*; public class solution { public static void main(String args[]) { try { // create a temp file File f = File.createTempFile("geeks", ".SVP", new File("F:")); // check if the file is created if (f.exists()) { // the file is created // as the function returned true System.out.println("Temp File created: " + f.getAbsolutePath()); } else { // display the file cannot be created // as the function returned false System.out.println("Temp File cannot be created: " + f.getAbsolutePath()); } } catch (Exception e) { // display the error message System.err.println(e); } }} Output: Temp File created: F:\geeks7006753451952178741.SVP Note: The programs might not run in an online IDE. Please use an offline IDE and set the path of the file. sooda367 Java-File Class Java-Functions Java-IO package Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Java Programming Examples How to Iterate HashMap in Java? Iterate through List in Java Factory method design pattern in Java Min Heap in Java Java Program to Remove Duplicate Elements From the Array Traverse Through a HashMap in Java Java program to count the occurrence of each character in a string using Hashmap Iterate Over the Characters of a String in Java How to Get Elements By Index from HashSet in Java?
[ { "code": null, "e": 25174, "s": 25146, "text": "\n20 Jun, 2021" }, { "code": null, "e": 25543, "s": 25174, "text": "The createTempFile() function creates a temporary file in a given directory ( if directory is not mentioned then a default directory is selected ), the function generates the filename by using the prefix and suffix passed as the parameters . If the suffix is null then the function uses “.tmp” as suffix. The function then returns the created fileFunction signature: " }, { "code": null, "e": 25690, "s": 25543, "text": "1. public static File createTempFile(String PREFIX, String SUFFIX)OR2. public static File createTempFile(String PREFIX, String SUFFIX, File DIR) " }, { "code": null, "e": 25700, "s": 25690, "text": "Syntax: " }, { "code": null, "e": 25787, "s": 25700, "text": "1. File.createTempFile(String, String, FILE);\n\n2. File.createTempFile(String, String);" }, { "code": null, "e": 26262, "s": 25787, "text": "Parameters:The function is a overloaded function so one function takes suffix, prefix and a File object, whereas other function takes only suffix and prefix.The prefix must not be less than three characters but the suffix might be null and if the directory is not specified or a null value is passed then the function uses an default directory.Return Type: The function returns the abstract file name denoting the newly created temporary fileException: This method throws: " }, { "code": null, "e": 26347, "s": 26262, "text": "IllegalArgumentException: if the prefix argument contains less than three characters" }, { "code": null, "e": 26411, "s": 26347, "text": "IOExcetion: if there is any IO error(File could not be created)" }, { "code": null, "e": 26478, "s": 26411, "text": "SecurityException: if the method does not allow file to be created" }, { "code": null, "e": 26617, "s": 26478, "text": "Below programs illustrates the use of createTempFile() function:Example 1: If we provide the prefix string and provide null suffix string " }, { "code": null, "e": 26622, "s": 26617, "text": "Java" }, { "code": "// Java program to demonstrate// createTempFile() method of File Class import java.io.*; public class solution { public static void main(String args[]) { try { // create a temp file File f = File.createTempFile(\"geeks\", null); // check if the file is created if (f.exists()) { // the file is created // as the function returned true System.out.println(\"Temp File created: \" + f.getName()); } else { // display the file cannot be created // as the function returned false System.out.println(\"Temp File cannot be created: \" + f.getName()); } } catch (Exception e) { // display the error message System.err.println(e); } }}", "e": 27559, "s": 26622, "text": null }, { "code": null, "e": 27569, "s": 27559, "text": "Output: " }, { "code": null, "e": 27617, "s": 27569, "text": "Temp File created: geeks7503529537487244659.tmp" }, { "code": null, "e": 27690, "s": 27617, "text": "Example 2: If we provide the prefix string and a definite suffix string " }, { "code": null, "e": 27695, "s": 27690, "text": "Java" }, { "code": "// Java Program to demonstrate// createTempFile() method import java.io.*; public class solution { public static void main(String args[]) { try { // create a temp file File f = File.createTempFile(\"geeks\", \".SVP\"); // check if the file is created if (f.exists()) { // the file is created // as the function returned true System.out.println(\"Temp File created: \" + f.getName()); } else { // display the file cannot be created // as the function returned false System.out.println(\"Temp File cannot be created: \" + f.getName()); } } catch (Exception e) { // display the error message System.err.println(e); } }}", "e": 28606, "s": 27695, "text": null }, { "code": null, "e": 28616, "s": 28606, "text": "Output: " }, { "code": null, "e": 28664, "s": 28616, "text": "Temp File created: geeks4425780422923344328.SVP" }, { "code": null, "e": 28750, "s": 28664, "text": "Example 3: If we provide the prefix string, a definite suffix string and a directory " }, { "code": null, "e": 28755, "s": 28750, "text": "Java" }, { "code": "// Java Program to demonstrate// createTempFile() method import java.io.*; public class solution { public static void main(String args[]) { try { // create a temp file File f = File.createTempFile(\"geeks\", \".SVP\", new File(\"F:\")); // check if the file is created if (f.exists()) { // the file is created // as the function returned true System.out.println(\"Temp File created: \" + f.getAbsolutePath()); } else { // display the file cannot be created // as the function returned false System.out.println(\"Temp File cannot be created: \" + f.getAbsolutePath()); } } catch (Exception e) { // display the error message System.err.println(e); } }}", "e": 29777, "s": 28755, "text": null }, { "code": null, "e": 29787, "s": 29777, "text": "Output: " }, { "code": null, "e": 29838, "s": 29787, "text": "Temp File created: F:\\geeks7006753451952178741.SVP" }, { "code": null, "e": 29946, "s": 29838, "text": "Note: The programs might not run in an online IDE. Please use an offline IDE and set the path of the file. " }, { "code": null, "e": 29955, "s": 29946, "text": "sooda367" }, { "code": null, "e": 29971, "s": 29955, "text": "Java-File Class" }, { "code": null, "e": 29986, "s": 29971, "text": "Java-Functions" }, { "code": null, "e": 30002, "s": 29986, "text": "Java-IO package" }, { "code": null, "e": 30016, "s": 30002, "text": "Java Programs" }, { "code": null, "e": 30114, "s": 30016, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30140, "s": 30114, "text": "Java Programming Examples" }, { "code": null, "e": 30172, "s": 30140, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 30201, "s": 30172, "text": "Iterate through List in Java" }, { "code": null, "e": 30239, "s": 30201, "text": "Factory method design pattern in Java" }, { "code": null, "e": 30256, "s": 30239, "text": "Min Heap in Java" }, { "code": null, "e": 30313, "s": 30256, "text": "Java Program to Remove Duplicate Elements From the Array" }, { "code": null, "e": 30348, "s": 30313, "text": "Traverse Through a HashMap in Java" }, { "code": null, "e": 30429, "s": 30348, "text": "Java program to count the occurrence of each character in a string using Hashmap" }, { "code": null, "e": 30477, "s": 30429, "text": "Iterate Over the Characters of a String in Java" } ]
Paragraph Formatting In Python .docx Module - GeeksforGeeks
03 Jan, 2021 Prerequisite: Working with .docx module Word documents contain formatted text wrapped within three object levels. The Lowest level- run objects, middle level- paragraph objects, and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. Pip command to install this module is: pip install python-docx Python docx module allows users to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend. To set the line spacing between the text in the paragraph we make use of the paragraph_format along with line_spacing. It is used to set the space between each line in the paragraph. Syntax: para.paragraph_format.line_spacing = Length Parameter: Length: It is the length of the space to be left between the lines. It takes length as an input. It can be defined either with an absolute distance value or with a relative distance value of the line-height. If the input is in pt, inches or cm then it considered them as an absolute value and if the input is in float then it is considered as a relative value. Example 1: Setting the line spacing with absolute distance value. Python3 # Import docx NOT python-docximport docxfrom docx.shared import Inches # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding paragraph with spacingdoc.add_heading('Line Spacing: Para-1 [With Spacing]', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.')# Adding line space of 0.5 inches in the paragraphpara.paragraph_format.line_spacing = Inches(0.5) # Adding paragraph without spacingdoc.add_heading('Line Spacing: Para-2 [Without Spacing]', 3)doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.') # Now save the document to a location doc.save('gfg.docx') Output: Example 2: Setting the line spacing with relative value. Python3 # Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding paragraph with spacingdoc.add_heading('Line Spacing: Para-1 [With Spacing]', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.')# Adding line space in the paragraphpara.paragraph_format.line_spacing = 1.75 # Adding paragraph without spacingdoc.add_heading('Line Spacing: Para-2 [Without Spacing]', 3)doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.') # Now save the document to a location doc.save('gfg.docx') Output: To apply paragraph spacing to the paragraphs in the Word document we make use of .paragraph_format along with .space_before and .space_after. It specifies the space to be left before and after the paragraph respectively. It can only take the positive value as input, if we give any negative value it will give range error. Sr. No. Spacing Description 1. .space_before It adds space before the paragraph in the word document. 2. .space_after It adds space after the paragraph in the word document. Example 3: Adding paragraph with and without spacing in a Word document. Python3 # Import docx NOT python-docximport docxfrom docx.shared import Inches # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding paragraph with spacingdoc.add_heading('Paragraph Spacing: Para-1 [With Spacing]', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')# Adding space before and after of the paragraphpara.paragraph_format.space_before = Inches(0.25)para.paragraph_format.space_after = Inches(0.25) # Adding paragraph without spacingdoc.add_heading('Paragraph Spacing: Para-2 [Without Spacing]', 3)doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.') # Now save the document to a location doc.save('gfg.docx') Output: To set the horizontal alignment in the text we will use the .paragraph_format.alignment method. It is used along with WD_PARAGRAPH_ALIGNMENT to set the alignment of the paragraph. You have to import WD_PARAGRAPH_ALIGNMENT from the docx.enum.text before using it: from docx.enum.text import WD_ALIGN_PARAGRAPH Syntax: para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.[Alignment] Parameter: Alignment: It is used to set the alignment. You can set the alignment to any of the left, Centre, right, or fully justified. Various alignments are described below: Sr. No. Alignment Name Description 1. CENTER It sets the alignment to Centre. 2. LEFT It sets the alignment to left. 3. RIGHT It sets the alignment to right. 4. JUSTIFY It sets the alignment to justify. 5. DISTRIBUTE It sets the characters in such a way that they fill the entire width of the paragraph. Example 1: Adding paragraphs with different Horizontal Alignments. Python3 # Import docx NOT python-docximport docxfrom docx.enum.text import WD_ALIGN_PARAGRAPH # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding paragraph with alignment Centerdoc.add_heading('Alignment: Center', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER # Adding paragraph with alignment Leftdoc.add_heading('Alignment: Left', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.LEFT # Adding paragraph with alignment Rightdoc.add_heading('Alignment: Right', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.RIGHT # Adding paragraph with alignment Justifydoc.add_heading('Alignment: Justify', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY # Adding paragraph with alignment Distributedoc.add_heading('Alignment: Distribute', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.DISTRIBUTE # Now save the document to a location doc.save('gfg.docx') Output: To set the indentation in the text we will use the .paragraph_format method. To apply indentation we use left_indent and right_indent with the .paragraph_format and set the value of the indentation. You have to specify indentation with a length value i.e inches, pt or cm. You can also give a negative value as indentation which will cause the paragraph to overlap with the margin by the value specified. Sr. No. Indentation Description 1. left_indent It sets the left indentation of the paragraph in the word file. 2. right_indent It sets the right indentation of the paragraph in the word file. Syntax: For the left indentation: para.paragraph_format.left_indent = size For the right indentation: para.paragraph_format.right_indent = size Parameter: size: It is the value by which we want indentation on our paragraph. It can be in inches, pt or cm... etc. Example 2: Setting left and right indentation of the paragraph. Python3 # Import docx NOT python-docximport docxfrom docx.shared import Inches # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding paragraph with left Indentationdoc.add_heading('Indentation: Left', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal \for geeks. It contains well written, well thought and well-explained \computer science and programming articles, quizzes etc.')para.paragraph_format.left_indent = Inches(0.5) # Adding paragraph with right Indentationdoc.add_heading('Indentation: Right', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal\for geeks. It contains well written, well thought and well-explained\computer science and programming articles, quizzes etc.')para.paragraph_format.right_indent = Inches(0.5) # Now save the document to a location doc.save('gfg.docx') Output: Example 3: Setting a negative value for the left and right indentation of the paragraph. Python3 # Import docx NOT python-docximport docxfrom docx.shared import Inches # Create an instance of a word documentdoc = docx.Document() # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Adding paragraph with negative left Indentationdoc.add_heading('Indentation: Left', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal \for geeks. It contains well written, well thought and well-explained\computer science and programming articles, quizzes etc.')para.paragraph_format.left_indent = Inches(-0.5) # Adding paragraph with negative right Indentationdoc.add_heading('Indentation: Right', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal\for geeks. It contains well written, well thought and well-explained\computer science and programming articles, quizzes etc.')para.paragraph_format.right_indent = Inches(-0.5) # Now save the document to a locationdoc.save('gfg.docx') Output: You can also set indentation only for the first line of the paragraph by using .paragraph_format along with .first_line_indent property. It specifies the indentation length between the first line and the other lines. Syntax: para.paragraph_format. first_line_indent = Length Parameters: Length: It is the length to be left as indentation at the first line. A positive value will cause the line to indent while the negative value will cause hanging indentation. Example 4: Giving positive indentation value as input for the first-line indentation. Python3 # Import docx NOT python-docximport docxfrom docx.shared import Inches # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding paragraph with only first line Indenteddoc.add_heading('Indentation: First Line', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science\portal for geeks. It contains well written, well thought and \well-explained computer science and programming articles, quizzes etc.') # Causing First Line Indentationpara.paragraph_format. first_line_indent = Inches(0.5) # Now save the document to a location doc.save('gfg.docx') Output: Example 5: Giving negative indentation value as input for the first-line indentation. Python3 # Import docx NOT python-docximport docxfrom docx.shared import Inches # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding paragraph with only first line Indenteddoc.add_heading('Indentation: First Line', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.') # Causing First Line Indentationpara.paragraph_format. first_line_indent = Inches(-0.5) # Now save the document to a location doc.save('gfg.docx') Output: Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python sum() function in Python Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 24291, "s": 24263, "text": "\n03 Jan, 2021" }, { "code": null, "e": 24331, "s": 24291, "text": "Prerequisite: Working with .docx module" }, { "code": null, "e": 24695, "s": 24331, "text": "Word documents contain formatted text wrapped within three object levels. The Lowest level- run objects, middle level- paragraph objects, and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. Pip command to install this module is:" }, { "code": null, "e": 24719, "s": 24695, "text": "pip install python-docx" }, { "code": null, "e": 24953, "s": 24719, "text": "Python docx module allows users to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend." }, { "code": null, "e": 25136, "s": 24953, "text": "To set the line spacing between the text in the paragraph we make use of the paragraph_format along with line_spacing. It is used to set the space between each line in the paragraph." }, { "code": null, "e": 25188, "s": 25136, "text": "Syntax: para.paragraph_format.line_spacing = Length" }, { "code": null, "e": 25560, "s": 25188, "text": "Parameter: Length: It is the length of the space to be left between the lines. It takes length as an input. It can be defined either with an absolute distance value or with a relative distance value of the line-height. If the input is in pt, inches or cm then it considered them as an absolute value and if the input is in float then it is considered as a relative value." }, { "code": null, "e": 25626, "s": 25560, "text": "Example 1: Setting the line spacing with absolute distance value." }, { "code": null, "e": 25634, "s": 25626, "text": "Python3" }, { "code": "# Import docx NOT python-docximport docxfrom docx.shared import Inches # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding paragraph with spacingdoc.add_heading('Line Spacing: Para-1 [With Spacing]', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.')# Adding line space of 0.5 inches in the paragraphpara.paragraph_format.line_spacing = Inches(0.5) # Adding paragraph without spacingdoc.add_heading('Line Spacing: Para-2 [Without Spacing]', 3)doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.') # Now save the document to a location doc.save('gfg.docx')", "e": 26561, "s": 25634, "text": null }, { "code": null, "e": 26569, "s": 26561, "text": "Output:" }, { "code": null, "e": 26626, "s": 26569, "text": "Example 2: Setting the line spacing with relative value." }, { "code": null, "e": 26634, "s": 26626, "text": "Python3" }, { "code": "# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding paragraph with spacingdoc.add_heading('Line Spacing: Para-1 [With Spacing]', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.')# Adding line space in the paragraphpara.paragraph_format.line_spacing = 1.75 # Adding paragraph without spacingdoc.add_heading('Line Spacing: Para-2 [Without Spacing]', 3)doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.') # Now save the document to a location doc.save('gfg.docx')", "e": 27510, "s": 26634, "text": null }, { "code": null, "e": 27518, "s": 27510, "text": "Output:" }, { "code": null, "e": 27841, "s": 27518, "text": "To apply paragraph spacing to the paragraphs in the Word document we make use of .paragraph_format along with .space_before and .space_after. It specifies the space to be left before and after the paragraph respectively. It can only take the positive value as input, if we give any negative value it will give range error." }, { "code": null, "e": 27849, "s": 27841, "text": "Sr. No." }, { "code": null, "e": 27857, "s": 27849, "text": "Spacing" }, { "code": null, "e": 27869, "s": 27857, "text": "Description" }, { "code": null, "e": 27872, "s": 27869, "text": "1." }, { "code": null, "e": 27886, "s": 27872, "text": ".space_before" }, { "code": null, "e": 27943, "s": 27886, "text": "It adds space before the paragraph in the word document." }, { "code": null, "e": 27946, "s": 27943, "text": "2." }, { "code": null, "e": 27959, "s": 27946, "text": ".space_after" }, { "code": null, "e": 28015, "s": 27959, "text": "It adds space after the paragraph in the word document." }, { "code": null, "e": 28088, "s": 28015, "text": "Example 3: Adding paragraph with and without spacing in a Word document." }, { "code": null, "e": 28096, "s": 28088, "text": "Python3" }, { "code": "# Import docx NOT python-docximport docxfrom docx.shared import Inches # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding paragraph with spacingdoc.add_heading('Paragraph Spacing: Para-1 [With Spacing]', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')# Adding space before and after of the paragraphpara.paragraph_format.space_before = Inches(0.25)para.paragraph_format.space_after = Inches(0.25) # Adding paragraph without spacingdoc.add_heading('Paragraph Spacing: Para-2 [Without Spacing]', 3)doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.') # Now save the document to a location doc.save('gfg.docx')", "e": 28852, "s": 28096, "text": null }, { "code": null, "e": 28860, "s": 28852, "text": "Output:" }, { "code": null, "e": 29123, "s": 28860, "text": "To set the horizontal alignment in the text we will use the .paragraph_format.alignment method. It is used along with WD_PARAGRAPH_ALIGNMENT to set the alignment of the paragraph. You have to import WD_PARAGRAPH_ALIGNMENT from the docx.enum.text before using it:" }, { "code": null, "e": 29169, "s": 29123, "text": "from docx.enum.text import WD_ALIGN_PARAGRAPH" }, { "code": null, "e": 29242, "s": 29169, "text": "Syntax: para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.[Alignment]" }, { "code": null, "e": 29254, "s": 29242, "text": "Parameter: " }, { "code": null, "e": 29379, "s": 29254, "text": "Alignment: It is used to set the alignment. You can set the alignment to any of the left, Centre, right, or fully justified." }, { "code": null, "e": 29419, "s": 29379, "text": "Various alignments are described below:" }, { "code": null, "e": 29427, "s": 29419, "text": "Sr. No." }, { "code": null, "e": 29442, "s": 29427, "text": "Alignment Name" }, { "code": null, "e": 29454, "s": 29442, "text": "Description" }, { "code": null, "e": 29457, "s": 29454, "text": "1." }, { "code": null, "e": 29464, "s": 29457, "text": "CENTER" }, { "code": null, "e": 29497, "s": 29464, "text": "It sets the alignment to Centre." }, { "code": null, "e": 29500, "s": 29497, "text": "2." }, { "code": null, "e": 29505, "s": 29500, "text": "LEFT" }, { "code": null, "e": 29536, "s": 29505, "text": "It sets the alignment to left." }, { "code": null, "e": 29539, "s": 29536, "text": "3." }, { "code": null, "e": 29545, "s": 29539, "text": "RIGHT" }, { "code": null, "e": 29577, "s": 29545, "text": "It sets the alignment to right." }, { "code": null, "e": 29580, "s": 29577, "text": "4." }, { "code": null, "e": 29588, "s": 29580, "text": "JUSTIFY" }, { "code": null, "e": 29622, "s": 29588, "text": "It sets the alignment to justify." }, { "code": null, "e": 29625, "s": 29622, "text": "5." }, { "code": null, "e": 29636, "s": 29625, "text": "DISTRIBUTE" }, { "code": null, "e": 29723, "s": 29636, "text": "It sets the characters in such a way that they fill the entire width of the paragraph." }, { "code": null, "e": 29790, "s": 29723, "text": "Example 1: Adding paragraphs with different Horizontal Alignments." }, { "code": null, "e": 29798, "s": 29790, "text": "Python3" }, { "code": "# Import docx NOT python-docximport docxfrom docx.enum.text import WD_ALIGN_PARAGRAPH # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding paragraph with alignment Centerdoc.add_heading('Alignment: Center', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER # Adding paragraph with alignment Leftdoc.add_heading('Alignment: Left', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.LEFT # Adding paragraph with alignment Rightdoc.add_heading('Alignment: Right', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.RIGHT # Adding paragraph with alignment Justifydoc.add_heading('Alignment: Justify', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY # Adding paragraph with alignment Distributedoc.add_heading('Alignment: Distribute', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks.')para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.DISTRIBUTE # Now save the document to a location doc.save('gfg.docx')", "e": 31184, "s": 29798, "text": null }, { "code": null, "e": 31192, "s": 31184, "text": "Output:" }, { "code": null, "e": 31597, "s": 31192, "text": "To set the indentation in the text we will use the .paragraph_format method. To apply indentation we use left_indent and right_indent with the .paragraph_format and set the value of the indentation. You have to specify indentation with a length value i.e inches, pt or cm. You can also give a negative value as indentation which will cause the paragraph to overlap with the margin by the value specified." }, { "code": null, "e": 31605, "s": 31597, "text": "Sr. No." }, { "code": null, "e": 31617, "s": 31605, "text": "Indentation" }, { "code": null, "e": 31629, "s": 31617, "text": "Description" }, { "code": null, "e": 31632, "s": 31629, "text": "1." }, { "code": null, "e": 31644, "s": 31632, "text": "left_indent" }, { "code": null, "e": 31708, "s": 31644, "text": "It sets the left indentation of the paragraph in the word file." }, { "code": null, "e": 31711, "s": 31708, "text": "2." }, { "code": null, "e": 31724, "s": 31711, "text": "right_indent" }, { "code": null, "e": 31789, "s": 31724, "text": "It sets the right indentation of the paragraph in the word file." }, { "code": null, "e": 31797, "s": 31789, "text": "Syntax:" }, { "code": null, "e": 31864, "s": 31797, "text": "For the left indentation: para.paragraph_format.left_indent = size" }, { "code": null, "e": 31933, "s": 31864, "text": "For the right indentation: para.paragraph_format.right_indent = size" }, { "code": null, "e": 31945, "s": 31933, "text": "Parameter: " }, { "code": null, "e": 32052, "s": 31945, "text": "size: It is the value by which we want indentation on our paragraph. It can be in inches, pt or cm... etc." }, { "code": null, "e": 32116, "s": 32052, "text": "Example 2: Setting left and right indentation of the paragraph." }, { "code": null, "e": 32124, "s": 32116, "text": "Python3" }, { "code": "# Import docx NOT python-docximport docxfrom docx.shared import Inches # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding paragraph with left Indentationdoc.add_heading('Indentation: Left', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal \\for geeks. It contains well written, well thought and well-explained \\computer science and programming articles, quizzes etc.')para.paragraph_format.left_indent = Inches(0.5) # Adding paragraph with right Indentationdoc.add_heading('Indentation: Right', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal\\for geeks. It contains well written, well thought and well-explained\\computer science and programming articles, quizzes etc.')para.paragraph_format.right_indent = Inches(0.5) # Now save the document to a location doc.save('gfg.docx')", "e": 33035, "s": 32124, "text": null }, { "code": null, "e": 33043, "s": 33035, "text": "Output:" }, { "code": null, "e": 33132, "s": 33043, "text": "Example 3: Setting a negative value for the left and right indentation of the paragraph." }, { "code": null, "e": 33140, "s": 33132, "text": "Python3" }, { "code": "# Import docx NOT python-docximport docxfrom docx.shared import Inches # Create an instance of a word documentdoc = docx.Document() # Add a Title to the documentdoc.add_heading('GeeksForGeeks', 0) # Adding paragraph with negative left Indentationdoc.add_heading('Indentation: Left', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal \\for geeks. It contains well written, well thought and well-explained\\computer science and programming articles, quizzes etc.')para.paragraph_format.left_indent = Inches(-0.5) # Adding paragraph with negative right Indentationdoc.add_heading('Indentation: Right', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal\\for geeks. It contains well written, well thought and well-explained\\computer science and programming articles, quizzes etc.')para.paragraph_format.right_indent = Inches(-0.5) # Now save the document to a locationdoc.save('gfg.docx')", "e": 34068, "s": 33140, "text": null }, { "code": null, "e": 34076, "s": 34068, "text": "Output:" }, { "code": null, "e": 34294, "s": 34076, "text": "You can also set indentation only for the first line of the paragraph by using .paragraph_format along with .first_line_indent property. It specifies the indentation length between the first line and the other lines." }, { "code": null, "e": 34352, "s": 34294, "text": "Syntax: para.paragraph_format. first_line_indent = Length" }, { "code": null, "e": 34365, "s": 34352, "text": "Parameters: " }, { "code": null, "e": 34539, "s": 34365, "text": "Length: It is the length to be left as indentation at the first line. A positive value will cause the line to indent while the negative value will cause hanging indentation." }, { "code": null, "e": 34625, "s": 34539, "text": "Example 4: Giving positive indentation value as input for the first-line indentation." }, { "code": null, "e": 34633, "s": 34625, "text": "Python3" }, { "code": "# Import docx NOT python-docximport docxfrom docx.shared import Inches # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding paragraph with only first line Indenteddoc.add_heading('Indentation: First Line', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science\\portal for geeks. It contains well written, well thought and \\well-explained computer science and programming articles, quizzes etc.') # Causing First Line Indentationpara.paragraph_format. first_line_indent = Inches(0.5) # Now save the document to a location doc.save('gfg.docx')", "e": 35272, "s": 34633, "text": null }, { "code": null, "e": 35280, "s": 35272, "text": "Output:" }, { "code": null, "e": 35366, "s": 35280, "text": "Example 5: Giving negative indentation value as input for the first-line indentation." }, { "code": null, "e": 35374, "s": 35366, "text": "Python3" }, { "code": "# Import docx NOT python-docximport docxfrom docx.shared import Inches # Create an instance of a word documentdoc = docx.Document() # Add a Title to the document doc.add_heading('GeeksForGeeks', 0) # Adding paragraph with only first line Indenteddoc.add_heading('Indentation: First Line', 3)para = doc.add_paragraph('GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.') # Causing First Line Indentationpara.paragraph_format. first_line_indent = Inches(-0.5) # Now save the document to a location doc.save('gfg.docx')", "e": 36013, "s": 35374, "text": null }, { "code": null, "e": 36021, "s": 36013, "text": "Output:" }, { "code": null, "e": 36045, "s": 36021, "text": "Technical Scripter 2020" }, { "code": null, "e": 36052, "s": 36045, "text": "Python" }, { "code": null, "e": 36071, "s": 36052, "text": "Technical Scripter" }, { "code": null, "e": 36169, "s": 36071, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36178, "s": 36169, "text": "Comments" }, { "code": null, "e": 36191, "s": 36178, "text": "Old Comments" }, { "code": null, "e": 36209, "s": 36191, "text": "Python Dictionary" }, { "code": null, "e": 36244, "s": 36209, "text": "Read a file line by line in Python" }, { "code": null, "e": 36266, "s": 36244, "text": "Enumerate() in Python" }, { "code": null, "e": 36298, "s": 36266, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 36340, "s": 36298, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 36366, "s": 36340, "text": "Python String | replace()" }, { "code": null, "e": 36410, "s": 36366, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 36435, "s": 36410, "text": "sum() function in Python" }, { "code": null, "e": 36472, "s": 36435, "text": "Create a Pandas DataFrame from Lists" } ]
SAS - Standard Deviation
Standard deviation (SD) is a measure of how varied is the data in a data set. Mathematically it measures how distant or close are each value to the mean value of a data set. A standard deviation value close to 0 indicates that the data points tend to be very close to the mean of the data set and a high standard deviation indicates that the data points are spread out over a wider range of values In SAS the SD values is measured using PROC MEAN as well as PROC SURVEYMEANS. To measure the SD using proc means we choose the STD option in the PROC step. It brings out the SD values for each numeric variable present in the data set. The basic syntax for calculating standard deviation in SAS is − PROC means DATA = dataset STD; Following is the description of the parameters used − Dataset − is the name of the dataset. Dataset − is the name of the dataset. In the below example we create the data set CARS1 form the CARS data set in the SASHELP library. We choose the STD option with the PROC means step. PROC SQL; create table CARS1 as SELECT make, type, invoice, horsepower, length, weight FROM SASHELP.CARS WHERE make in ('Audi','BMW') ; RUN; proc means data = CARS1 STD; run; When we execute the above code it gives the following output − This procedure is also used for measurement of SD along with some advance features like measuring SD for categorical variables as well as provide estimates in variance. The syntax for using PROC SURVEYMEANS is − PROC SURVEYMEANS options statistic-keywords ; BY variables ; CLASS variables ; VAR variables ; Following is the description of the parameters used − BY − indicates the variables used to create groups of observations. BY − indicates the variables used to create groups of observations. CLASS − indicates the variables used for categorical variables. CLASS − indicates the variables used for categorical variables. VAR − indicates the variables for which SD will be calculated. VAR − indicates the variables for which SD will be calculated. The below example describes the use of class option which creates the statistics for each of the values in the class variable. proc surveymeans data = CARS1 STD; class type; var type horsepower; ods output statistics = rectangle; run; proc print data = rectangle; run; When we execute the above code it gives the following output − The below code gives example of BY option. In it the result is grouped for each value in the BY option. proc surveymeans data = CARS1 STD; var horsepower; BY make; ods output statistics = rectangle; run; proc print data = rectangle; run; When we execute the above code it gives the following output − 50 Lectures 5.5 hours Code And Create 124 Lectures 30 hours Juan Galvan 162 Lectures 31.5 hours Yossef Ayman Zedan 35 Lectures 2.5 hours Ermin Dedic 167 Lectures 45.5 hours Muslim Helalee Print Add Notes Bookmark this page
[ { "code": null, "e": 2981, "s": 2583, "text": "Standard deviation (SD) is a measure of how varied is the data in a data set. Mathematically it measures how distant or close are each value to the mean value of a data set. A standard deviation value close to 0 indicates that the data points tend to be very close to the mean of the data set and a high standard deviation indicates that the data points are spread out over a wider range of values" }, { "code": null, "e": 3059, "s": 2981, "text": "In SAS the SD values is measured using PROC MEAN as well as PROC SURVEYMEANS." }, { "code": null, "e": 3216, "s": 3059, "text": "To measure the SD using proc means we choose the STD option in the PROC step. It brings out the SD values for each numeric variable present in the data set." }, { "code": null, "e": 3280, "s": 3216, "text": "The basic syntax for calculating standard deviation in SAS is −" }, { "code": null, "e": 3312, "s": 3280, "text": "PROC means DATA = dataset STD;\n" }, { "code": null, "e": 3366, "s": 3312, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 3404, "s": 3366, "text": "Dataset − is the name of the dataset." }, { "code": null, "e": 3442, "s": 3404, "text": "Dataset − is the name of the dataset." }, { "code": null, "e": 3590, "s": 3442, "text": "In the below example we create the data set CARS1 form the CARS data set in the SASHELP library. We choose the STD option with the PROC means step." }, { "code": null, "e": 3777, "s": 3590, "text": "PROC SQL;\ncreate table CARS1 as\nSELECT make, type, invoice, horsepower, length, weight\n FROM \n SASHELP.CARS\n WHERE make in ('Audi','BMW')\n;\nRUN;\n\nproc means data = CARS1 STD;\nrun;\n" }, { "code": null, "e": 3840, "s": 3777, "text": "When we execute the above code it gives the following output −" }, { "code": null, "e": 4009, "s": 3840, "text": "This procedure is also used for measurement of SD along with some advance features like measuring SD for categorical variables as well as provide estimates in variance." }, { "code": null, "e": 4052, "s": 4009, "text": "The syntax for using PROC SURVEYMEANS is −" }, { "code": null, "e": 4148, "s": 4052, "text": "PROC SURVEYMEANS options statistic-keywords ;\nBY variables ;\nCLASS variables ;\nVAR variables ;\n" }, { "code": null, "e": 4202, "s": 4148, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 4270, "s": 4202, "text": "BY − indicates the variables used to create groups of observations." }, { "code": null, "e": 4338, "s": 4270, "text": "BY − indicates the variables used to create groups of observations." }, { "code": null, "e": 4402, "s": 4338, "text": "CLASS − indicates the variables used for categorical variables." }, { "code": null, "e": 4466, "s": 4402, "text": "CLASS − indicates the variables used for categorical variables." }, { "code": null, "e": 4529, "s": 4466, "text": "VAR − indicates the variables for which SD will be calculated." }, { "code": null, "e": 4592, "s": 4529, "text": "VAR − indicates the variables for which SD will be calculated." }, { "code": null, "e": 4719, "s": 4592, "text": "The below example describes the use of class option which creates the statistics for each of the values in the class variable." }, { "code": null, "e": 4862, "s": 4719, "text": "proc surveymeans data = CARS1 STD;\nclass type;\nvar type horsepower;\nods output statistics = rectangle;\nrun;\nproc print data = rectangle;\nrun;\n" }, { "code": null, "e": 4925, "s": 4862, "text": "When we execute the above code it gives the following output −" }, { "code": null, "e": 5029, "s": 4925, "text": "The below code gives example of BY option. In it the result is grouped for each value in the BY option." }, { "code": null, "e": 5164, "s": 5029, "text": "proc surveymeans data = CARS1 STD;\nvar horsepower;\nBY make;\nods output statistics = rectangle;\nrun;\nproc print data = rectangle;\nrun;\n" }, { "code": null, "e": 5227, "s": 5164, "text": "When we execute the above code it gives the following output −" }, { "code": null, "e": 5262, "s": 5227, "text": "\n 50 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5279, "s": 5262, "text": " Code And Create" }, { "code": null, "e": 5314, "s": 5279, "text": "\n 124 Lectures \n 30 hours \n" }, { "code": null, "e": 5327, "s": 5314, "text": " Juan Galvan" }, { "code": null, "e": 5364, "s": 5327, "text": "\n 162 Lectures \n 31.5 hours \n" }, { "code": null, "e": 5384, "s": 5364, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 5419, "s": 5384, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5432, "s": 5419, "text": " Ermin Dedic" }, { "code": null, "e": 5469, "s": 5432, "text": "\n 167 Lectures \n 45.5 hours \n" }, { "code": null, "e": 5485, "s": 5469, "text": " Muslim Helalee" }, { "code": null, "e": 5492, "s": 5485, "text": " Print" }, { "code": null, "e": 5503, "s": 5492, "text": " Add Notes" } ]
Intersection of two sorted Linked lists | Practice | GeeksforGeeks
Given two lists sorted in increasing order, create a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed. Note: The list elements are not necessarily distinct. Example 1: Input: L1 = 1->2->3->4->6 L2 = 2->4->6->8 Output: 2 4 6 Explanation: For the given first two linked list, 2, 4 and 6 are the elements in the intersection. Example 2: Input: L1 = 10->20->40->50 L2 = 15->40 Output: 40 Your Task: The task is to complete the function intersection() which should find the intersection of two linked list and add all the elements in intersection to the third linked list and return the head of the third linked list. Expected Time Complexity : O(n+m) Expected Auxilliary Space : O(n+m) Note: n,m are the size of the linked lists. Constraints: 1 <= size of linked lists <= 5000 1 <= Data in linked list nodes <= 1000 0 bhavinraichura28in 7 hours C++ solution Node* findIntersection(Node* head1, Node* head2){ // Your Code Here Node *temp,*l1,*l2,*l3; l3=new Node(0); l1 = head1; l2=head2; temp=l3; while(l1!=NULL && l2!=NULL){ if (l1->data == l2->data){ temp->next=new Node(l1->data); temp=temp->next; l2= l2->next; l1= l1->next; } else if(l1->data > l2->data) l2= l2->next; else l1=l1->next; } return l3->next;} 0 deeptimayeemaharana06 This comment was deleted. +2 shahabuddinbravo404 days ago Node* findIntersection(Node* head1, Node* head2){ Node *ptr1=head1,*ptr2=head2; unordered_set<int>s; while(ptr2){ s.insert(ptr2->data); ptr2=ptr2->next; } Node *list= new Node(-1),*head=list; while(ptr1) { // auto it=s.find(ptr1->data); // if(it!=s.end()){ // list->next=ptr1; // list=list->next; // } // ptr1=ptr1->next; auto it=s.find(ptr1->data); if(it!=s.end()){ Node *temp=new Node(ptr1->data); list->next=temp; list=list->next; } ptr1=ptr1->next; } //list->next=NULL; head=head->next; return head;} +1 2019sushilkumarkori4 days ago Node* findIntersection(Node* head1, Node* head2) { Node* temp1 = head1; Node* temp2 = head2; Node* new_head = new Node(0); Node* temp3 = new_head; while(temp1!=NULL && temp2!=NULL){ if(temp1->data > temp2->data){ temp2=temp2->next; } else if(temp1->data < temp2->data){ temp1=temp1->next; } else{ temp3->next=new Node(temp1->data); temp3=temp3->next; temp1=temp1->next; temp2=temp2->next; } } temp3->next = NULL; return new_head->next; } 0 sy9924554 days ago HashSet<Integer> set = new HashSet<>(); while(head2 != null){ set.add(head2.data); head2 = head2.next; } Node dummy = new Node(-1); Node itr = dummy; while(head1 != null){ if(set.contains(head1.data)){ itr.next = new Node(head1.data); itr = itr.next; } head1 = head1.next; } return dummy.next; +1 mohitraj27414 days ago Note: Vector c stores common elements. Node* findIntersection(Node* head1, Node* head2){ // Your Code Here vector<int>c; Node* temp1=head1; Node* temp2=head2; while(temp1!=NULL && temp2!=NULL) { if(temp1->data < temp2->data) temp1=temp1->next; else if(temp1->data > temp2->data) temp2=temp2->next; else { c.push_back(temp1->data); temp1=temp1->next; temp2=temp2->next; } } Node* t = new Node(0); Node* h=t; int k=0; while(k!=c.size()) { h->next=new Node(c[k]); h=h->next; k++; } h->next=NULL; return t->next; } 0 codewithaddy6 days ago C++ Solution Time Taken: 0.08 sec Node* findIntersection(Node* head1, Node* head2) { Node* t1=head1; Node* t2=head2; vector<int> v; while(t1 && t2){ if(t1->data==t2->data){ v.push_back(t1->data); t1=t1->next; t2=t2->next; } else if(t1->data<t2->data){ t1=t1->next; } else{ t2=t2->next; } } Node* q=new Node(v[0]); Node* it=q; for(int i=1; i<v.size();i++){ it->next=new Node(v[i]); it=it->next; } return q; } 0 09himanshusah6 days ago JavaScript Solution class Solution { findIntersection(head1, head2) { //your code here let dummy = new Node(-1); let tail = dummy; let l1 = head1; let l2 = head2; while(l1 !== null && l1 !== null) { if(l1.data == l2.data) { tail.next = l1; tail = l1; l1 = l1.next; l2 = l2.next; } else if(l1.data < l2.data) { l1= l1.next; } else { l2 = l2.next; } } return dummy.next; } } 0 gamerextension0072 weeks ago Update your solution to fulfill the disclaimer note 5 4 1 2 2 4 62 2 6 8 Your solution would output wrong for this 0 tthakare732 weeks ago //Java Solution TC -> 1.17 //hint -> Two pointer Approch class Sol{ public static Node findIntersection(Node head1, Node head2){ Node Result = null, dummy = null; while(head1 != null && head2 != null){ if(head1.data == head2.data){ Node NewNode = new Node(head1.data); if(Result == null){ Result = NewNode; dummy = NewNode; } else { dummy.next = NewNode; dummy = dummy.next; } head1 = head1.next; head2 = head2.next; } else { if(head1.data < head2.data) head1 = head1.next; else head2 = head2.next; } } return Result; } } 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": 494, "s": 238, "text": "Given two lists sorted in increasing order, create a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed.\nNote: The list elements are not necessarily distinct." }, { "code": null, "e": 505, "s": 494, "text": "Example 1:" }, { "code": null, "e": 660, "s": 505, "text": "Input:\nL1 = 1->2->3->4->6\nL2 = 2->4->6->8\nOutput: 2 4 6\nExplanation: For the given first two\nlinked list, 2, 4 and 6 are the elements\nin the intersection." }, { "code": null, "e": 671, "s": 660, "text": "Example 2:" }, { "code": null, "e": 722, "s": 671, "text": "Input:\nL1 = 10->20->40->50\nL2 = 15->40\nOutput: 40\n" }, { "code": null, "e": 951, "s": 722, "text": "Your Task:\nThe task is to complete the function intersection() which should find the intersection of two linked list and add all the elements in intersection to the third linked list and return the head of the third linked list." }, { "code": null, "e": 1064, "s": 951, "text": "Expected Time Complexity : O(n+m)\nExpected Auxilliary Space : O(n+m)\nNote: n,m are the size of the linked lists." }, { "code": null, "e": 1150, "s": 1064, "text": "Constraints:\n1 <= size of linked lists <= 5000\n1 <= Data in linked list nodes <= 1000" }, { "code": null, "e": 1152, "s": 1150, "text": "0" }, { "code": null, "e": 1179, "s": 1152, "text": "bhavinraichura28in 7 hours" }, { "code": null, "e": 1192, "s": 1179, "text": "C++ solution" }, { "code": null, "e": 1657, "s": 1194, "text": "Node* findIntersection(Node* head1, Node* head2){ // Your Code Here Node *temp,*l1,*l2,*l3; l3=new Node(0); l1 = head1; l2=head2; temp=l3; while(l1!=NULL && l2!=NULL){ if (l1->data == l2->data){ temp->next=new Node(l1->data); temp=temp->next; l2= l2->next; l1= l1->next; } else if(l1->data > l2->data) l2= l2->next; else l1=l1->next; } return l3->next;}" }, { "code": null, "e": 1659, "s": 1657, "text": "0" }, { "code": null, "e": 1681, "s": 1659, "text": "deeptimayeemaharana06" }, { "code": null, "e": 1707, "s": 1681, "text": "This comment was deleted." }, { "code": null, "e": 1710, "s": 1707, "text": "+2" }, { "code": null, "e": 1739, "s": 1710, "text": "shahabuddinbravo404 days ago" }, { "code": null, "e": 2426, "s": 1739, "text": "Node* findIntersection(Node* head1, Node* head2){ Node *ptr1=head1,*ptr2=head2; unordered_set<int>s; while(ptr2){ s.insert(ptr2->data); ptr2=ptr2->next; } Node *list= new Node(-1),*head=list; while(ptr1) { // auto it=s.find(ptr1->data); // if(it!=s.end()){ // list->next=ptr1; // list=list->next; // } // ptr1=ptr1->next; auto it=s.find(ptr1->data); if(it!=s.end()){ Node *temp=new Node(ptr1->data); list->next=temp; list=list->next; } ptr1=ptr1->next; } //list->next=NULL; head=head->next; return head;}" }, { "code": null, "e": 2429, "s": 2426, "text": "+1" }, { "code": null, "e": 2459, "s": 2429, "text": "2019sushilkumarkori4 days ago" }, { "code": null, "e": 3087, "s": 2459, "text": "\nNode* findIntersection(Node* head1, Node* head2)\n{\n Node* temp1 = head1;\n Node* temp2 = head2;\n Node* new_head = new Node(0);\n Node* temp3 = new_head;\n while(temp1!=NULL && temp2!=NULL){\n if(temp1->data > temp2->data){\n temp2=temp2->next;\n }\n else if(temp1->data < temp2->data){\n temp1=temp1->next;\n }\n \n else{\n temp3->next=new Node(temp1->data);\n temp3=temp3->next;\n temp1=temp1->next;\n temp2=temp2->next;\n }\n \n }\n temp3->next = NULL;\n return new_head->next;\n }\n \n" }, { "code": null, "e": 3089, "s": 3087, "text": "0" }, { "code": null, "e": 3108, "s": 3089, "text": "sy9924554 days ago" }, { "code": null, "e": 3537, "s": 3108, "text": " HashSet<Integer> set = new HashSet<>();\n while(head2 != null){\n set.add(head2.data);\n head2 = head2.next;\n }\n Node dummy = new Node(-1);\n Node itr = dummy;\n while(head1 != null){\n if(set.contains(head1.data)){\n itr.next = new Node(head1.data);\n itr = itr.next;\n }\n head1 = head1.next;\n }\n return dummy.next;" }, { "code": null, "e": 3540, "s": 3537, "text": "+1" }, { "code": null, "e": 3563, "s": 3540, "text": "mohitraj27414 days ago" }, { "code": null, "e": 3602, "s": 3563, "text": "Note: Vector c stores common elements." }, { "code": null, "e": 4189, "s": 3602, "text": "Node* findIntersection(Node* head1, Node* head2){ // Your Code Here vector<int>c; Node* temp1=head1; Node* temp2=head2; while(temp1!=NULL && temp2!=NULL) { if(temp1->data < temp2->data) temp1=temp1->next; else if(temp1->data > temp2->data) temp2=temp2->next; else { c.push_back(temp1->data); temp1=temp1->next; temp2=temp2->next; } } Node* t = new Node(0); Node* h=t; int k=0; while(k!=c.size()) { h->next=new Node(c[k]); h=h->next; k++; } h->next=NULL; return t->next; }" }, { "code": null, "e": 4191, "s": 4189, "text": "0" }, { "code": null, "e": 4214, "s": 4191, "text": "codewithaddy6 days ago" }, { "code": null, "e": 4227, "s": 4214, "text": "C++ Solution" }, { "code": null, "e": 4248, "s": 4227, "text": "Time Taken: 0.08 sec" }, { "code": null, "e": 4796, "s": 4248, "text": "Node* findIntersection(Node* head1, Node* head2)\n{\n Node* t1=head1;\n Node* t2=head2;\n \n vector<int> v;\n while(t1 && t2){\n if(t1->data==t2->data){\n v.push_back(t1->data);\n t1=t1->next;\n t2=t2->next;\n }\n else if(t1->data<t2->data){\n t1=t1->next;\n }\n else{\n t2=t2->next;\n }\n }\n \n Node* q=new Node(v[0]);\n Node* it=q;\n for(int i=1; i<v.size();i++){\n it->next=new Node(v[i]);\n it=it->next;\n }\n return q;\n}" }, { "code": null, "e": 4798, "s": 4796, "text": "0" }, { "code": null, "e": 4822, "s": 4798, "text": "09himanshusah6 days ago" }, { "code": null, "e": 4842, "s": 4822, "text": "JavaScript Solution" }, { "code": null, "e": 5421, "s": 4842, "text": "class Solution {\n \n findIntersection(head1, head2)\n {\n //your code here\n let dummy = new Node(-1);\n let tail = dummy;\n let l1 = head1;\n let l2 = head2;\n while(l1 !== null && l1 !== null) {\n if(l1.data == l2.data) {\n tail.next = l1;\n tail = l1;\n l1 = l1.next;\n l2 = l2.next;\n } else if(l1.data < l2.data) {\n l1= l1.next;\n } else {\n l2 = l2.next;\n }\n }\n return dummy.next;\n }\n}\n" }, { "code": null, "e": 5423, "s": 5421, "text": "0" }, { "code": null, "e": 5452, "s": 5423, "text": "gamerextension0072 weeks ago" }, { "code": null, "e": 5504, "s": 5452, "text": "Update your solution to fulfill the disclaimer note" }, { "code": null, "e": 5508, "s": 5504, "text": "5 4" }, { "code": null, "e": 5525, "s": 5508, "text": "1 2 2 4 62 2 6 8" }, { "code": null, "e": 5567, "s": 5525, "text": "Your solution would output wrong for this" }, { "code": null, "e": 5569, "s": 5567, "text": "0" }, { "code": null, "e": 5591, "s": 5569, "text": "tthakare732 weeks ago" }, { "code": null, "e": 6429, "s": 5591, "text": "//Java Solution TC -> 1.17\n//hint -> Two pointer Approch\nclass Sol{\n public static Node findIntersection(Node head1, Node head2){\n Node Result = null, dummy = null;\n while(head1 != null && head2 != null){\n if(head1.data == head2.data){\n Node NewNode = new Node(head1.data);\n \n if(Result == null){\n Result = NewNode;\n dummy = NewNode;\n } else {\n dummy.next = NewNode;\n dummy = dummy.next;\n }\n \n head1 = head1.next;\n head2 = head2.next;\n } else {\n if(head1.data < head2.data) head1 = head1.next;\n else head2 = head2.next;\n }\n }\n return Result;\n }\n}" }, { "code": null, "e": 6575, "s": 6429, "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": 6611, "s": 6575, "text": " Login to access your submissions. " }, { "code": null, "e": 6621, "s": 6611, "text": "\nProblem\n" }, { "code": null, "e": 6631, "s": 6621, "text": "\nContest\n" }, { "code": null, "e": 6694, "s": 6631, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6842, "s": 6694, "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": 7050, "s": 6842, "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": 7156, "s": 7050, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to minus one column from another in an R matrix?
To minus one column from another in an R matrix, we first need to read the matrix as a data frame using as.data.frame then find minus the columns using minus sign and accessing the column of the data frame. To understand how it can be done look at the steps in below examples. Consider the below data frame − Live Demo M1<-matrix(rpois(40,8),ncol=2) M1 [,1] [,2] [1,] 10 5 [2,] 10 16 [3,] 7 7 [4,] 10 5 [5,] 9 9 [6,] 9 5 [7,] 8 11 [8,] 8 3 [9,] 10 11 [10,] 8 8 [11,] 5 11 [12,] 8 6 [13,] 7 9 [14,] 8 6 [15,] 10 10 [16,] 5 10 [17,] 6 9 [18,] 8 8 [19,] 7 13 [20,] 6 8 Reading the matrix M1 as data frame − M1<-as.data.frame(M1) M1 V1 V2 1 10 5 2 10 16 3 7 7 4 10 5 5 9 9 6 9 5 7 8 11 8 8 3 9 10 11 10 8 8 11 5 11 12 8 6 13 7 9 14 8 6 15 10 10 16 5 10 17 6 9 18 8 8 19 7 13 20 6 8 Finding the difference in columns V1 and V2 of M1 − M1$Difference<-(M1$V1-M1$V2) M1 V1 V2 Difference 1 10 5 5 2 10 16 -6 3 7 7 0 4 10 5 5 5 9 9 0 6 9 5 4 7 8 11 -3 8 8 3 5 9 10 11 -1 10 8 8 0 11 5 11 -6 12 8 6 2 13 7 9 -2 14 8 6 2 15 10 10 0 16 5 10 -5 17 6 9 -3 18 8 8 0 19 7 13 -6 20 6 8 -2 Live Demo M2<-matrix(rpois(40,5),ncol=2) M2 [,1] [,2] [1,] 8 7 [2,] 4 5 [3,] 3 6 [4,] 8 3 [5,] 3 4 [6,] 5 7 [7,] 4 4 [8,] 6 5 [9,] 4 6 [10,] 8 5 [11,] 5 5 [12,] 3 9 [13,] 3 3 [14,] 3 4 [15,] 8 6 [16,] 5 5 [17,] 7 8 [18,] 8 8 [19,] 0 6 [20,] 3 4 Finding the difference in columns V1 and V2 of M2 − M2<-as.data.frame(M2) M2 V1 V2 1 8 7 2 4 5 3 3 6 4 8 3 5 3 4 6 5 7 7 4 4 8 6 5 9 4 6 10 8 5 11 5 5 12 3 9 13 3 3 14 3 4 15 8 6 16 5 5 17 7 8 18 8 8 19 0 6 20 3 4 Finding the difference in columns V1 and V2 of M2 − M2$Difference<-(M2$V1-M2$V2) M2 V1 V2 Difference 1 8 7 1 2 4 5 -1 3 3 6 -3 4 8 3 5 5 3 4 -1 6 5 7 -2 7 4 4 0 8 6 5 1 9 4 6 -2 10 8 5 3 11 5 5 0 12 3 9 -6 13 3 3 0 14 3 4 -1 15 8 6 2 16 5 5 0 17 7 8 -1 18 8 8 0 19 0 6 -6 20 3 4 -1
[ { "code": null, "e": 1339, "s": 1062, "text": "To minus one column from another in an R matrix, we first need to read the matrix as a data frame using as.data.frame then find minus the columns using minus sign and accessing the column of the data frame. To understand how it can be done look at the steps in below examples." }, { "code": null, "e": 1371, "s": 1339, "text": "Consider the below data frame −" }, { "code": null, "e": 1382, "s": 1371, "text": " Live Demo" }, { "code": null, "e": 1416, "s": 1382, "text": "M1<-matrix(rpois(40,8),ncol=2)\nM1" }, { "code": null, "e": 1712, "s": 1416, "text": " [,1] [,2]\n[1,] 10 5\n[2,] 10 16\n[3,] 7 7\n[4,] 10 5\n[5,] 9 9\n[6,] 9 5\n[7,] 8 11\n[8,] 8 3\n[9,] 10 11\n[10,] 8 8\n[11,] 5 11\n[12,] 8 6\n[13,] 7 9\n[14,] 8 6\n[15,] 10 10\n[16,] 5 10\n[17,] 6 9\n[18,] 8 8\n[19,] 7 13\n[20,] 6 8" }, { "code": null, "e": 1750, "s": 1712, "text": "Reading the matrix M1 as data frame −" }, { "code": null, "e": 1775, "s": 1750, "text": "M1<-as.data.frame(M1)\nM1" }, { "code": null, "e": 1986, "s": 1775, "text": " V1 V2\n1 10 5\n2 10 16\n3 7 7\n4 10 5\n5 9 9\n6 9 5\n7 8 11\n8 8 3\n9 10 11\n10 8 8\n11 5 11\n12 8 6\n13 7 9\n14 8 6\n15 10 10\n16 5 10\n17 6 9\n18 8 8\n19 7 13\n20 6 8" }, { "code": null, "e": 2038, "s": 1986, "text": "Finding the difference in columns V1 and V2 of M1 −" }, { "code": null, "e": 2070, "s": 2038, "text": "M1$Difference<-(M1$V1-M1$V2)\nM1" }, { "code": null, "e": 2392, "s": 2070, "text": " V1 V2 Difference\n1 10 5 5\n2 10 16 -6\n3 7 7 0\n4 10 5 5\n5 9 9 0\n6 9 5 4\n7 8 11 -3\n8 8 3 5\n9 10 11 -1\n10 8 8 0\n11 5 11 -6\n12 8 6 2\n13 7 9 -2\n14 8 6 2\n15 10 10 0\n16 5 10 -5\n17 6 9 -3\n18 8 8 0\n19 7 13 -6\n20 6 8 -2" }, { "code": null, "e": 2403, "s": 2392, "text": " Live Demo" }, { "code": null, "e": 2437, "s": 2403, "text": "M2<-matrix(rpois(40,5),ncol=2)\nM2" }, { "code": null, "e": 2712, "s": 2437, "text": " [,1] [,2]\n[1,] 8 7\n[2,] 4 5\n[3,] 3 6\n[4,] 8 3\n[5,] 3 4\n[6,] 5 7\n[7,] 4 4\n[8,] 6 5\n[9,] 4 6\n[10,] 8 5\n[11,] 5 5\n[12,] 3 9\n[13,] 3 3\n[14,] 3 4\n[15,] 8 6\n[16,] 5 5\n[17,] 7 8\n[18,] 8 8\n[19,] 0 6\n[20,] 3 4" }, { "code": null, "e": 2764, "s": 2712, "text": "Finding the difference in columns V1 and V2 of M2 −" }, { "code": null, "e": 2789, "s": 2764, "text": "M2<-as.data.frame(M2)\nM2" }, { "code": null, "e": 2958, "s": 2789, "text": " V1 V2\n1 8 7\n2 4 5\n3 3 6\n4 8 3\n5 3 4\n6 5 7\n7 4 4\n8 6 5\n9 4 6\n10 8 5\n11 5 5\n12 3 9\n13 3 3\n14 3 4\n15 8 6\n16 5 5\n17 7 8\n18 8 8\n19 0 6\n20 3 4" }, { "code": null, "e": 3010, "s": 2958, "text": "Finding the difference in columns V1 and V2 of M2 −" }, { "code": null, "e": 3042, "s": 3010, "text": "M2$Difference<-(M2$V1-M2$V2)\nM2" }, { "code": null, "e": 3322, "s": 3042, "text": " V1 V2 Difference\n1 8 7 1\n2 4 5 -1\n3 3 6 -3\n4 8 3 5\n5 3 4 -1\n6 5 7 -2\n7 4 4 0\n8 6 5 1\n9 4 6 -2\n10 8 5 3\n11 5 5 0\n12 3 9 -6\n13 3 3 0\n14 3 4 -1\n15 8 6 2\n16 5 5 0\n17 7 8 -1\n18 8 8 0\n19 0 6 -6\n20 3 4 -1" } ]
Determine if a string has all Unique Characters - GeeksforGeeks
25 Apr, 2022 Given a string, determine if the string has all unique characters. Examples : Input : abcd10jk Output : true Input : hutg9mnd!nk9 Output : false Approach 1 – Brute Force technique: Run 2 loops with variable i and j. Compare str[i] and str[j]. If they become equal at any point, return false. Time Complexity: O(n2) C++ Java Python3 C# PHP Javascript // C++ program to illustrate string// with unique characters using// brute force technique#include <bits/stdc++.h>using namespace std; bool uniqueCharacters(string str){ // If at any time we encounter 2 // same characters, return false for (int i = 0; i < str.length() - 1; i++) { for (int j = i + 1; j < str.length(); j++) { if (str[i] == str[j]) { return false; } } } // If no duplicate characters encountered, // return true return true;} // driver codeint main(){ string str = "GeeksforGeeks"; if (uniqueCharacters(str)) { cout << "The String " << str << " has all unique characters\n"; } else { cout << "The String " << str << " has duplicate characters\n"; } return 0;}// This code is contributed by Divyam Madaan // Java program to illustrate string with// unique characters using brute force techniqueimport java.util.*; class GfG { boolean uniqueCharacters(String str) { // If at any time we encounter 2 same // characters, return false for (int i = 0; i < str.length(); i++) for (int j = i + 1; j < str.length(); j++) if (str.charAt(i) == str.charAt(j)) return false; // If no duplicate characters encountered, // return true return true; } public static void main(String args[]) { GfG obj = new GfG(); String input = "GeeksforGeeks"; if (obj.uniqueCharacters(input)) System.out.println("The String " + input + " has all unique characters"); else System.out.println("The String " + input + " has duplicate characters"); }} # Python program to illustrate string# with unique characters using# brute force technique def uniqueCharacters(str): # If at any time we encounter 2 # same characters, return false for i in range(len(str)): for j in range(i + 1,len(str)): if(str[i] == str[j]): return False; # If no duplicate characters # encountered, return true return True; # Driver Codestr = "GeeksforGeeks"; if(uniqueCharacters(str)): print("The String ", str," has all unique characters");else: print("The String ", str, " has duplicate characters"); # This code contributed by PrinciRaj1992 // C# program to illustrate string with// unique characters using brute force// techniqueusing System; public class GFG { static bool uniqueCharacters(String str) { // If at any time we encounter 2 // same characters, return false for (int i = 0; i < str.Length; i++) for (int j = i + 1; j < str.Length; j++) if (str[i] == str[j]) return false; // If no duplicate characters // encountered, return true return true; } public static void Main() { string input = "GeeksforGeeks"; if (uniqueCharacters(input) == true) Console.WriteLine("The String " + input + " has all unique characters"); else Console.WriteLine("The String " + input + " has duplicate characters"); }} // This code is contributed by shiv_bhakt. <?php// PHP program to illustrate string// with unique characters using// brute force technique function uniqueCharacters($str){ // If at any time we encounter 2 // same characters, return false for($i = 0; $i < strlen($str); $i++) { for($j = $i + 1; $j < strlen($str); $j++) { if($str[$i] == $str[$j]) { return false; } } } // If no duplicate characters // encountered, return true return true;} // Driver Code$str = "GeeksforGeeks"; if(uniqueCharacters($str)){ echo "The String ", $str, " has all unique characters\n";}else{ echo "The String ", $str, " has duplicate characters\n";} // This code is contributed by ajit?> <script> // Javascript program to illustrate string with// unique characters using brute force// techniquefunction uniqueCharacters(str){ // If at any time we encounter 2 // same characters, return false for(let i = 0; i < str.length; i++) for(let j = i + 1; j < str.length; j++) if (str[i] == str[j]) return false; // If no duplicate characters // encountered, return true return true;} // Driver codelet input = "GeeksforGeeks"; if (uniqueCharacters(input) == true) document.write("The String " + input + " has all unique characters" + "</br>");else document.write("The String " + input + " has duplicate characters"); // This code is contributed by decode2207 </script> Output : The String GeeksforGeeks has duplicate characters Note: Please note that the program is case-sensitive. Approach 2 – Sorting: Using sorting based on ASCII values of characters Time Complexity: O(n log n) C++ Java Python3 C# Javascript // C++ program to illustrate string// with unique characters using// brute force technique#include <bits/stdc++.h>using namespace std; bool uniqueCharacters(string str){ // Using sorting sort(str.begin(), str.end()); for (int i = 0; i < str.length()-1; i++) { // if at any time, 2 adjacent // elements become equal, // return false if (str[i] == str[i + 1]) { return false; } } return true;} // driver codeint main(){ string str = "GeeksforGeeks"; if (uniqueCharacters(str)) { cout << "The String " << str << " has all unique characters\n"; } else { cout << "The String " << str << " has duplicate characters\n"; } return 0;}// This code is contributed by Divyam Madaan // Java program to check string with unique// characters using sorting techniqueimport java.util.*; class GfG { /* Convert the string to character array for sorting */ boolean uniqueCharacters(String str) { char[] chArray = str.toCharArray(); // Using sorting // Arrays.sort() uses binarySort in the background // for non-primitives which is of O(nlogn) time complexity Arrays.sort(chArray); for (int i = 0; i < chArray.length - 1; i++) { // if the adjacent elements are not // equal, move to next element if (chArray[i] != chArray[i + 1]) continue; // if at any time, 2 adjacent elements // become equal, return false else return false; } return true; } // Driver code public static void main(String args[]) { GfG obj = new GfG(); String input = "GeeksforGeeks"; if (obj.uniqueCharacters(input)) System.out.println("The String " + input + " has all unique characters"); else System.out.println("The String " + input + " has duplicate characters"); }} # Python3 program to illustrate string# with unique characters using# brute force techniquedef uniqueCharacters(st): # Using sorting st = sorted(st) for i in range(len(st)-1): # if at any time, 2 adjacent # elements become equal, # return false if (st[i] == st[i + 1]) : return False return True # Driver codeif __name__=='__main__': st = "GeeksforGeeks" if (uniqueCharacters(st)) : print("The String",st,"has all unique characters\n") else : print("The String",st,"has duplicate characters\n") # This code is contributed by AbhiThakur // C# program to check string with unique// characters using sorting techniqueusing System; public class GFG { /* Convert the string to character array for sorting */ static bool uniqueCharacters(String str) { char[] chArray = str.ToCharArray(); // Using sorting Array.Sort(chArray); for (int i = 0; i < chArray.Length - 1; i++) { // if the adjacent elements are not // equal, move to next element if (chArray[i] != chArray[i + 1]) continue; // if at any time, 2 adjacent elements // become equal, return false else return false; } return true; } // Driver code public static void Main() { string input = "GeeksforGeeks"; if (uniqueCharacters(input) == true) Console.WriteLine("The String " + input + " has all unique characters"); else Console.WriteLine("The String " + input + " has duplicate characters"); }} // This code is contributed by shiv_bhakt. <script> // Javascript program to // check string with unique // characters using sorting technique /* Convert the string to character array for sorting */ function uniqueCharacters(str) { let chArray = str.split(''); // Using sorting chArray.sort(); for (let i = 0; i < chArray.length - 1; i++) { // if the adjacent elements are not // equal, move to next element if (chArray[i] != chArray[i + 1]) continue; // if at any time, 2 adjacent elements // become equal, return false else return false; } return true; } let input = "GeeksforGeeks"; if (uniqueCharacters(input) == true) document.write("The String " + input + " has all unique characters" + "</br>"); else document.write("The String " + input + " has duplicate characters" + "</br>"); </script> Output: The String GeeksforGeeks has duplicate characters Approach 3 – Use of Extra Data Structure: This approach assumes ASCII char set(8 bits). The idea is to maintain a boolean array for the characters. The 256 indices represent 256 characters. All the array elements are initially set to false. As we iterate over the string, set true at the index equal to the int value of the character. If at any time, we encounter that the array value is already true, it means the character with that int value is repeated. Time Complexity: O(n) C++ Java Python3 C# Javascript #include <cstring>#include <iostream>using namespace std; const int MAX_CHAR = 256; bool uniqueCharacters(string str){ // If length is greater than 265, // some characters must have been repeated if (str.length() > MAX_CHAR) return false; bool chars[MAX_CHAR] = { 0 }; for (int i = 0; i < str.length(); i++) { if (chars[int(str[i])] == true) return false; chars[int(str[i])] = true; } return true;} // driver codeint main(){ string str = "GeeksforGeeks"; if (uniqueCharacters(str)) { cout << "The String " << str << " has all unique characters\n"; } else { cout << "The String " << str << " has duplicate characters\n"; } return 0;}// This code is contributed by Divyam Madaan // Java program to illustrate String With// Unique Characters using data structureimport java.util.*; class GfG { int MAX_CHAR = 256; boolean uniqueCharacters(String str) { // If length is greater than 256, // some characters must have been repeated if (str.length() > MAX_CHAR) return false; boolean[] chars = new boolean[MAX_CHAR]; Arrays.fill(chars, false); for (int i = 0; i < str.length(); i++) { int index = (int)str.charAt(i); /* If the value is already true, string has duplicate characters, return false */ if (chars[index] == true) return false; chars[index] = true; } /* No duplicates encountered, return true */ return true; } // Driver code public static void main(String args[]) { GfG obj = new GfG(); String input = "GeeksforGeeks"; if (obj.uniqueCharacters(input)) System.out.println("The String " + input + " has all unique characters"); else System.out.println("The String " + input + " has duplicate characters"); }} # Python program to illustrate# string with unique characters# using data structureMAX_CHAR = 256; def uniqueCharacters(string): n = len(string) # If length is greater than 256, # some characters must have # been repeated if n > MAX_CHAR: return False chars = [False] * MAX_CHAR for i in range(n): index = ord(string[i]) ''' * If the value is already True, string has duplicate characters, return False''' if (chars[index] == True): return False chars[index] = True ''' No duplicates encountered, return True ''' return True # Driver codeif __name__ == '__main__': input = "GeeksforGeeks" if (uniqueCharacters(input)): print("The String", input, "has all unique characters") else: print("The String", input, "has duplicate characters") # This code is contributed by shikhasingrajput // C# program to illustrate String With// Unique Characters using data structureusing System; class GfG { static int MAX_CHAR = 256; bool uniqueCharacters(String str) { // If length is greater than 256, // some characters must have been repeated if (str.Length > MAX_CHAR) return false; bool[] chars = new bool[MAX_CHAR]; for (int i = 0; i < MAX_CHAR; i++) { chars[i] = false; } for (int i = 0; i < str.Length; i++) { int index = (int)str[i]; /* If the value is already true, string has duplicate characters, return false */ if (chars[index] == true) return false; chars[index] = true; } /* No duplicates encountered, return true */ return true; } // Driver code public static void Main(String[] args) { GfG obj = new GfG(); String input = "GeeksforGeeks"; if (obj.uniqueCharacters(input)) Console.WriteLine("The String " + input + " has all unique characters"); else Console.WriteLine("The String " + input + " has duplicate characters"); }} // This code has been contributed by 29AjayKumar <script> // Javascript program to illustrate String With // Unique Characters using data structure let MAX_CHAR = 256; function uniqueCharacters(str) { // If length is greater than 256, // some characters must have been repeated if (str.length > MAX_CHAR) return false; let chars = new Array(MAX_CHAR); for (let i = 0; i < MAX_CHAR; i++) { chars[i] = false; } for (let i = 0; i < str.length; i++) { let index = str[i].charCodeAt(); /* If the value is already true, string has duplicate characters, return false */ if (chars[index] == true) return false; chars[index] = true; } /* No duplicates encountered, return true */ return true; } let input = "GeeksforGeeks"; if (uniqueCharacters(input)) document.write("The String " + input + " has all unique characters"); else document.write("The String " + input + " has duplicate characters"); </script> Output: The String GeeksforGeeks has duplicate characters Approach 4 – Without Extra Data Structure: The approach is valid for strings having alphabet as a-z. This approach is a little tricky. Instead of maintaining a boolean array, we maintain an integer value called checker(32 bits). As we iterate over the string, we find the int value of the character with respect to ‘a’ with the statement int bitAtIndex = str.charAt(i)-‘a’; Then the bit at that int value is set to 1 with the statement 1 << bitAtIndex . Now, if this bit is already set in the checker, the bit AND operation would make the checker > 0. Return false in this case. Else Update checker to make the bit 1 at that index with the statement checker = checker | (1 <<bitAtIndex); Time Complexity: O(n) C++ Java Python3 C# PHP Javascript // C++ program to illustrate string// with unique characters using// brute force technique#include <bits/stdc++.h>using namespace std; bool uniqueCharacters(string str){ // Assuming string can have characters // a-z, this has 32 bits set to 0 int checker = 0; for (int i = 0; i < str.length(); i++) { int bitAtIndex = str[i] - 'a'; // if that bit is already set in // checker, return false if ((checker & (1 << bitAtIndex)) > 0) { return false; } // otherwise update and continue by // setting that bit in the checker checker = checker | (1 << bitAtIndex); } // no duplicates encountered, return true return true;} // driver codeint main(){ string str = "geeksforgeeks"; if (uniqueCharacters(str)) { cout << "The String " << str << " has all unique characters\n"; } else { cout << "The String " << str << " has duplicate characters\n"; } return 0;}// This code is contributed by Divyam Madaan // Java program to illustrate String with unique// characters without using any data structureimport java.util.*; class GfG { boolean uniqueCharacters(String str) { // Assuming string can have characters a-z // this has 32 bits set to 0 int checker = 0; for (int i = 0; i < str.length(); i++) { int bitAtIndex = str.charAt(i) - 'a'; // if that bit is already set in checker, // return false if ((checker & (1 << bitAtIndex)) > 0) return false; // otherwise update and continue by // setting that bit in the checker checker = checker | (1 << bitAtIndex); } // no duplicates encountered, return true return true; } // Driver Code public static void main(String args[]) { GfG obj = new GfG(); String input = "geekforgeeks"; if (obj.uniqueCharacters(input)) System.out.println("The String " + input + " has all unique characters"); else System.out.println("The String " + input + " has duplicate characters"); }} # Python3 program to illustrate String with unique# characters without using any data structureimport math def uniqueCharacters(string): # Assuming string can have characters # a-z this has 32 bits set to 0 checker = 0 for i in range(len(string)): bitAtIndex = ord(string[i]) - ord('a') # If that bit is already set in # checker, return False if ((bitAtIndex) > 0): if ((checker & ((1 << bitAtIndex))) > 0): return False # Otherwise update and continue by # setting that bit in the checker checker = checker | (1 << bitAtIndex) # No duplicates encountered, return True return True # Driver Codeif __name__ == '__main__': input = "geekforgeeks" if (uniqueCharacters(input)): print("The String " + input + " has all unique characters") else: print("The String " + input + " has duplicate characters") # This code is contributed by Princi Singh // C# program to illustrate String// with unique characters without// using any data structureusing System; class GFG { public virtual bool uniqueCharacters(string str) { // Assuming string can have // characters a-z this has // 32 bits set to 0 int checker = 0; for (int i = 0; i < str.Length; i++) { int bitAtIndex = str[i] - 'a'; // if that bit is already set // in checker, return false if ((checker & (1 << bitAtIndex)) > 0) { return false; } // otherwise update and continue by // setting that bit in the checker checker = checker | (1 << bitAtIndex); } // no duplicates encountered, // return true return true; } // Driver Code public static void Main(string[] args) { GFG obj = new GFG(); string input = "geekforgeeks"; if (obj.uniqueCharacters(input)) { Console.WriteLine("The String " + input + " has all unique characters"); } else { Console.WriteLine("The String " + input + " has duplicate characters"); } }} // This code is contributed by Shrikant13 <?php// PHP program to illustrate// string with unique characters// using brute force techniquefunction uniqueCharacters($str){ // Assuming string can have // characters a-z, this has // 32 bits set to 0 $checker = 0; for ($i = 0; $i < strlen($str); $i++) { $bitAtIndex = $str[$i] - 'a'; // if that bit is already set // in checker, return false if (($checker & (1 << $bitAtIndex)) > 0) { return false; } // otherwise update and continue by // setting that bit in the checker $checker = $checker | (1 << $bitAtIndex); } // no duplicates encountered, // return true return true;} // Driver Code$str = "geeksforgeeks"; if(uniqueCharacters($str)){ echo "The String ", $str, " has all unique characters\n";}else{ echo "The String ", $str, " has duplicate characters\n";} // This code is contributed by ajit?> <script> // Javascript program to illustrate String // with unique characters without // using any data structure function uniqueCharacters(str) { // Assuming string can have // characters a-z this has // 32 bits set to 0 let checker = 0; for (let i = 0; i < str.length; i++) { let bitAtIndex = str[i] - 'a'; // if that bit is already set // in checker, return false if ((checker & (1 << bitAtIndex)) > 0) { return false; } // otherwise update and continue by // setting that bit in the checker checker = checker | (1 << bitAtIndex); } // no duplicates encountered, // return true return true; } let input = "geekforgeeks"; if (uniqueCharacters(input)) { document.write("The String " + input + " has all unique characters"); } else { document.write("The String " + input + " has duplicate characters"); } </script> Output : The String GeekforGeeks has duplicate characters Exercise: Above program is case insensitive, you can try making the same program that is case sensitive i.e Geeks and GEeks both give different output. Using Java Stream : Java import java.util.Collections;import java.util.stream.Collectors;class GfG { boolean uniqueCharacters(String s) { // If at any character more than once create another stream // stream count more than 0, return false return s.chars().filter(e-> Collections.frequency(s.chars().boxed().collect(Collectors.toList()), e) > 1).count() > 1 ? false: true; } public static void main(String args[]) { GfG obj = new GfG(); String input = "GeeksforGeeks"; if (obj.uniqueCharacters(input)) System.out.println("The String " + input + " has all unique characters"); else System.out.println("The String " + input + " has duplicate characters"); }} //Write Java code here Reference: Cracking the Coding Interview by Gayle Approach 5: Using sets() function: Convert the string to set. If the length of set is equal to the length of the string then return True else False. Below is the implementation of the above approach C++ Java Python3 C# Javascript // C++ program to illustrate String with unique// characters using set data structure#include <bits/stdc++.h>using namespace std; bool uniqueCharacters(string str){ set<char> char_set; // Inserting character of string into set for(char c : str) { char_set.insert(c); } // If length of set is equal to len of string // then it will have unique characters return char_set.size() == str.size();} // Driver codeint main(){ string str = "GeeksforGeeks"; if (uniqueCharacters(str)) { cout << "The String " << str << " has all unique characters\n"; } else { cout << "The String " << str << " has duplicate characters\n"; } return 0;} // This code is contributed by abhishekjha558498 // Java program to illustrate String with unique// characters using set data structureimport java.util.*; class GFG{ static boolean uniqueCharacters(String str){ HashSet<Character> char_set = new HashSet<>(); // Inserting character of String into set for(int c = 0; c< str.length();c++) { char_set.add(str.charAt(c)); } // If length of set is equal to len of String // then it will have unique characters return char_set.size() == str.length();} // Driver codepublic static void main(String[] args){ String str = "GeeksforGeeks"; if (uniqueCharacters(str)) { System.out.print("The String " + str + " has all unique characters\n"); } else { System.out.print("The String " + str + " has duplicate characters\n"); }}} // This code contributed by umadevi9616 # Python3 program to illustrate String with unique# charactersdef uniqueCharacters(str): # Converting string to set setstring = set(str) # If length of set is equal to len of string # then it will have unique characters if(len(setstring) == len(str)): return True return False # Driver Codeif __name__ == '__main__': input = "GeeksforGeeks" if (uniqueCharacters(input)): print("The String " + input + " has all unique characters") else: print("The String " + input + " has duplicate characters") # This code is contributed by vikkycirus // C# program to illustrate String with unique// characters using set data structureusing System;using System.Collections.Generic; public class GFG { static bool uniquechars(String str) { HashSet<char> char_set = new HashSet<char>(); // Inserting character of String into set for (int c = 0; c < str.Length; c++) { char_set.Add(str); } // If length of set is equal to len of String // then it will have unique characters if (char_set.Count == str.Length) { return true; } else { return false; } } // Driver code public static void Main(String[] args) { String str = "GeeksforGeeks"; if (uniquechars(str)) { Console.Write("The String " + str + " has all unique characters\n"); } else { Console.Write("The String " + str + " has duplicate characters\n"); } }} // This code is contributed by umadevi9616 <script> // Function program to illustrate String// with unique charactersfunction uniqueCharacters(str){ // Converting string to set var setstring = new Set(str) // If length of set is equal to len of string // then it will have unique characters if (setstring.size == str.length) { return true } else { return false }} // Driver Codevar input = "GeeksforGeeks" if (uniqueCharacters(input)){ document.write("The String " + input + " has all unique characters") ;}else{ document.write("The String " + input + " has duplicate characters")} // This code is contributed by bunnyram19 </script> Output: The String GeeksforGeeks has duplicate characters Time Complexity: O(nlogn) Auxiliary Space: O(n) This article is contributed by Saloni Baweja. 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. Vishal_Khoda jit_t V1 shrikanth13 Karthikn2099 29AjayKumar princiraj1992 sudhanshusahoo88 abhaysingh290895 prateek kumar 4 shikhasingrajput princi singh vikkycirus decode2207 divyeshrabadiya07 suresh07 divyesh072019 bunnyram19 abhishekjha558498 miharsh umadevi9616 CoderSaty aymanemx vjvipulvj Bit Magic Strings Strings Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Cyclic Redundancy Check and Modulo-2 Division Little and Big Endian Mystery Binary representation of a given number Bits manipulation (Important tactics) Bit Fields in C Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 25634, "s": 25606, "text": "\n25 Apr, 2022" }, { "code": null, "e": 25701, "s": 25634, "text": "Given a string, determine if the string has all unique characters." }, { "code": null, "e": 25714, "s": 25701, "text": "Examples : " }, { "code": null, "e": 25782, "s": 25714, "text": "Input : abcd10jk\nOutput : true\n\nInput : hutg9mnd!nk9\nOutput : false" }, { "code": null, "e": 25953, "s": 25782, "text": "Approach 1 – Brute Force technique: Run 2 loops with variable i and j. Compare str[i] and str[j]. If they become equal at any point, return false. Time Complexity: O(n2) " }, { "code": null, "e": 25957, "s": 25953, "text": "C++" }, { "code": null, "e": 25962, "s": 25957, "text": "Java" }, { "code": null, "e": 25970, "s": 25962, "text": "Python3" }, { "code": null, "e": 25973, "s": 25970, "text": "C#" }, { "code": null, "e": 25977, "s": 25973, "text": "PHP" }, { "code": null, "e": 25988, "s": 25977, "text": "Javascript" }, { "code": "// C++ program to illustrate string// with unique characters using// brute force technique#include <bits/stdc++.h>using namespace std; bool uniqueCharacters(string str){ // If at any time we encounter 2 // same characters, return false for (int i = 0; i < str.length() - 1; i++) { for (int j = i + 1; j < str.length(); j++) { if (str[i] == str[j]) { return false; } } } // If no duplicate characters encountered, // return true return true;} // driver codeint main(){ string str = \"GeeksforGeeks\"; if (uniqueCharacters(str)) { cout << \"The String \" << str << \" has all unique characters\\n\"; } else { cout << \"The String \" << str << \" has duplicate characters\\n\"; } return 0;}// This code is contributed by Divyam Madaan", "e": 26839, "s": 25988, "text": null }, { "code": "// Java program to illustrate string with// unique characters using brute force techniqueimport java.util.*; class GfG { boolean uniqueCharacters(String str) { // If at any time we encounter 2 same // characters, return false for (int i = 0; i < str.length(); i++) for (int j = i + 1; j < str.length(); j++) if (str.charAt(i) == str.charAt(j)) return false; // If no duplicate characters encountered, // return true return true; } public static void main(String args[]) { GfG obj = new GfG(); String input = \"GeeksforGeeks\"; if (obj.uniqueCharacters(input)) System.out.println(\"The String \" + input + \" has all unique characters\"); else System.out.println(\"The String \" + input + \" has duplicate characters\"); }}", "e": 27710, "s": 26839, "text": null }, { "code": "# Python program to illustrate string# with unique characters using# brute force technique def uniqueCharacters(str): # If at any time we encounter 2 # same characters, return false for i in range(len(str)): for j in range(i + 1,len(str)): if(str[i] == str[j]): return False; # If no duplicate characters # encountered, return true return True; # Driver Codestr = \"GeeksforGeeks\"; if(uniqueCharacters(str)): print(\"The String \", str,\" has all unique characters\");else: print(\"The String \", str, \" has duplicate characters\"); # This code contributed by PrinciRaj1992", "e": 28340, "s": 27710, "text": null }, { "code": "// C# program to illustrate string with// unique characters using brute force// techniqueusing System; public class GFG { static bool uniqueCharacters(String str) { // If at any time we encounter 2 // same characters, return false for (int i = 0; i < str.Length; i++) for (int j = i + 1; j < str.Length; j++) if (str[i] == str[j]) return false; // If no duplicate characters // encountered, return true return true; } public static void Main() { string input = \"GeeksforGeeks\"; if (uniqueCharacters(input) == true) Console.WriteLine(\"The String \" + input + \" has all unique characters\"); else Console.WriteLine(\"The String \" + input + \" has duplicate characters\"); }} // This code is contributed by shiv_bhakt.", "e": 29262, "s": 28340, "text": null }, { "code": "<?php// PHP program to illustrate string// with unique characters using// brute force technique function uniqueCharacters($str){ // If at any time we encounter 2 // same characters, return false for($i = 0; $i < strlen($str); $i++) { for($j = $i + 1; $j < strlen($str); $j++) { if($str[$i] == $str[$j]) { return false; } } } // If no duplicate characters // encountered, return true return true;} // Driver Code$str = \"GeeksforGeeks\"; if(uniqueCharacters($str)){ echo \"The String \", $str, \" has all unique characters\\n\";}else{ echo \"The String \", $str, \" has duplicate characters\\n\";} // This code is contributed by ajit?>", "e": 30011, "s": 29262, "text": null }, { "code": "<script> // Javascript program to illustrate string with// unique characters using brute force// techniquefunction uniqueCharacters(str){ // If at any time we encounter 2 // same characters, return false for(let i = 0; i < str.length; i++) for(let j = i + 1; j < str.length; j++) if (str[i] == str[j]) return false; // If no duplicate characters // encountered, return true return true;} // Driver codelet input = \"GeeksforGeeks\"; if (uniqueCharacters(input) == true) document.write(\"The String \" + input + \" has all unique characters\" + \"</br>\");else document.write(\"The String \" + input + \" has duplicate characters\"); // This code is contributed by decode2207 </script>", "e": 30800, "s": 30011, "text": null }, { "code": null, "e": 30810, "s": 30800, "text": "Output : " }, { "code": null, "e": 30860, "s": 30810, "text": "The String GeeksforGeeks has duplicate characters" }, { "code": null, "e": 30914, "s": 30860, "text": "Note: Please note that the program is case-sensitive." }, { "code": null, "e": 31015, "s": 30914, "text": "Approach 2 – Sorting: Using sorting based on ASCII values of characters Time Complexity: O(n log n) " }, { "code": null, "e": 31019, "s": 31015, "text": "C++" }, { "code": null, "e": 31024, "s": 31019, "text": "Java" }, { "code": null, "e": 31032, "s": 31024, "text": "Python3" }, { "code": null, "e": 31035, "s": 31032, "text": "C#" }, { "code": null, "e": 31046, "s": 31035, "text": "Javascript" }, { "code": "// C++ program to illustrate string// with unique characters using// brute force technique#include <bits/stdc++.h>using namespace std; bool uniqueCharacters(string str){ // Using sorting sort(str.begin(), str.end()); for (int i = 0; i < str.length()-1; i++) { // if at any time, 2 adjacent // elements become equal, // return false if (str[i] == str[i + 1]) { return false; } } return true;} // driver codeint main(){ string str = \"GeeksforGeeks\"; if (uniqueCharacters(str)) { cout << \"The String \" << str << \" has all unique characters\\n\"; } else { cout << \"The String \" << str << \" has duplicate characters\\n\"; } return 0;}// This code is contributed by Divyam Madaan", "e": 31839, "s": 31046, "text": null }, { "code": "// Java program to check string with unique// characters using sorting techniqueimport java.util.*; class GfG { /* Convert the string to character array for sorting */ boolean uniqueCharacters(String str) { char[] chArray = str.toCharArray(); // Using sorting // Arrays.sort() uses binarySort in the background // for non-primitives which is of O(nlogn) time complexity Arrays.sort(chArray); for (int i = 0; i < chArray.length - 1; i++) { // if the adjacent elements are not // equal, move to next element if (chArray[i] != chArray[i + 1]) continue; // if at any time, 2 adjacent elements // become equal, return false else return false; } return true; } // Driver code public static void main(String args[]) { GfG obj = new GfG(); String input = \"GeeksforGeeks\"; if (obj.uniqueCharacters(input)) System.out.println(\"The String \" + input + \" has all unique characters\"); else System.out.println(\"The String \" + input + \" has duplicate characters\"); }}", "e": 33088, "s": 31839, "text": null }, { "code": "# Python3 program to illustrate string# with unique characters using# brute force techniquedef uniqueCharacters(st): # Using sorting st = sorted(st) for i in range(len(st)-1): # if at any time, 2 adjacent # elements become equal, # return false if (st[i] == st[i + 1]) : return False return True # Driver codeif __name__=='__main__': st = \"GeeksforGeeks\" if (uniqueCharacters(st)) : print(\"The String\",st,\"has all unique characters\\n\") else : print(\"The String\",st,\"has duplicate characters\\n\") # This code is contributed by AbhiThakur", "e": 33726, "s": 33088, "text": null }, { "code": "// C# program to check string with unique// characters using sorting techniqueusing System; public class GFG { /* Convert the string to character array for sorting */ static bool uniqueCharacters(String str) { char[] chArray = str.ToCharArray(); // Using sorting Array.Sort(chArray); for (int i = 0; i < chArray.Length - 1; i++) { // if the adjacent elements are not // equal, move to next element if (chArray[i] != chArray[i + 1]) continue; // if at any time, 2 adjacent elements // become equal, return false else return false; } return true; } // Driver code public static void Main() { string input = \"GeeksforGeeks\"; if (uniqueCharacters(input) == true) Console.WriteLine(\"The String \" + input + \" has all unique characters\"); else Console.WriteLine(\"The String \" + input + \" has duplicate characters\"); }} // This code is contributed by shiv_bhakt.", "e": 34855, "s": 33726, "text": null }, { "code": "<script> // Javascript program to // check string with unique // characters using sorting technique /* Convert the string to character array for sorting */ function uniqueCharacters(str) { let chArray = str.split(''); // Using sorting chArray.sort(); for (let i = 0; i < chArray.length - 1; i++) { // if the adjacent elements are not // equal, move to next element if (chArray[i] != chArray[i + 1]) continue; // if at any time, 2 adjacent elements // become equal, return false else return false; } return true; } let input = \"GeeksforGeeks\"; if (uniqueCharacters(input) == true) document.write(\"The String \" + input + \" has all unique characters\" + \"</br>\"); else document.write(\"The String \" + input + \" has duplicate characters\" + \"</br>\"); </script>", "e": 35834, "s": 34855, "text": null }, { "code": null, "e": 35843, "s": 35834, "text": "Output: " }, { "code": null, "e": 35893, "s": 35843, "text": "The String GeeksforGeeks has duplicate characters" }, { "code": null, "e": 36352, "s": 35893, "text": "Approach 3 – Use of Extra Data Structure: This approach assumes ASCII char set(8 bits). The idea is to maintain a boolean array for the characters. The 256 indices represent 256 characters. All the array elements are initially set to false. As we iterate over the string, set true at the index equal to the int value of the character. If at any time, we encounter that the array value is already true, it means the character with that int value is repeated. " }, { "code": null, "e": 36375, "s": 36352, "text": "Time Complexity: O(n) " }, { "code": null, "e": 36379, "s": 36375, "text": "C++" }, { "code": null, "e": 36384, "s": 36379, "text": "Java" }, { "code": null, "e": 36392, "s": 36384, "text": "Python3" }, { "code": null, "e": 36395, "s": 36392, "text": "C#" }, { "code": null, "e": 36406, "s": 36395, "text": "Javascript" }, { "code": "#include <cstring>#include <iostream>using namespace std; const int MAX_CHAR = 256; bool uniqueCharacters(string str){ // If length is greater than 265, // some characters must have been repeated if (str.length() > MAX_CHAR) return false; bool chars[MAX_CHAR] = { 0 }; for (int i = 0; i < str.length(); i++) { if (chars[int(str[i])] == true) return false; chars[int(str[i])] = true; } return true;} // driver codeint main(){ string str = \"GeeksforGeeks\"; if (uniqueCharacters(str)) { cout << \"The String \" << str << \" has all unique characters\\n\"; } else { cout << \"The String \" << str << \" has duplicate characters\\n\"; } return 0;}// This code is contributed by Divyam Madaan", "e": 37197, "s": 36406, "text": null }, { "code": "// Java program to illustrate String With// Unique Characters using data structureimport java.util.*; class GfG { int MAX_CHAR = 256; boolean uniqueCharacters(String str) { // If length is greater than 256, // some characters must have been repeated if (str.length() > MAX_CHAR) return false; boolean[] chars = new boolean[MAX_CHAR]; Arrays.fill(chars, false); for (int i = 0; i < str.length(); i++) { int index = (int)str.charAt(i); /* If the value is already true, string has duplicate characters, return false */ if (chars[index] == true) return false; chars[index] = true; } /* No duplicates encountered, return true */ return true; } // Driver code public static void main(String args[]) { GfG obj = new GfG(); String input = \"GeeksforGeeks\"; if (obj.uniqueCharacters(input)) System.out.println(\"The String \" + input + \" has all unique characters\"); else System.out.println(\"The String \" + input + \" has duplicate characters\"); }}", "e": 38422, "s": 37197, "text": null }, { "code": "# Python program to illustrate# string with unique characters# using data structureMAX_CHAR = 256; def uniqueCharacters(string): n = len(string) # If length is greater than 256, # some characters must have # been repeated if n > MAX_CHAR: return False chars = [False] * MAX_CHAR for i in range(n): index = ord(string[i]) ''' * If the value is already True, string has duplicate characters, return False''' if (chars[index] == True): return False chars[index] = True ''' No duplicates encountered, return True ''' return True # Driver codeif __name__ == '__main__': input = \"GeeksforGeeks\" if (uniqueCharacters(input)): print(\"The String\", input, \"has all unique characters\") else: print(\"The String\", input, \"has duplicate characters\") # This code is contributed by shikhasingrajput", "e": 39371, "s": 38422, "text": null }, { "code": "// C# program to illustrate String With// Unique Characters using data structureusing System; class GfG { static int MAX_CHAR = 256; bool uniqueCharacters(String str) { // If length is greater than 256, // some characters must have been repeated if (str.Length > MAX_CHAR) return false; bool[] chars = new bool[MAX_CHAR]; for (int i = 0; i < MAX_CHAR; i++) { chars[i] = false; } for (int i = 0; i < str.Length; i++) { int index = (int)str[i]; /* If the value is already true, string has duplicate characters, return false */ if (chars[index] == true) return false; chars[index] = true; } /* No duplicates encountered, return true */ return true; } // Driver code public static void Main(String[] args) { GfG obj = new GfG(); String input = \"GeeksforGeeks\"; if (obj.uniqueCharacters(input)) Console.WriteLine(\"The String \" + input + \" has all unique characters\"); else Console.WriteLine(\"The String \" + input + \" has duplicate characters\"); }} // This code has been contributed by 29AjayKumar", "e": 40664, "s": 39371, "text": null }, { "code": "<script> // Javascript program to illustrate String With // Unique Characters using data structure let MAX_CHAR = 256; function uniqueCharacters(str) { // If length is greater than 256, // some characters must have been repeated if (str.length > MAX_CHAR) return false; let chars = new Array(MAX_CHAR); for (let i = 0; i < MAX_CHAR; i++) { chars[i] = false; } for (let i = 0; i < str.length; i++) { let index = str[i].charCodeAt(); /* If the value is already true, string has duplicate characters, return false */ if (chars[index] == true) return false; chars[index] = true; } /* No duplicates encountered, return true */ return true; } let input = \"GeeksforGeeks\"; if (uniqueCharacters(input)) document.write(\"The String \" + input + \" has all unique characters\"); else document.write(\"The String \" + input + \" has duplicate characters\"); </script>", "e": 41783, "s": 40664, "text": null }, { "code": null, "e": 41791, "s": 41783, "text": "Output:" }, { "code": null, "e": 41841, "s": 41791, "text": "The String GeeksforGeeks has duplicate characters" }, { "code": null, "e": 42530, "s": 41841, "text": "Approach 4 – Without Extra Data Structure: The approach is valid for strings having alphabet as a-z. This approach is a little tricky. Instead of maintaining a boolean array, we maintain an integer value called checker(32 bits). As we iterate over the string, we find the int value of the character with respect to ‘a’ with the statement int bitAtIndex = str.charAt(i)-‘a’; Then the bit at that int value is set to 1 with the statement 1 << bitAtIndex . Now, if this bit is already set in the checker, the bit AND operation would make the checker > 0. Return false in this case. Else Update checker to make the bit 1 at that index with the statement checker = checker | (1 <<bitAtIndex); " }, { "code": null, "e": 42554, "s": 42530, "text": "Time Complexity: O(n) " }, { "code": null, "e": 42558, "s": 42554, "text": "C++" }, { "code": null, "e": 42563, "s": 42558, "text": "Java" }, { "code": null, "e": 42571, "s": 42563, "text": "Python3" }, { "code": null, "e": 42574, "s": 42571, "text": "C#" }, { "code": null, "e": 42578, "s": 42574, "text": "PHP" }, { "code": null, "e": 42589, "s": 42578, "text": "Javascript" }, { "code": "// C++ program to illustrate string// with unique characters using// brute force technique#include <bits/stdc++.h>using namespace std; bool uniqueCharacters(string str){ // Assuming string can have characters // a-z, this has 32 bits set to 0 int checker = 0; for (int i = 0; i < str.length(); i++) { int bitAtIndex = str[i] - 'a'; // if that bit is already set in // checker, return false if ((checker & (1 << bitAtIndex)) > 0) { return false; } // otherwise update and continue by // setting that bit in the checker checker = checker | (1 << bitAtIndex); } // no duplicates encountered, return true return true;} // driver codeint main(){ string str = \"geeksforgeeks\"; if (uniqueCharacters(str)) { cout << \"The String \" << str << \" has all unique characters\\n\"; } else { cout << \"The String \" << str << \" has duplicate characters\\n\"; } return 0;}// This code is contributed by Divyam Madaan", "e": 43634, "s": 42589, "text": null }, { "code": "// Java program to illustrate String with unique// characters without using any data structureimport java.util.*; class GfG { boolean uniqueCharacters(String str) { // Assuming string can have characters a-z // this has 32 bits set to 0 int checker = 0; for (int i = 0; i < str.length(); i++) { int bitAtIndex = str.charAt(i) - 'a'; // if that bit is already set in checker, // return false if ((checker & (1 << bitAtIndex)) > 0) return false; // otherwise update and continue by // setting that bit in the checker checker = checker | (1 << bitAtIndex); } // no duplicates encountered, return true return true; } // Driver Code public static void main(String args[]) { GfG obj = new GfG(); String input = \"geekforgeeks\"; if (obj.uniqueCharacters(input)) System.out.println(\"The String \" + input + \" has all unique characters\"); else System.out.println(\"The String \" + input + \" has duplicate characters\"); }}", "e": 44821, "s": 43634, "text": null }, { "code": "# Python3 program to illustrate String with unique# characters without using any data structureimport math def uniqueCharacters(string): # Assuming string can have characters # a-z this has 32 bits set to 0 checker = 0 for i in range(len(string)): bitAtIndex = ord(string[i]) - ord('a') # If that bit is already set in # checker, return False if ((bitAtIndex) > 0): if ((checker & ((1 << bitAtIndex))) > 0): return False # Otherwise update and continue by # setting that bit in the checker checker = checker | (1 << bitAtIndex) # No duplicates encountered, return True return True # Driver Codeif __name__ == '__main__': input = \"geekforgeeks\" if (uniqueCharacters(input)): print(\"The String \" + input + \" has all unique characters\") else: print(\"The String \" + input + \" has duplicate characters\") # This code is contributed by Princi Singh", "e": 45852, "s": 44821, "text": null }, { "code": "// C# program to illustrate String// with unique characters without// using any data structureusing System; class GFG { public virtual bool uniqueCharacters(string str) { // Assuming string can have // characters a-z this has // 32 bits set to 0 int checker = 0; for (int i = 0; i < str.Length; i++) { int bitAtIndex = str[i] - 'a'; // if that bit is already set // in checker, return false if ((checker & (1 << bitAtIndex)) > 0) { return false; } // otherwise update and continue by // setting that bit in the checker checker = checker | (1 << bitAtIndex); } // no duplicates encountered, // return true return true; } // Driver Code public static void Main(string[] args) { GFG obj = new GFG(); string input = \"geekforgeeks\"; if (obj.uniqueCharacters(input)) { Console.WriteLine(\"The String \" + input + \" has all unique characters\"); } else { Console.WriteLine(\"The String \" + input + \" has duplicate characters\"); } }} // This code is contributed by Shrikant13", "e": 47073, "s": 45852, "text": null }, { "code": "<?php// PHP program to illustrate// string with unique characters// using brute force techniquefunction uniqueCharacters($str){ // Assuming string can have // characters a-z, this has // 32 bits set to 0 $checker = 0; for ($i = 0; $i < strlen($str); $i++) { $bitAtIndex = $str[$i] - 'a'; // if that bit is already set // in checker, return false if (($checker & (1 << $bitAtIndex)) > 0) { return false; } // otherwise update and continue by // setting that bit in the checker $checker = $checker | (1 << $bitAtIndex); } // no duplicates encountered, // return true return true;} // Driver Code$str = \"geeksforgeeks\"; if(uniqueCharacters($str)){ echo \"The String \", $str, \" has all unique characters\\n\";}else{ echo \"The String \", $str, \" has duplicate characters\\n\";} // This code is contributed by ajit?>", "e": 48050, "s": 47073, "text": null }, { "code": "<script> // Javascript program to illustrate String // with unique characters without // using any data structure function uniqueCharacters(str) { // Assuming string can have // characters a-z this has // 32 bits set to 0 let checker = 0; for (let i = 0; i < str.length; i++) { let bitAtIndex = str[i] - 'a'; // if that bit is already set // in checker, return false if ((checker & (1 << bitAtIndex)) > 0) { return false; } // otherwise update and continue by // setting that bit in the checker checker = checker | (1 << bitAtIndex); } // no duplicates encountered, // return true return true; } let input = \"geekforgeeks\"; if (uniqueCharacters(input)) { document.write(\"The String \" + input + \" has all unique characters\"); } else { document.write(\"The String \" + input + \" has duplicate characters\"); } </script>", "e": 49098, "s": 48050, "text": null }, { "code": null, "e": 49108, "s": 49098, "text": "Output : " }, { "code": null, "e": 49157, "s": 49108, "text": "The String GeekforGeeks has duplicate characters" }, { "code": null, "e": 49309, "s": 49157, "text": "Exercise: Above program is case insensitive, you can try making the same program that is case sensitive i.e Geeks and GEeks both give different output." }, { "code": null, "e": 49330, "s": 49309, "text": "Using Java Stream : " }, { "code": null, "e": 49335, "s": 49330, "text": "Java" }, { "code": "import java.util.Collections;import java.util.stream.Collectors;class GfG { boolean uniqueCharacters(String s) { // If at any character more than once create another stream // stream count more than 0, return false return s.chars().filter(e-> Collections.frequency(s.chars().boxed().collect(Collectors.toList()), e) > 1).count() > 1 ? false: true; } public static void main(String args[]) { GfG obj = new GfG(); String input = \"GeeksforGeeks\"; if (obj.uniqueCharacters(input)) System.out.println(\"The String \" + input + \" has all unique characters\"); else System.out.println(\"The String \" + input + \" has duplicate characters\"); }} //Write Java code here", "e": 50083, "s": 49335, "text": null }, { "code": null, "e": 50134, "s": 50083, "text": "Reference: Cracking the Coding Interview by Gayle " }, { "code": null, "e": 50169, "s": 50134, "text": "Approach 5: Using sets() function:" }, { "code": null, "e": 50196, "s": 50169, "text": "Convert the string to set." }, { "code": null, "e": 50283, "s": 50196, "text": "If the length of set is equal to the length of the string then return True else False." }, { "code": null, "e": 50333, "s": 50283, "text": "Below is the implementation of the above approach" }, { "code": null, "e": 50337, "s": 50333, "text": "C++" }, { "code": null, "e": 50342, "s": 50337, "text": "Java" }, { "code": null, "e": 50350, "s": 50342, "text": "Python3" }, { "code": null, "e": 50353, "s": 50350, "text": "C#" }, { "code": null, "e": 50364, "s": 50353, "text": "Javascript" }, { "code": "// C++ program to illustrate String with unique// characters using set data structure#include <bits/stdc++.h>using namespace std; bool uniqueCharacters(string str){ set<char> char_set; // Inserting character of string into set for(char c : str) { char_set.insert(c); } // If length of set is equal to len of string // then it will have unique characters return char_set.size() == str.size();} // Driver codeint main(){ string str = \"GeeksforGeeks\"; if (uniqueCharacters(str)) { cout << \"The String \" << str << \" has all unique characters\\n\"; } else { cout << \"The String \" << str << \" has duplicate characters\\n\"; } return 0;} // This code is contributed by abhishekjha558498", "e": 51136, "s": 50364, "text": null }, { "code": "// Java program to illustrate String with unique// characters using set data structureimport java.util.*; class GFG{ static boolean uniqueCharacters(String str){ HashSet<Character> char_set = new HashSet<>(); // Inserting character of String into set for(int c = 0; c< str.length();c++) { char_set.add(str.charAt(c)); } // If length of set is equal to len of String // then it will have unique characters return char_set.size() == str.length();} // Driver codepublic static void main(String[] args){ String str = \"GeeksforGeeks\"; if (uniqueCharacters(str)) { System.out.print(\"The String \" + str + \" has all unique characters\\n\"); } else { System.out.print(\"The String \" + str + \" has duplicate characters\\n\"); }}} // This code contributed by umadevi9616", "e": 51986, "s": 51136, "text": null }, { "code": "# Python3 program to illustrate String with unique# charactersdef uniqueCharacters(str): # Converting string to set setstring = set(str) # If length of set is equal to len of string # then it will have unique characters if(len(setstring) == len(str)): return True return False # Driver Codeif __name__ == '__main__': input = \"GeeksforGeeks\" if (uniqueCharacters(input)): print(\"The String \" + input + \" has all unique characters\") else: print(\"The String \" + input + \" has duplicate characters\") # This code is contributed by vikkycirus", "e": 52615, "s": 51986, "text": null }, { "code": "// C# program to illustrate String with unique// characters using set data structureusing System;using System.Collections.Generic; public class GFG { static bool uniquechars(String str) { HashSet<char> char_set = new HashSet<char>(); // Inserting character of String into set for (int c = 0; c < str.Length; c++) { char_set.Add(str); } // If length of set is equal to len of String // then it will have unique characters if (char_set.Count == str.Length) { return true; } else { return false; } } // Driver code public static void Main(String[] args) { String str = \"GeeksforGeeks\"; if (uniquechars(str)) { Console.Write(\"The String \" + str + \" has all unique characters\\n\"); } else { Console.Write(\"The String \" + str + \" has duplicate characters\\n\"); } }} // This code is contributed by umadevi9616", "e": 53652, "s": 52615, "text": null }, { "code": "<script> // Function program to illustrate String// with unique charactersfunction uniqueCharacters(str){ // Converting string to set var setstring = new Set(str) // If length of set is equal to len of string // then it will have unique characters if (setstring.size == str.length) { return true } else { return false }} // Driver Codevar input = \"GeeksforGeeks\" if (uniqueCharacters(input)){ document.write(\"The String \" + input + \" has all unique characters\") ;}else{ document.write(\"The String \" + input + \" has duplicate characters\")} // This code is contributed by bunnyram19 </script>", "e": 54339, "s": 53652, "text": null }, { "code": null, "e": 54347, "s": 54339, "text": "Output:" }, { "code": null, "e": 54397, "s": 54347, "text": "The String GeeksforGeeks has duplicate characters" }, { "code": null, "e": 54423, "s": 54397, "text": "Time Complexity: O(nlogn)" }, { "code": null, "e": 54445, "s": 54423, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 54865, "s": 54445, "text": "This article is contributed by Saloni Baweja. 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": 54878, "s": 54865, "text": "Vishal_Khoda" }, { "code": null, "e": 54884, "s": 54878, "text": "jit_t" }, { "code": null, "e": 54887, "s": 54884, "text": "V1" }, { "code": null, "e": 54899, "s": 54887, "text": "shrikanth13" }, { "code": null, "e": 54912, "s": 54899, "text": "Karthikn2099" }, { "code": null, "e": 54924, "s": 54912, "text": "29AjayKumar" }, { "code": null, "e": 54938, "s": 54924, "text": "princiraj1992" }, { "code": null, "e": 54955, "s": 54938, "text": "sudhanshusahoo88" }, { "code": null, "e": 54972, "s": 54955, "text": "abhaysingh290895" }, { "code": null, "e": 54988, "s": 54972, "text": "prateek kumar 4" }, { "code": null, "e": 55005, "s": 54988, "text": "shikhasingrajput" }, { "code": null, "e": 55018, "s": 55005, "text": "princi singh" }, { "code": null, "e": 55029, "s": 55018, "text": "vikkycirus" }, { "code": null, "e": 55040, "s": 55029, "text": "decode2207" }, { "code": null, "e": 55058, "s": 55040, "text": "divyeshrabadiya07" }, { "code": null, "e": 55067, "s": 55058, "text": "suresh07" }, { "code": null, "e": 55081, "s": 55067, "text": "divyesh072019" }, { "code": null, "e": 55092, "s": 55081, "text": "bunnyram19" }, { "code": null, "e": 55110, "s": 55092, "text": "abhishekjha558498" }, { "code": null, "e": 55118, "s": 55110, "text": "miharsh" }, { "code": null, "e": 55130, "s": 55118, "text": "umadevi9616" }, { "code": null, "e": 55140, "s": 55130, "text": "CoderSaty" }, { "code": null, "e": 55149, "s": 55140, "text": "aymanemx" }, { "code": null, "e": 55159, "s": 55149, "text": "vjvipulvj" }, { "code": null, "e": 55169, "s": 55159, "text": "Bit Magic" }, { "code": null, "e": 55177, "s": 55169, "text": "Strings" }, { "code": null, "e": 55185, "s": 55177, "text": "Strings" }, { "code": null, "e": 55195, "s": 55185, "text": "Bit Magic" }, { "code": null, "e": 55293, "s": 55195, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 55339, "s": 55293, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 55369, "s": 55339, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 55409, "s": 55369, "text": "Binary representation of a given number" }, { "code": null, "e": 55447, "s": 55409, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 55463, "s": 55447, "text": "Bit Fields in C" }, { "code": null, "e": 55488, "s": 55463, "text": "Reverse a string in Java" }, { "code": null, "e": 55534, "s": 55488, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 55568, "s": 55534, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 55628, "s": 55568, "text": "Write a program to print all permutations of a given string" } ]
Software Testing | Stability Testing - GeeksforGeeks
16 May, 2019 Stability Testing is a type of Software Testing to check the quality and behavior of the software in different environmental parameters. It is defined as the ability of the product to continue to function over time without failure. It is a Non-functional Testing technique that focuses to stress the software component to the maximum. Stability testing is done to check the efficiency of a developed product beyond normal operational capacity that is known as break point. It has higher significance in error handling, software reliability, robustness and scalability of a product under heavy load rather than checking the system behavior under normal circumstances. Stability testing assesses stability problems. This testing is majorly intended to check whether the application will crash at any point in time or not. Objective of the Stability Testing:The objective of the stability testing is: To yield confidence in the stability of the system or software application under test. To ensure the system handling big programs. To operate the effectiveness of the system or software application. To check the stability of the system under stress. Stability Testing Process: Effects of not performing Stability Testing: If stability testing is not carried out, system slows down with large amount of data.Without stability testing, system crashes suddenly.In absence of stability testing, System’s behavior is abnormal when it goes to different environment.In absence of stability testing, system’s performance decreases which in turn can have bad effects on the business. If stability testing is not carried out, system slows down with large amount of data. Without stability testing, system crashes suddenly. In absence of stability testing, System’s behavior is abnormal when it goes to different environment. In absence of stability testing, system’s performance decreases which in turn can have bad effects on the business. Testing Tools used in Stability Testing: 1. Apache JMeter 2. NeoLoad 3. WebLOAD 4. LoadRunner Advantages of Stability Testing: It gives the limit of the data that a system can handle practically.It provides the confidence on the performance of the system.It determines the stability and robustness of the system under load.Stability testing leads to a better end user experience. It gives the limit of the data that a system can handle practically. It provides the confidence on the performance of the system. It determines the stability and robustness of the system under load. Stability testing leads to a better end user experience. Software Testing Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Software Engineering | Integration Testing System Testing Software Engineering | Software Quality Assurance Software Engineering | Black box testing What is DFD(Data Flow Diagram)? Difference between IAAS, PAAS and SAAS Use Case Diagram for Library Management System Difference between Unit Testing and Integration Testing Object Oriented Analysis and Design Software Engineering | Software Design Process
[ { "code": null, "e": 26235, "s": 26207, "text": "\n16 May, 2019" }, { "code": null, "e": 26467, "s": 26235, "text": "Stability Testing is a type of Software Testing to check the quality and behavior of the software in different environmental parameters. It is defined as the ability of the product to continue to function over time without failure." }, { "code": null, "e": 26902, "s": 26467, "text": "It is a Non-functional Testing technique that focuses to stress the software component to the maximum. Stability testing is done to check the efficiency of a developed product beyond normal operational capacity that is known as break point. It has higher significance in error handling, software reliability, robustness and scalability of a product under heavy load rather than checking the system behavior under normal circumstances." }, { "code": null, "e": 27055, "s": 26902, "text": "Stability testing assesses stability problems. This testing is majorly intended to check whether the application will crash at any point in time or not." }, { "code": null, "e": 27133, "s": 27055, "text": "Objective of the Stability Testing:The objective of the stability testing is:" }, { "code": null, "e": 27220, "s": 27133, "text": "To yield confidence in the stability of the system or software application under test." }, { "code": null, "e": 27264, "s": 27220, "text": "To ensure the system handling big programs." }, { "code": null, "e": 27332, "s": 27264, "text": "To operate the effectiveness of the system or software application." }, { "code": null, "e": 27383, "s": 27332, "text": "To check the stability of the system under stress." }, { "code": null, "e": 27410, "s": 27383, "text": "Stability Testing Process:" }, { "code": null, "e": 27455, "s": 27410, "text": "Effects of not performing Stability Testing:" }, { "code": null, "e": 27808, "s": 27455, "text": "If stability testing is not carried out, system slows down with large amount of data.Without stability testing, system crashes suddenly.In absence of stability testing, System’s behavior is abnormal when it goes to different environment.In absence of stability testing, system’s performance decreases which in turn can have bad effects on the business." }, { "code": null, "e": 27894, "s": 27808, "text": "If stability testing is not carried out, system slows down with large amount of data." }, { "code": null, "e": 27946, "s": 27894, "text": "Without stability testing, system crashes suddenly." }, { "code": null, "e": 28048, "s": 27946, "text": "In absence of stability testing, System’s behavior is abnormal when it goes to different environment." }, { "code": null, "e": 28164, "s": 28048, "text": "In absence of stability testing, system’s performance decreases which in turn can have bad effects on the business." }, { "code": null, "e": 28205, "s": 28164, "text": "Testing Tools used in Stability Testing:" }, { "code": null, "e": 28259, "s": 28205, "text": "1. Apache JMeter\n2. NeoLoad\n3. WebLOAD\n4. LoadRunner " }, { "code": null, "e": 28292, "s": 28259, "text": "Advantages of Stability Testing:" }, { "code": null, "e": 28545, "s": 28292, "text": "It gives the limit of the data that a system can handle practically.It provides the confidence on the performance of the system.It determines the stability and robustness of the system under load.Stability testing leads to a better end user experience." }, { "code": null, "e": 28614, "s": 28545, "text": "It gives the limit of the data that a system can handle practically." }, { "code": null, "e": 28675, "s": 28614, "text": "It provides the confidence on the performance of the system." }, { "code": null, "e": 28744, "s": 28675, "text": "It determines the stability and robustness of the system under load." }, { "code": null, "e": 28801, "s": 28744, "text": "Stability testing leads to a better end user experience." }, { "code": null, "e": 28818, "s": 28801, "text": "Software Testing" }, { "code": null, "e": 28839, "s": 28818, "text": "Software Engineering" }, { "code": null, "e": 28937, "s": 28839, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28980, "s": 28937, "text": "Software Engineering | Integration Testing" }, { "code": null, "e": 28995, "s": 28980, "text": "System Testing" }, { "code": null, "e": 29045, "s": 28995, "text": "Software Engineering | Software Quality Assurance" }, { "code": null, "e": 29086, "s": 29045, "text": "Software Engineering | Black box testing" }, { "code": null, "e": 29118, "s": 29086, "text": "What is DFD(Data Flow Diagram)?" }, { "code": null, "e": 29157, "s": 29118, "text": "Difference between IAAS, PAAS and SAAS" }, { "code": null, "e": 29204, "s": 29157, "text": "Use Case Diagram for Library Management System" }, { "code": null, "e": 29260, "s": 29204, "text": "Difference between Unit Testing and Integration Testing" }, { "code": null, "e": 29296, "s": 29260, "text": "Object Oriented Analysis and Design" } ]
Access Relation Databases with Python - GeeksforGeeks
16 Jul, 2020 Databases are powerful tools for data scientists. DB-API is Python’s standard API used for accessing databases. It allows you to write a single program that works with multiple kinds of relational databases instead of writing a separate program for each one. This is how a typical user accesses databases using Python code written on a Jupyter notebook, a Web-based editor. There is a mechanism by which the Python program communicates with the DBMS: The application program begins its database access with one or more API calls that connect the program to the DBMS. Then to send the SQL statement to the DBMS, the program builds the statement as a text string and then makes an API call to pass the contents to the DBMS. The application program makes API calls to check the status of its DBMS request and to handle errors. The application program ends its database access with an API call that disconnects it from the database. The two main concepts in the Python DB-API are: 1) Connection objects used for Connect to a database Manage your transactions. Following are a few connection methods: cursor(): This method returns a new cursor object using the connection. commit(): This method is used to commit any pending transaction to the database. rollback(): This method causes the database to roll back to the start of any pending transaction. close(): This method is used to close a database connection. 2) Query objects are used to run queries. This is a python application that uses the DB-API to query a database. Python3 from dbmodule import connect # Create connection objectconnection = connect('databasename', 'username', 'pswd') # Create a cursor objectcursor = connection.cursor() # Run queriescursor.execute('select * from mytable')results = cursor.fetchall() # Free resourcescursor.close()connection.close() First, we import the database module by using the connect API from that module. To open a connection to the database, you use the connection function and pass in the parameters that are the database name, username, and password. The connect function returns the connection object.After this, we create a cursor object on the connection object. The cursor is used to run queries and get the results.After running the queries using the cursor, we also use the cursor to fetch the results of the query.Finally, when the system is done running the queries, it frees all resources by closing the connection. Remember that it is always important to close connections to avoid unused connections taking up resources. First, we import the database module by using the connect API from that module. To open a connection to the database, you use the connection function and pass in the parameters that are the database name, username, and password. The connect function returns the connection object. After this, we create a cursor object on the connection object. The cursor is used to run queries and get the results. After running the queries using the cursor, we also use the cursor to fetch the results of the query. Finally, when the system is done running the queries, it frees all resources by closing the connection. Remember that it is always important to close connections to avoid unused connections taking up resources. Python-projects python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25561, "s": 25533, "text": "\n16 Jul, 2020" }, { "code": null, "e": 25935, "s": 25561, "text": "Databases are powerful tools for data scientists. DB-API is Python’s standard API used for accessing databases. It allows you to write a single program that works with multiple kinds of relational databases instead of writing a separate program for each one. This is how a typical user accesses databases using Python code written on a Jupyter notebook, a Web-based editor." }, { "code": null, "e": 26012, "s": 25935, "text": "There is a mechanism by which the Python program communicates with the DBMS:" }, { "code": null, "e": 26128, "s": 26012, "text": "The application program begins its database access with one or more API calls that connect the program to the DBMS." }, { "code": null, "e": 26283, "s": 26128, "text": "Then to send the SQL statement to the DBMS, the program builds the statement as a text string and then makes an API call to pass the contents to the DBMS." }, { "code": null, "e": 26385, "s": 26283, "text": "The application program makes API calls to check the status of its DBMS request and to handle errors." }, { "code": null, "e": 26490, "s": 26385, "text": "The application program ends its database access with an API call that disconnects it from the database." }, { "code": null, "e": 26538, "s": 26490, "text": "The two main concepts in the Python DB-API are:" }, { "code": null, "e": 26569, "s": 26538, "text": "1) Connection objects used for" }, { "code": null, "e": 26591, "s": 26569, "text": "Connect to a database" }, { "code": null, "e": 26617, "s": 26591, "text": "Manage your transactions." }, { "code": null, "e": 26657, "s": 26617, "text": "Following are a few connection methods:" }, { "code": null, "e": 26729, "s": 26657, "text": "cursor(): This method returns a new cursor object using the connection." }, { "code": null, "e": 26810, "s": 26729, "text": "commit(): This method is used to commit any pending transaction to the database." }, { "code": null, "e": 26908, "s": 26810, "text": "rollback(): This method causes the database to roll back to the start of any pending transaction." }, { "code": null, "e": 26969, "s": 26908, "text": "close(): This method is used to close a database connection." }, { "code": null, "e": 27011, "s": 26969, "text": "2) Query objects are used to run queries." }, { "code": null, "e": 27082, "s": 27011, "text": "This is a python application that uses the DB-API to query a database." }, { "code": null, "e": 27090, "s": 27082, "text": "Python3" }, { "code": "from dbmodule import connect # Create connection objectconnection = connect('databasename', 'username', 'pswd') # Create a cursor objectcursor = connection.cursor() # Run queriescursor.execute('select * from mytable')results = cursor.fetchall() # Free resourcescursor.close()connection.close()", "e": 27388, "s": 27090, "text": null }, { "code": null, "e": 28098, "s": 27388, "text": "First, we import the database module by using the connect API from that module. To open a connection to the database, you use the connection function and pass in the parameters that are the database name, username, and password. The connect function returns the connection object.After this, we create a cursor object on the connection object. The cursor is used to run queries and get the results.After running the queries using the cursor, we also use the cursor to fetch the results of the query.Finally, when the system is done running the queries, it frees all resources by closing the connection. Remember that it is always important to close connections to avoid unused connections taking up resources." }, { "code": null, "e": 28379, "s": 28098, "text": "First, we import the database module by using the connect API from that module. To open a connection to the database, you use the connection function and pass in the parameters that are the database name, username, and password. The connect function returns the connection object." }, { "code": null, "e": 28498, "s": 28379, "text": "After this, we create a cursor object on the connection object. The cursor is used to run queries and get the results." }, { "code": null, "e": 28600, "s": 28498, "text": "After running the queries using the cursor, we also use the cursor to fetch the results of the query." }, { "code": null, "e": 28811, "s": 28600, "text": "Finally, when the system is done running the queries, it frees all resources by closing the connection. Remember that it is always important to close connections to avoid unused connections taking up resources." }, { "code": null, "e": 28827, "s": 28811, "text": "Python-projects" }, { "code": null, "e": 28842, "s": 28827, "text": "python-utility" }, { "code": null, "e": 28849, "s": 28842, "text": "Python" }, { "code": null, "e": 28947, "s": 28849, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28979, "s": 28947, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29021, "s": 28979, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29063, "s": 29021, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29119, "s": 29063, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29146, "s": 29119, "text": "Python Classes and Objects" }, { "code": null, "e": 29185, "s": 29146, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29216, "s": 29185, "text": "Python | os.path.join() method" }, { "code": null, "e": 29245, "s": 29216, "text": "Create a directory in Python" }, { "code": null, "e": 29267, "s": 29245, "text": "Defaultdict in Python" } ]
Clipboard in Android - GeeksforGeeks
20 Nov, 2021 Android’s Clipboard performs copying and pasting on different data types, such as text strings, images, binary stream data, and other complex data types. Clipboard does the copying and pasting operations within the same application and between multiple applications that have implemented the clipboard framework. Clipboard has a limitation on the number of clip objects it can hold at a time. The clipboard can hold only one object at a time. If an object is put on the clipboard, the previously held object on the clipboard is dropped. The clip object can take in three types of data: Text: A string can directly be put into the clip object and then into the clipboard. We can then get the clip object from the clipboard and paste the string into the application’s text or storage fields. URI: It is used for copying complex data from the content provider. A URI object can be put into a clip object and then loaded onto the clipboard. To perform a paste operation, the clip object must be resolved into the source, such as a content provider. Intent: An intent object must be created and put into a clip object and loaded onto the clipboard. Paste action, similar to the text, can be performed. To make an application that stores some data into the clipboard and derives the data from it in Android, we follow the following steps: A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language. Step 2: Working with the activity_main.xml file Go to the activity_main.xml file which represents the UI of the application. Create an EditText where we shall supply the text to be saved in the clipboard, and a Button to perform the saving action. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!--Text must be entered here--> <EditText android:id="@+id/txtCopy" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@id/btnCopy" android:layout_centerHorizontal="true" android:hint="Type something..." /> <!--Text entered in the above field gets copied to Clipboard on this button click--> <Button android:id="@+id/btnCopy" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Copy to Clipboard" /> </RelativeLayout> Step 3: Working with the MainActivity.kt file Go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import android.content.ClipDataimport android.content.ClipboardManagerimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring the edit text and button from the layout file val copyTxt = findViewById<EditText>(R.id.txtCopy) val copyBtn = findViewById<Button>(R.id.btnCopy) // Initializing the ClipboardManager and Clip data val clipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager var clipData: ClipData // Action when the copy button is clicked copyBtn.setOnClickListener { // Text from the edit text is stored in a val val txtCopy = copyTxt!!.text.toString() // clip data is initialized with the text variable declared above clipData = ClipData.newPlainText("text", txtCopy) // Clipboard saves this clip object clipboardManager.setPrimaryClip(clipData) // A toast is shown for user reference that the text is copied to the clipboard Toast.makeText(applicationContext, "Copied to Clipboard", Toast.LENGTH_SHORT).show() } }} A sample GIF is given below to get an idea about what we are going to do in this section. Step 1: Working with the activity_main.xml file Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!--Text from the clip object will be shown here*--> <TextView android:id="@+id/txtShow" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@id/btnShow" android:layout_centerHorizontal="true" android:hint="Clipboard Data" /> <!--*on this button click--> <Button android:id="@+id/btnShow" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Show Clipboard Data" /> </RelativeLayout> Step 2: Working with the MainActivity.kt file Go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import android.content.ClipboardManagerimport android.os.Bundleimport android.widget.Buttonimport android.widget.TextViewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declare the textview and button from the layout file val pasteTxt = findViewById<TextView>(R.id.txtShow) val btnPaste = findViewById<Button>(R.id.btnShow) // Declaring the clipboard manager val clipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager // Action on paste button click btnPaste.setOnClickListener { // Storing the clip data in a variable val pData = clipboardManager.primaryClip // Retrieving the items val item = pData!!.getItemAt(0) // item is converted to string and stored in a variable val txtPaste = item.text.toString() // Textview is set as txtPaste string pasteTxt!!.text = txtPaste // Toast for user reference Toast.makeText(applicationContext, "Pasted from Clipboard", Toast.LENGTH_SHORT).show() } }} sumitgumber28 android Android-View Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Resource Raw Folder in Android Studio Android RecyclerView in Kotlin Content Providers in Android with Example Broadcast Receiver in Android With Example Android UI Layouts Kotlin Array Android RecyclerView in Kotlin Content Providers in Android with Example
[ { "code": null, "e": 26303, "s": 26275, "text": "\n20 Nov, 2021" }, { "code": null, "e": 26889, "s": 26303, "text": "Android’s Clipboard performs copying and pasting on different data types, such as text strings, images, binary stream data, and other complex data types. Clipboard does the copying and pasting operations within the same application and between multiple applications that have implemented the clipboard framework. Clipboard has a limitation on the number of clip objects it can hold at a time. The clipboard can hold only one object at a time. If an object is put on the clipboard, the previously held object on the clipboard is dropped. The clip object can take in three types of data:" }, { "code": null, "e": 27093, "s": 26889, "text": "Text: A string can directly be put into the clip object and then into the clipboard. We can then get the clip object from the clipboard and paste the string into the application’s text or storage fields." }, { "code": null, "e": 27348, "s": 27093, "text": "URI: It is used for copying complex data from the content provider. A URI object can be put into a clip object and then loaded onto the clipboard. To perform a paste operation, the clip object must be resolved into the source, such as a content provider." }, { "code": null, "e": 27500, "s": 27348, "text": "Intent: An intent object must be created and put into a clip object and loaded onto the clipboard. Paste action, similar to the text, can be performed." }, { "code": null, "e": 27636, "s": 27500, "text": "To make an application that stores some data into the clipboard and derives the data from it in Android, we follow the following steps:" }, { "code": null, "e": 27803, "s": 27636, "text": "A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. " }, { "code": null, "e": 27832, "s": 27803, "text": "Step 1: Create a New Project" }, { "code": null, "e": 27996, "s": 27832, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language." }, { "code": null, "e": 28044, "s": 27996, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 28294, "s": 28044, "text": "Go to the activity_main.xml file which represents the UI of the application. Create an EditText where we shall supply the text to be saved in the clipboard, and a Button to perform the saving action. Below is the code for the activity_main.xml file." }, { "code": null, "e": 28298, "s": 28294, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\"> <!--Text must be entered here--> <EditText android:id=\"@+id/txtCopy\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_above=\"@id/btnCopy\" android:layout_centerHorizontal=\"true\" android:hint=\"Type something...\" /> <!--Text entered in the above field gets copied to Clipboard on this button click--> <Button android:id=\"@+id/btnCopy\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"Copy to Clipboard\" /> </RelativeLayout>", "e": 29166, "s": 28298, "text": null }, { "code": null, "e": 29212, "s": 29166, "text": "Step 3: Working with the MainActivity.kt file" }, { "code": null, "e": 29399, "s": 29212, "text": "Go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 29406, "s": 29399, "text": "Kotlin" }, { "code": "import android.content.ClipDataimport android.content.ClipboardManagerimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring the edit text and button from the layout file val copyTxt = findViewById<EditText>(R.id.txtCopy) val copyBtn = findViewById<Button>(R.id.btnCopy) // Initializing the ClipboardManager and Clip data val clipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager var clipData: ClipData // Action when the copy button is clicked copyBtn.setOnClickListener { // Text from the edit text is stored in a val val txtCopy = copyTxt!!.text.toString() // clip data is initialized with the text variable declared above clipData = ClipData.newPlainText(\"text\", txtCopy) // Clipboard saves this clip object clipboardManager.setPrimaryClip(clipData) // A toast is shown for user reference that the text is copied to the clipboard Toast.makeText(applicationContext, \"Copied to Clipboard\", Toast.LENGTH_SHORT).show() } }}", "e": 30830, "s": 29406, "text": null }, { "code": null, "e": 30920, "s": 30830, "text": "A sample GIF is given below to get an idea about what we are going to do in this section." }, { "code": null, "e": 30968, "s": 30920, "text": "Step 1: Working with the activity_main.xml file" }, { "code": null, "e": 31018, "s": 30968, "text": "Below is the code for the activity_main.xml file." }, { "code": null, "e": 31022, "s": 31018, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\"> <!--Text from the clip object will be shown here*--> <TextView android:id=\"@+id/txtShow\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_above=\"@id/btnShow\" android:layout_centerHorizontal=\"true\" android:hint=\"Clipboard Data\" /> <!--*on this button click--> <Button android:id=\"@+id/btnShow\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"Show Clipboard Data\" /> </RelativeLayout>", "e": 31845, "s": 31022, "text": null }, { "code": null, "e": 31891, "s": 31845, "text": "Step 2: Working with the MainActivity.kt file" }, { "code": null, "e": 32078, "s": 31891, "text": "Go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 32085, "s": 32078, "text": "Kotlin" }, { "code": "import android.content.ClipboardManagerimport android.os.Bundleimport android.widget.Buttonimport android.widget.TextViewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declare the textview and button from the layout file val pasteTxt = findViewById<TextView>(R.id.txtShow) val btnPaste = findViewById<Button>(R.id.btnShow) // Declaring the clipboard manager val clipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager // Action on paste button click btnPaste.setOnClickListener { // Storing the clip data in a variable val pData = clipboardManager.primaryClip // Retrieving the items val item = pData!!.getItemAt(0) // item is converted to string and stored in a variable val txtPaste = item.text.toString() // Textview is set as txtPaste string pasteTxt!!.text = txtPaste // Toast for user reference Toast.makeText(applicationContext, \"Pasted from Clipboard\", Toast.LENGTH_SHORT).show() } }}", "e": 33401, "s": 32085, "text": null }, { "code": null, "e": 33415, "s": 33401, "text": "sumitgumber28" }, { "code": null, "e": 33423, "s": 33415, "text": "android" }, { "code": null, "e": 33436, "s": 33423, "text": "Android-View" }, { "code": null, "e": 33444, "s": 33436, "text": "Android" }, { "code": null, "e": 33451, "s": 33444, "text": "Kotlin" }, { "code": null, "e": 33459, "s": 33451, "text": "Android" }, { "code": null, "e": 33557, "s": 33459, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33615, "s": 33557, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 33658, "s": 33615, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 33696, "s": 33658, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 33727, "s": 33696, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 33769, "s": 33727, "text": "Content Providers in Android with Example" }, { "code": null, "e": 33812, "s": 33769, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 33831, "s": 33812, "text": "Android UI Layouts" }, { "code": null, "e": 33844, "s": 33831, "text": "Kotlin Array" }, { "code": null, "e": 33875, "s": 33844, "text": "Android RecyclerView in Kotlin" } ]
error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++ - GeeksforGeeks
11 Jan, 2022 Pre-requisite: Function Overloading in C++ Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. Two or more functions are said to be overloaded if they differ in any of the following- The number of arguments.Order of arguments.Type of arguments. The number of arguments. Order of arguments. Type of arguments. In Function overloading, sometimes a situation can occur when the compiler is unable to choose between two correctly overloaded functions. This situation is said to be ambiguous. Ambiguous statements are error-generating statements and the programs containing ambiguity will not compile. Automatic type conversions are the main cause of ambiguity. In C++, the type of argument that is used to call the function is converted into the type of parameters defined by the function. Let’s understand ambiguity through a few examples. Call of overloaded function is ambiguous Example 1: Call of overloaded ‘test(char)’ is ambiguous How this ambiguity occurs:Below is the C++ program to demonstrate the ambiguity. C++ // C++ program to implement// the above approach#include <iostream>using namespace std; // Overloaded Function with// float type parametervoid test(float f){ cout << "Overloaded Function with float " << "parameter being called";} // Overloaded Function with// double type parametervoid test(double d){ cout << "Overloaded Function with double " << "parameter being called";} // Driver codeint main(){ // Overloaded Function called // with char type value test('a'); return 0;} Output: prog.cpp: In function ‘int main()’: prog.cpp:25:11: error: call of overloaded ‘test(char)’ is ambiguous test(‘a’); ^ prog.cpp:8:6: note: candidate: void test(float) void test(float f) ^ prog.cpp:15:6: note: candidate: void test(double) void test(double d) ^ Why ambiguity occurs: When there is no exact type match, the compiler looks for the closest match. The closest match for “test(‘a’);” will be “void test(int a)”, since it is not present, void test(double d) and void (float f)will cause ambiguity. Both are valid conversions. This confusion causes an error message to be displayed and prevents the program from compiling. Note:According to the C language specification, any integer type shorter than int, for example, bool, char, short are implicitly converted to int. A char fits into an int without overflowing or losing precision, which explains the first code. But an int doesn’t fit into a char (overflow), double (lack of precision), or int* (incompatible type). How to resolve ambiguity: There are two ways to resolve this ambiguity: Typecast char to float.Remove either one of the ambiguity generating functions float or double and add overloaded function with an int type parameter. Typecast char to float. Remove either one of the ambiguity generating functions float or double and add overloaded function with an int type parameter. Solution 1: Typecast char to float Below is the C++ program to demonstrate how typecasting char to float resolves the issue. C++ // C++ program to implement// the above approach#include <iostream>using namespace std; // Overloaded Function with// float type parametervoid test(float f){ cout << "Overloaded Function with float " << "parameter being called";} // Overloaded Function with// double type parametervoid test(double d){ cout << "Overloaded Function with double " << "parameter being called";} // Driver codeint main(){ // Overloaded Function called // with char type value // typecasted to float test((float)('a')); return 0;} Overloaded Function with float parameter being called Solution 2: Remove either one of the ambiguity generating functions float or double and add overloaded function with an int type parameter. Below is the C++ program to demonstrate how adding an overloading function with an int type parameter can resolve the ambiguity in the above code. C++ // C++ program to implement// the above approach#include <iostream>using namespace std; // Overloaded function with// int type parametervoid test(int f){ cout << "Overloaded Function with " << "int type parameter called";} // Overloaded function with// double type parametervoid test(double d){ cout << "Overloaded Function with " << "double type parameter called";} // Driver codeint main(){ // Overloaded Function called // with char type value test('a'); return 0;} Overloaded Function with int type parameter called Example 2: Call of overloaded ‘test(float)’ is ambiguous How this ambiguity occurs:Below is the C++ program to demonstrate what will happen in the scenario when the type of float value is used to call the overloaded function and there is no function with the float or double parameters. C++ // C++ program to implement// the above approach#include <iostream>using namespace std; // Overloaded function with// int type parametervoid test(int f){ cout << "Overloaded Function with " << "int type parameter called";} // Overloaded function with// long type parametervoid test(long l){ cout << "Overloaded Function with " << "long type parameter called";} // Driver codeint main(){ // Overloaded Function called // with float type value test(2.5f); return 0;} Output: prog.cpp: In function ‘int main()’: prog.cpp:25:12: error: call of overloaded ‘test(float)’ is ambiguous test(2.5f); ^ prog.cpp:8:6: note: candidate: void test(int) void test(int f) ^ prog.cpp:15:6: note: candidate: void test(long int) void test(long d) ^ Why ambiguity occurs:The above code will throw an error because the test(2.5f) function call will look for float function if not present it is only promoted to double, but there is no function definition with double or float type of parameter. Unless explicitly specified all floating-point literals are automatically of type double in C++. In this ambiguity, the variable of a float type is implicitly converted to double type and if there is no overloaded function of float or double type and the function is called with a float value then the program will throw an error. Note:The float is converted to double under the following situations: The float is an argument to a function call, corresponding to a parameter type double in a function prototype. A binary operator has double and float as two argument types. A conditional operator has double and float as a second and third operand. The float value is cast to double. The float value is assigned to double. How to resolve ambiguity: There are two ways to resolve the ambiguity- Typecast float to int.Remove either one of the ambiguity generating functions int or long and add overloaded function with a double type parameter. Typecast float to int. Remove either one of the ambiguity generating functions int or long and add overloaded function with a double type parameter. Solution 1: Typecast float to int Below is the C++ program to demonstrate how typecasting float to int resolves the issue. C++ // C++ program to implement// the above approach#include <iostream>using namespace std; // Overloaded function with// int type parametervoid test(int f){ cout << "Overloaded Function with " << "int type parameter called";} // Overloaded function with// long type parametervoid test(long l){ cout << "Overloaded Function with " << "long type parameter called";} // Driver codeint main(){ // Overloaded Function called // with float type value test((int)(2.5f)); return 0;} Overloaded Function with int type parameter called Solution 2: Remove either one of the ambiguity generating functions int or long and add overloaded function with a double type parameter. Below is the C++ program to demonstrate how to resolve this ambiguity by adding an overloaded function with double type parameters. C++ // C++ program to implement// the above approach#include <iostream>using namespace std; // Overloaded function with// int type parametervoid test(double d){ cout << "Overloaded Function with " << "double type parameter called";} // Overloaded function with// long type parametervoid test(long l){ cout << "Overloaded Function with " << "long type parameter called";} // Driver codeint main(){ // Overloaded Function called // with float type value test(2.5f); return 0;} Overloaded Function with double type parameter called Call of overloaded function with different number of arguments Redefinition of ‘void test(int, int) function:Let’s look at another ambiguity scenario where ambiguity occurs when it is two-parameter and one of the parameters has a default value set. C++ // C++ program to implement// the above approach#include <iostream>using namespace std; // Overloaded Function with// one int type parametervoid test(int i){ cout << "Overloaded function with " << "one int parameter called " << endl; cout << i;} // Overloaded Functionwith// two int type parametervoid test(int i, int j = 5){ int sum; sum = i + j; cout << "Overloaded function with " << "two int parameter called " << endl; cout << sum;} // Driver codeint main(){ // Overloaded Function called // with two int values // Unambiguous call test(10, 11); // Overloaded Function called // with one int value // Ambiguous call test(10); return 0;} Output: prog.cpp: In function ‘void test(int, int)’: prog.cpp:17:6: error: redefinition of ‘void test(int, int)’ void test(int i, int j = 5) ^ prog.cpp:8:6: note: ‘void test(int, int)’ previously defined here void test(int i, int j) ^ prog.cpp: In function ‘int main()’: prog.cpp:35:10: error: too few arguments to function ‘void test(int, int)’ test(10); ^ prog.cpp:8:6: note: declared here void test(int i, int j) ^ Why ambiguity occurs: Here, in the unambiguous call statement test(10, 11) two arguments are specified, therefore there is no ambiguity. In the ambiguous call statement test(10), the compiler gets confused about whether to call the first function test() which takes one argument or to call the second test() function with two arguments out of which one is the default. This causes the program to throw an error. How to resolve the ambiguity: One solution to resolve the ambiguity is to remove the default value from the overloaded function with two int parameters. Below is the C++ program to demonstrate the above approach- C++ // C++ program to implement// the above approach#include <iostream>using namespace std; // Overloaded Function with// one int type parametervoid test(int i){ cout << "Overloaded function with " << "one int parameter called " << endl; cout << i << endl;} // Overloaded Functionwith// two int type parametervoid test(int i, int j){ int sum; sum = i + j; cout << "Overloaded function with " << "two int parameter called " << endl; cout << sum << endl;} // Driver codeint main(){ // Overloaded Function called // with two int values // Unambiguous call test(10, 11); // Overloaded Function called // with one int value // Ambiguous call test(10); return 0;} Overloaded function with two int parameter called 21 Overloaded function with one int parameter called 10 C++ Program Output CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Arrow operator -> in C/C++ with Examples Output of Java Program | Set 1 delete keyword in C++ Output of C Programs | Set 1 Output of Java programs | Set 13 (Collections)
[ { "code": null, "e": 25367, "s": 25339, "text": "\n11 Jan, 2022" }, { "code": null, "e": 25410, "s": 25367, "text": "Pre-requisite: Function Overloading in C++" }, { "code": null, "e": 25730, "s": 25410, "text": "Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. Two or more functions are said to be overloaded if they differ in any of the following-" }, { "code": null, "e": 25792, "s": 25730, "text": "The number of arguments.Order of arguments.Type of arguments." }, { "code": null, "e": 25817, "s": 25792, "text": "The number of arguments." }, { "code": null, "e": 25837, "s": 25817, "text": "Order of arguments." }, { "code": null, "e": 25856, "s": 25837, "text": "Type of arguments." }, { "code": null, "e": 26036, "s": 25856, "text": "In Function overloading, sometimes a situation can occur when the compiler is unable to choose between two correctly overloaded functions. This situation is said to be ambiguous. " }, { "code": null, "e": 26335, "s": 26036, "text": "Ambiguous statements are error-generating statements and the programs containing ambiguity will not compile. Automatic type conversions are the main cause of ambiguity. In C++, the type of argument that is used to call the function is converted into the type of parameters defined by the function. " }, { "code": null, "e": 26386, "s": 26335, "text": "Let’s understand ambiguity through a few examples." }, { "code": null, "e": 26427, "s": 26386, "text": "Call of overloaded function is ambiguous" }, { "code": null, "e": 26483, "s": 26427, "text": "Example 1: Call of overloaded ‘test(char)’ is ambiguous" }, { "code": null, "e": 26564, "s": 26483, "text": "How this ambiguity occurs:Below is the C++ program to demonstrate the ambiguity." }, { "code": null, "e": 26568, "s": 26564, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Overloaded Function with// float type parametervoid test(float f){ cout << \"Overloaded Function with float \" << \"parameter being called\";} // Overloaded Function with// double type parametervoid test(double d){ cout << \"Overloaded Function with double \" << \"parameter being called\";} // Driver codeint main(){ // Overloaded Function called // with char type value test('a'); return 0;}", "e": 27084, "s": 26568, "text": null }, { "code": null, "e": 27092, "s": 27084, "text": "Output:" }, { "code": null, "e": 27128, "s": 27092, "text": "prog.cpp: In function ‘int main()’:" }, { "code": null, "e": 27196, "s": 27128, "text": "prog.cpp:25:11: error: call of overloaded ‘test(char)’ is ambiguous" }, { "code": null, "e": 27209, "s": 27196, "text": " test(‘a’);" }, { "code": null, "e": 27221, "s": 27209, "text": " ^" }, { "code": null, "e": 27269, "s": 27221, "text": "prog.cpp:8:6: note: candidate: void test(float)" }, { "code": null, "e": 27290, "s": 27269, "text": "void test(float f) " }, { "code": null, "e": 27297, "s": 27290, "text": " ^" }, { "code": null, "e": 27347, "s": 27297, "text": "prog.cpp:15:6: note: candidate: void test(double)" }, { "code": null, "e": 27369, "s": 27347, "text": "void test(double d) " }, { "code": null, "e": 27376, "s": 27369, "text": " ^" }, { "code": null, "e": 27398, "s": 27376, "text": "Why ambiguity occurs:" }, { "code": null, "e": 27748, "s": 27398, "text": " When there is no exact type match, the compiler looks for the closest match. The closest match for “test(‘a’);” will be “void test(int a)”, since it is not present, void test(double d) and void (float f)will cause ambiguity. Both are valid conversions. This confusion causes an error message to be displayed and prevents the program from compiling." }, { "code": null, "e": 27895, "s": 27748, "text": "Note:According to the C language specification, any integer type shorter than int, for example, bool, char, short are implicitly converted to int." }, { "code": null, "e": 28095, "s": 27895, "text": "A char fits into an int without overflowing or losing precision, which explains the first code. But an int doesn’t fit into a char (overflow), double (lack of precision), or int* (incompatible type)." }, { "code": null, "e": 28121, "s": 28095, "text": "How to resolve ambiguity:" }, { "code": null, "e": 28167, "s": 28121, "text": "There are two ways to resolve this ambiguity:" }, { "code": null, "e": 28318, "s": 28167, "text": "Typecast char to float.Remove either one of the ambiguity generating functions float or double and add overloaded function with an int type parameter." }, { "code": null, "e": 28342, "s": 28318, "text": "Typecast char to float." }, { "code": null, "e": 28470, "s": 28342, "text": "Remove either one of the ambiguity generating functions float or double and add overloaded function with an int type parameter." }, { "code": null, "e": 28505, "s": 28470, "text": "Solution 1: Typecast char to float" }, { "code": null, "e": 28595, "s": 28505, "text": "Below is the C++ program to demonstrate how typecasting char to float resolves the issue." }, { "code": null, "e": 28599, "s": 28595, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Overloaded Function with// float type parametervoid test(float f){ cout << \"Overloaded Function with float \" << \"parameter being called\";} // Overloaded Function with// double type parametervoid test(double d){ cout << \"Overloaded Function with double \" << \"parameter being called\";} // Driver codeint main(){ // Overloaded Function called // with char type value // typecasted to float test((float)('a')); return 0;}", "e": 29150, "s": 28599, "text": null }, { "code": null, "e": 29204, "s": 29150, "text": "Overloaded Function with float parameter being called" }, { "code": null, "e": 29344, "s": 29204, "text": "Solution 2: Remove either one of the ambiguity generating functions float or double and add overloaded function with an int type parameter." }, { "code": null, "e": 29491, "s": 29344, "text": "Below is the C++ program to demonstrate how adding an overloading function with an int type parameter can resolve the ambiguity in the above code." }, { "code": null, "e": 29495, "s": 29491, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Overloaded function with// int type parametervoid test(int f){ cout << \"Overloaded Function with \" << \"int type parameter called\";} // Overloaded function with// double type parametervoid test(double d){ cout << \"Overloaded Function with \" << \"double type parameter called\";} // Driver codeint main(){ // Overloaded Function called // with char type value test('a'); return 0;}", "e": 30001, "s": 29495, "text": null }, { "code": null, "e": 30052, "s": 30001, "text": "Overloaded Function with int type parameter called" }, { "code": null, "e": 30109, "s": 30052, "text": "Example 2: Call of overloaded ‘test(float)’ is ambiguous" }, { "code": null, "e": 30339, "s": 30109, "text": "How this ambiguity occurs:Below is the C++ program to demonstrate what will happen in the scenario when the type of float value is used to call the overloaded function and there is no function with the float or double parameters." }, { "code": null, "e": 30343, "s": 30339, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Overloaded function with// int type parametervoid test(int f){ cout << \"Overloaded Function with \" << \"int type parameter called\";} // Overloaded function with// long type parametervoid test(long l){ cout << \"Overloaded Function with \" << \"long type parameter called\";} // Driver codeint main(){ // Overloaded Function called // with float type value test(2.5f); return 0;}", "e": 30845, "s": 30343, "text": null }, { "code": null, "e": 30853, "s": 30845, "text": "Output:" }, { "code": null, "e": 30889, "s": 30853, "text": "prog.cpp: In function ‘int main()’:" }, { "code": null, "e": 30958, "s": 30889, "text": "prog.cpp:25:12: error: call of overloaded ‘test(float)’ is ambiguous" }, { "code": null, "e": 30972, "s": 30958, "text": " test(2.5f);" }, { "code": null, "e": 30985, "s": 30972, "text": " ^" }, { "code": null, "e": 31031, "s": 30985, "text": "prog.cpp:8:6: note: candidate: void test(int)" }, { "code": null, "e": 31050, "s": 31031, "text": "void test(int f) " }, { "code": null, "e": 31057, "s": 31050, "text": " ^" }, { "code": null, "e": 31109, "s": 31057, "text": "prog.cpp:15:6: note: candidate: void test(long int)" }, { "code": null, "e": 31129, "s": 31109, "text": "void test(long d) " }, { "code": null, "e": 31136, "s": 31129, "text": " ^" }, { "code": null, "e": 31380, "s": 31136, "text": "Why ambiguity occurs:The above code will throw an error because the test(2.5f) function call will look for float function if not present it is only promoted to double, but there is no function definition with double or float type of parameter." }, { "code": null, "e": 31711, "s": 31380, "text": "Unless explicitly specified all floating-point literals are automatically of type double in C++. In this ambiguity, the variable of a float type is implicitly converted to double type and if there is no overloaded function of float or double type and the function is called with a float value then the program will throw an error." }, { "code": null, "e": 31781, "s": 31711, "text": "Note:The float is converted to double under the following situations:" }, { "code": null, "e": 31892, "s": 31781, "text": "The float is an argument to a function call, corresponding to a parameter type double in a function prototype." }, { "code": null, "e": 31954, "s": 31892, "text": "A binary operator has double and float as two argument types." }, { "code": null, "e": 32029, "s": 31954, "text": "A conditional operator has double and float as a second and third operand." }, { "code": null, "e": 32064, "s": 32029, "text": "The float value is cast to double." }, { "code": null, "e": 32103, "s": 32064, "text": "The float value is assigned to double." }, { "code": null, "e": 32129, "s": 32103, "text": "How to resolve ambiguity:" }, { "code": null, "e": 32174, "s": 32129, "text": "There are two ways to resolve the ambiguity-" }, { "code": null, "e": 32322, "s": 32174, "text": "Typecast float to int.Remove either one of the ambiguity generating functions int or long and add overloaded function with a double type parameter." }, { "code": null, "e": 32345, "s": 32322, "text": "Typecast float to int." }, { "code": null, "e": 32471, "s": 32345, "text": "Remove either one of the ambiguity generating functions int or long and add overloaded function with a double type parameter." }, { "code": null, "e": 32505, "s": 32471, "text": "Solution 1: Typecast float to int" }, { "code": null, "e": 32594, "s": 32505, "text": "Below is the C++ program to demonstrate how typecasting float to int resolves the issue." }, { "code": null, "e": 32598, "s": 32594, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Overloaded function with// int type parametervoid test(int f){ cout << \"Overloaded Function with \" << \"int type parameter called\";} // Overloaded function with// long type parametervoid test(long l){ cout << \"Overloaded Function with \" << \"long type parameter called\";} // Driver codeint main(){ // Overloaded Function called // with float type value test((int)(2.5f)); return 0;}", "e": 33107, "s": 32598, "text": null }, { "code": null, "e": 33158, "s": 33107, "text": "Overloaded Function with int type parameter called" }, { "code": null, "e": 33296, "s": 33158, "text": "Solution 2: Remove either one of the ambiguity generating functions int or long and add overloaded function with a double type parameter." }, { "code": null, "e": 33428, "s": 33296, "text": "Below is the C++ program to demonstrate how to resolve this ambiguity by adding an overloaded function with double type parameters." }, { "code": null, "e": 33432, "s": 33428, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Overloaded function with// int type parametervoid test(double d){ cout << \"Overloaded Function with \" << \"double type parameter called\";} // Overloaded function with// long type parametervoid test(long l){ cout << \"Overloaded Function with \" << \"long type parameter called\";} // Driver codeint main(){ // Overloaded Function called // with float type value test(2.5f); return 0;}", "e": 33940, "s": 33432, "text": null }, { "code": null, "e": 33994, "s": 33940, "text": "Overloaded Function with double type parameter called" }, { "code": null, "e": 34057, "s": 33994, "text": "Call of overloaded function with different number of arguments" }, { "code": null, "e": 34243, "s": 34057, "text": "Redefinition of ‘void test(int, int) function:Let’s look at another ambiguity scenario where ambiguity occurs when it is two-parameter and one of the parameters has a default value set." }, { "code": null, "e": 34247, "s": 34243, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Overloaded Function with// one int type parametervoid test(int i){ cout << \"Overloaded function with \" << \"one int parameter called \" << endl; cout << i;} // Overloaded Functionwith// two int type parametervoid test(int i, int j = 5){ int sum; sum = i + j; cout << \"Overloaded function with \" << \"two int parameter called \" << endl; cout << sum;} // Driver codeint main(){ // Overloaded Function called // with two int values // Unambiguous call test(10, 11); // Overloaded Function called // with one int value // Ambiguous call test(10); return 0;}", "e": 34959, "s": 34247, "text": null }, { "code": null, "e": 34967, "s": 34959, "text": "Output:" }, { "code": null, "e": 35012, "s": 34967, "text": "prog.cpp: In function ‘void test(int, int)’:" }, { "code": null, "e": 35072, "s": 35012, "text": "prog.cpp:17:6: error: redefinition of ‘void test(int, int)’" }, { "code": null, "e": 35102, "s": 35072, "text": "void test(int i, int j = 5) " }, { "code": null, "e": 35109, "s": 35102, "text": " ^" }, { "code": null, "e": 35175, "s": 35109, "text": "prog.cpp:8:6: note: ‘void test(int, int)’ previously defined here" }, { "code": null, "e": 35201, "s": 35175, "text": "void test(int i, int j) " }, { "code": null, "e": 35208, "s": 35201, "text": " ^" }, { "code": null, "e": 35244, "s": 35208, "text": "prog.cpp: In function ‘int main()’:" }, { "code": null, "e": 35319, "s": 35244, "text": "prog.cpp:35:10: error: too few arguments to function ‘void test(int, int)’" }, { "code": null, "e": 35331, "s": 35319, "text": " test(10);" }, { "code": null, "e": 35342, "s": 35331, "text": " ^" }, { "code": null, "e": 35376, "s": 35342, "text": "prog.cpp:8:6: note: declared here" }, { "code": null, "e": 35402, "s": 35376, "text": "void test(int i, int j) " }, { "code": null, "e": 35409, "s": 35402, "text": " ^" }, { "code": null, "e": 35431, "s": 35409, "text": "Why ambiguity occurs:" }, { "code": null, "e": 35821, "s": 35431, "text": "Here, in the unambiguous call statement test(10, 11) two arguments are specified, therefore there is no ambiguity. In the ambiguous call statement test(10), the compiler gets confused about whether to call the first function test() which takes one argument or to call the second test() function with two arguments out of which one is the default. This causes the program to throw an error." }, { "code": null, "e": 35851, "s": 35821, "text": "How to resolve the ambiguity:" }, { "code": null, "e": 36034, "s": 35851, "text": "One solution to resolve the ambiguity is to remove the default value from the overloaded function with two int parameters. Below is the C++ program to demonstrate the above approach-" }, { "code": null, "e": 36038, "s": 36034, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Overloaded Function with// one int type parametervoid test(int i){ cout << \"Overloaded function with \" << \"one int parameter called \" << endl; cout << i << endl;} // Overloaded Functionwith// two int type parametervoid test(int i, int j){ int sum; sum = i + j; cout << \"Overloaded function with \" << \"two int parameter called \" << endl; cout << sum << endl;} // Driver codeint main(){ // Overloaded Function called // with two int values // Unambiguous call test(10, 11); // Overloaded Function called // with one int value // Ambiguous call test(10); return 0;}", "e": 36762, "s": 36038, "text": null }, { "code": null, "e": 36870, "s": 36762, "text": "Overloaded function with two int parameter called \n21\nOverloaded function with one int parameter called \n10" }, { "code": null, "e": 36874, "s": 36870, "text": "C++" }, { "code": null, "e": 36889, "s": 36874, "text": "Program Output" }, { "code": null, "e": 36893, "s": 36889, "text": "CPP" }, { "code": null, "e": 36991, "s": 36893, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37019, "s": 36991, "text": "Operator Overloading in C++" }, { "code": null, "e": 37039, "s": 37019, "text": "Polymorphism in C++" }, { "code": null, "e": 37072, "s": 37039, "text": "Friend class and function in C++" }, { "code": null, "e": 37096, "s": 37072, "text": "Sorting a vector in C++" }, { "code": null, "e": 37121, "s": 37096, "text": "std::string class in C++" }, { "code": null, "e": 37162, "s": 37121, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 37193, "s": 37162, "text": "Output of Java Program | Set 1" }, { "code": null, "e": 37215, "s": 37193, "text": "delete keyword in C++" }, { "code": null, "e": 37244, "s": 37215, "text": "Output of C Programs | Set 1" } ]
Convert string to char array in C++ - GeeksforGeeks
06 Jul, 2021 Many of us have encountered error ‘cannot convert std::string to char[] or char* data type’. Examples: Input : string s = "geeksforgeeks" ; Output : char s[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's' } ; Input : string s = "coding" ; Output : char s[] = { 'c', 'o', 'd', 'i', 'n', 'g' } ; Method 1 A way to do this is to copy the contents of the string to char array. This can be done with the help of c_str() and strcpy() function of library cstring. The c_str() function is used to return a pointer to an array that contains a null terminated sequence of character representing the current value of the string.Syntax: const char* c_str() const ; If there is an exception thrown then there are no changes in the string. But when we need to find or access the individual elements then we copy it to a char array using strcpy() function. After copying it, we can use it just like a simple array. The length of the char array taken should not be less than the length of input string. CPP // CPP program to convert string// to char array#include <iostream>#include <cstring> using namespace std; // driver codeint main(){ // assigning value to string s string s = "geeksforgeeks"; int n = s.length(); // declaring character array char char_array[n + 1]; // copying the contents of the // string to char array strcpy(char_array, s.c_str()); for (int i = 0; i < n; i++) cout << char_array[i]; return 0;} geeksforgeeks Method 2: CPP // CPP program to convert string// to char array#include <iostream>#include <string> using namespace std; // driver codeint main(){ // assigning value to string s string s("geeksforgeeks"); // declaring character array : p char p[s.length()]; int i; for (i = 0; i < sizeof(p); i++) { p[i] = s[i]; cout << p[i]; } return 0;} geeksforgeeks Method 3: This is the simplest and most efficient one. We can directly assign the address of 1st character of the string to a pointer to char. This should be the preferred method unless your logic needs a copy of the string. C++14 // CPP program for the above approach#include <cstring>#include <iostream>#include <string>using namespace std; // Driver Codeint main(){ char* char_arr; string str_obj("GeeksForGeeks"); char_arr = &str_obj[0]; cout << char_arr; return 0;} GeeksForGeeks Method 4: An alternate way of Method 1 can be such, without using strcpy() function. C++14 // CPP program to convert string// to char array#include <iostream>#include <cstring> using namespace std; // driver codeint main(){ // assigning value to string s string st = "GeeksForGeeks"; //the c_str() function returns a const pointer //to null terminated contents. const char *str = st.c_str(); //printing the char array cout << str; return 0;} GeeksForGeeks akshaykmalik arupjyoti_dutta nidhi_biet manu singhal pujakumarinwd0039 singhbishalkumarsingh cpp-string C++ Strings Strings CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Bitwise Operators in C/C++ Virtual Function in C++ Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 25933, "s": 25905, "text": "\n06 Jul, 2021" }, { "code": null, "e": 26037, "s": 25933, "text": "Many of us have encountered error ‘cannot convert std::string to char[] or char* data type’. Examples: " }, { "code": null, "e": 26270, "s": 26037, "text": "Input : string s = \"geeksforgeeks\" ;\nOutput : char s[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o',\n 'r', 'g', 'e', 'e', 'k', 's' } ;\nInput : string s = \"coding\" ;\nOutput : char s[] = { 'c', 'o', 'd', 'i', 'n', 'g' } ;" }, { "code": null, "e": 26602, "s": 26270, "text": "Method 1 A way to do this is to copy the contents of the string to char array. This can be done with the help of c_str() and strcpy() function of library cstring. The c_str() function is used to return a pointer to an array that contains a null terminated sequence of character representing the current value of the string.Syntax: " }, { "code": null, "e": 26630, "s": 26602, "text": "const char* c_str() const ;" }, { "code": null, "e": 26965, "s": 26630, "text": "If there is an exception thrown then there are no changes in the string. But when we need to find or access the individual elements then we copy it to a char array using strcpy() function. After copying it, we can use it just like a simple array. The length of the char array taken should not be less than the length of input string. " }, { "code": null, "e": 26969, "s": 26965, "text": "CPP" }, { "code": "// CPP program to convert string// to char array#include <iostream>#include <cstring> using namespace std; // driver codeint main(){ // assigning value to string s string s = \"geeksforgeeks\"; int n = s.length(); // declaring character array char char_array[n + 1]; // copying the contents of the // string to char array strcpy(char_array, s.c_str()); for (int i = 0; i < n; i++) cout << char_array[i]; return 0;}", "e": 27424, "s": 26969, "text": null }, { "code": null, "e": 27438, "s": 27424, "text": "geeksforgeeks" }, { "code": null, "e": 27448, "s": 27438, "text": "Method 2:" }, { "code": null, "e": 27452, "s": 27448, "text": "CPP" }, { "code": "// CPP program to convert string// to char array#include <iostream>#include <string> using namespace std; // driver codeint main(){ // assigning value to string s string s(\"geeksforgeeks\"); // declaring character array : p char p[s.length()]; int i; for (i = 0; i < sizeof(p); i++) { p[i] = s[i]; cout << p[i]; } return 0;}", "e": 27815, "s": 27452, "text": null }, { "code": null, "e": 27829, "s": 27815, "text": "geeksforgeeks" }, { "code": null, "e": 27839, "s": 27829, "text": "Method 3:" }, { "code": null, "e": 28056, "s": 27839, "text": "This is the simplest and most efficient one. We can directly assign the address of 1st character of the string to a pointer to char. This should be the preferred method unless your logic needs a copy of the string. " }, { "code": null, "e": 28062, "s": 28056, "text": "C++14" }, { "code": "// CPP program for the above approach#include <cstring>#include <iostream>#include <string>using namespace std; // Driver Codeint main(){ char* char_arr; string str_obj(\"GeeksForGeeks\"); char_arr = &str_obj[0]; cout << char_arr; return 0;}", "e": 28317, "s": 28062, "text": null }, { "code": null, "e": 28331, "s": 28317, "text": "GeeksForGeeks" }, { "code": null, "e": 28341, "s": 28331, "text": "Method 4:" }, { "code": null, "e": 28416, "s": 28341, "text": "An alternate way of Method 1 can be such, without using strcpy() function." }, { "code": null, "e": 28422, "s": 28416, "text": "C++14" }, { "code": "// CPP program to convert string// to char array#include <iostream>#include <cstring> using namespace std; // driver codeint main(){ // assigning value to string s string st = \"GeeksForGeeks\"; //the c_str() function returns a const pointer //to null terminated contents. const char *str = st.c_str(); //printing the char array cout << str; return 0;}", "e": 28797, "s": 28422, "text": null }, { "code": null, "e": 28811, "s": 28797, "text": "GeeksForGeeks" }, { "code": null, "e": 28824, "s": 28811, "text": "akshaykmalik" }, { "code": null, "e": 28840, "s": 28824, "text": "arupjyoti_dutta" }, { "code": null, "e": 28851, "s": 28840, "text": "nidhi_biet" }, { "code": null, "e": 28864, "s": 28851, "text": "manu singhal" }, { "code": null, "e": 28882, "s": 28864, "text": "pujakumarinwd0039" }, { "code": null, "e": 28904, "s": 28882, "text": "singhbishalkumarsingh" }, { "code": null, "e": 28915, "s": 28904, "text": "cpp-string" }, { "code": null, "e": 28919, "s": 28915, "text": "C++" }, { "code": null, "e": 28927, "s": 28919, "text": "Strings" }, { "code": null, "e": 28935, "s": 28927, "text": "Strings" }, { "code": null, "e": 28939, "s": 28935, "text": "CPP" }, { "code": null, "e": 29037, "s": 28939, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29056, "s": 29037, "text": "Inheritance in C++" }, { "code": null, "e": 29099, "s": 29056, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 29123, "s": 29099, "text": "C++ Classes and Objects" }, { "code": null, "e": 29150, "s": 29123, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 29174, "s": 29150, "text": "Virtual Function in C++" }, { "code": null, "e": 29220, "s": 29174, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 29245, "s": 29220, "text": "Reverse a string in Java" }, { "code": null, "e": 29305, "s": 29245, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 29320, "s": 29305, "text": "C++ Data Types" } ]
Python | Pandas DatetimeIndex.normalize() - GeeksforGeeks
24 Dec, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas DatetimeIndex.normalize() function convert times to midnight. The time component of the date-timeise converted to midnight i.e. 00:00:00. This is useful in cases, when the time does not matter. Length is unaltered. The timezones are unaffected. Syntax: DatetimeIndex.normalize() Return: DatetimeIndex or Series Example #1: Use DatetimeIndex.normalize() function to normalize time. # importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'H' represents hourly frequency idx = pd.DatetimeIndex(start ='2018-08-10 08:00', freq ='H', periods = 5, tz ='Asia/Calcutta') # Print the DatetimeIndexprint(didx) Output :Now we want all the time values present in the DatetimeIndex object to be normalized i.e., it gets converted to midnight time. # normalize the time.idx.normalize() Output :As we can see in the output, the function has converted all the time values in the object to midnight time. Example #2: Use DatetimeIndex.normalize() function to normalize time. # importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'Q' represents quarter end frequency idx = pd.DatetimeIndex(start ='2000-01-15 08:00', freq ='Q', periods = 4, tz ='Asia/Calcutta') # Print the DatetimeIndexprint(didx) Output : Now we want all the time values present in the DatetimeIndex object to be normalized i.e., it gets converted to midnight time. # normalize the time.idx.normalize() Output :As we can see in the output, the function has converted all the time values in the object to midnight time. Python pandas-datetimeIndex Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Iterate over a list in Python Reading and Writing to text files in Python *args and **kwargs in Python Convert integer to string in Python Check if element exists in list in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26121, "s": 26093, "text": "\n24 Dec, 2018" }, { "code": null, "e": 26335, "s": 26121, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 26587, "s": 26335, "text": "Pandas DatetimeIndex.normalize() function convert times to midnight. The time component of the date-timeise converted to midnight i.e. 00:00:00. This is useful in cases, when the time does not matter. Length is unaltered. The timezones are unaffected." }, { "code": null, "e": 26621, "s": 26587, "text": "Syntax: DatetimeIndex.normalize()" }, { "code": null, "e": 26653, "s": 26621, "text": "Return: DatetimeIndex or Series" }, { "code": null, "e": 26723, "s": 26653, "text": "Example #1: Use DatetimeIndex.normalize() function to normalize time." }, { "code": "# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'H' represents hourly frequency idx = pd.DatetimeIndex(start ='2018-08-10 08:00', freq ='H', periods = 5, tz ='Asia/Calcutta') # Print the DatetimeIndexprint(didx)", "e": 26993, "s": 26723, "text": null }, { "code": null, "e": 27128, "s": 26993, "text": "Output :Now we want all the time values present in the DatetimeIndex object to be normalized i.e., it gets converted to midnight time." }, { "code": "# normalize the time.idx.normalize()", "e": 27165, "s": 27128, "text": null }, { "code": null, "e": 27351, "s": 27165, "text": "Output :As we can see in the output, the function has converted all the time values in the object to midnight time. Example #2: Use DatetimeIndex.normalize() function to normalize time." }, { "code": "# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'Q' represents quarter end frequency idx = pd.DatetimeIndex(start ='2000-01-15 08:00', freq ='Q', periods = 4, tz ='Asia/Calcutta') # Print the DatetimeIndexprint(didx)", "e": 27626, "s": 27351, "text": null }, { "code": null, "e": 27635, "s": 27626, "text": "Output :" }, { "code": null, "e": 27762, "s": 27635, "text": "Now we want all the time values present in the DatetimeIndex object to be normalized i.e., it gets converted to midnight time." }, { "code": "# normalize the time.idx.normalize()", "e": 27799, "s": 27762, "text": null }, { "code": null, "e": 27915, "s": 27799, "text": "Output :As we can see in the output, the function has converted all the time values in the object to midnight time." }, { "code": null, "e": 27943, "s": 27915, "text": "Python pandas-datetimeIndex" }, { "code": null, "e": 27957, "s": 27943, "text": "Python-pandas" }, { "code": null, "e": 27964, "s": 27957, "text": "Python" }, { "code": null, "e": 28062, "s": 27964, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28080, "s": 28062, "text": "Python Dictionary" }, { "code": null, "e": 28112, "s": 28080, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28147, "s": 28112, "text": "Read a file line by line in Python" }, { "code": null, "e": 28169, "s": 28147, "text": "Enumerate() in Python" }, { "code": null, "e": 28199, "s": 28169, "text": "Iterate over a list in Python" }, { "code": null, "e": 28243, "s": 28199, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28272, "s": 28243, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28308, "s": 28272, "text": "Convert integer to string in Python" }, { "code": null, "e": 28350, "s": 28308, "text": "Check if element exists in list in Python" } ]
Non-Repeating Element - GeeksforGeeks
25 Feb, 2022 Find the first non-repeating element in a given array of integers. Examples: Input : -1 2 -1 3 2 Output : 3 Explanation : The first number that does not repeat is : 3 Input : 9 4 9 6 7 4 Output : 6 A Simple Solution is to use two loops. The outer loop picks elements one by one and inner loop checks if the element is present more than once or not. C++ Java Python3 C# PHP JavaScript // Simple CPP program to find first non-// repeating element.#include <bits/stdc++.h>using namespace std; int firstNonRepeating(int arr[], int n){ for (int i = 0; i < n; i++) { int j; for (j = 0; j < n; j++) if (i != j && arr[i] == arr[j]) break; if (j == n) return arr[i]; } return -1;} // Driver codeint main(){ int arr[] = { 9, 4, 9, 6, 7, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << firstNonRepeating(arr, n); return 0;} // Java program to find first non-repeating// element.class GFG { static int firstNonRepeating(int arr[], int n) { for (int i = 0; i < n; i++) { int j; for (j = 0; j < n; j++) if (i != j && arr[i] == arr[j]) break; if (j == n) return arr[i]; } return -1; } // Driver code public static void main(String[] args) { int arr[] = { 9, 4, 9, 6, 7, 4 }; int n = arr.length; System.out.print(firstNonRepeating(arr, n)); }} // This code is contributed by Anant Agarwal. # Python3 program to find first# non-repeating element. def firstNonRepeating(arr, n): for i in range(n): j = 0 while(j < n): if (i != j and arr[i] == arr[j]): break j += 1 if (j == n): return arr[i] return -1 # Driver codearr = [ 9, 4, 9, 6, 7, 4 ]n = len(arr)print(firstNonRepeating(arr, n)) # This code is contributed by Anant Agarwal. // C# program to find first non-// repeating element.using System; class GFG { static int firstNonRepeating(int[] arr, int n) { for (int i = 0; i < n; i++) { int j; for (j = 0; j < n; j++) if (i != j && arr[i] == arr[j]) break; if (j == n) return arr[i]; } return -1; } // Driver code public static void Main() { int[] arr = { 9, 4, 9, 6, 7, 4 }; int n = arr.Length; Console.Write(firstNonRepeating(arr, n)); }}// This code is contributed by Anant Agarwal. <?php// Simple PHP program to find first non-// repeating element. function firstNonRepeating($arr, $n){ for ($i = 0; $i < $n; $i++) { $j; for ($j = 0; $j< $n; $j++) if ($i != $j && $arr[$i] == $arr[$j]) break; if ($j == $n) return $arr[$i]; } return -1;} // Driver code $arr = array(9, 4, 9, 6, 7, 4); $n = sizeof($arr) ; echo firstNonRepeating($arr, $n); // This code is contributed by ajit?> <script> // JavaScript code for the above approach function firstNonRepeating(arr, n) { for (let i = 0; i < n; i++) { let j; for (j = 0; j < n; j++) if (i != j && arr[i] == arr[j]) break; if (j == n) return arr[i]; } return -1; } // Driver code let arr = [9, 4, 9, 6, 7, 4]; let n = arr.length; document.write(firstNonRepeating(arr, n)); // This code is contributed by Potta Lokesh </script> 6 An Efficient Solution is to use hashing.1) Traverse array and insert elements and their counts in hash table.2) Traverse array again and print first element with count equals to 1. C++ Java Python3 C# Javascript // Efficient CPP program to find first non-// repeating element.#include <bits/stdc++.h>using namespace std; int firstNonRepeating(int arr[], int n){ // Insert all array elements in hash // table unordered_map<int, int> mp; for (int i = 0; i < n; i++) mp[arr[i]]++; // Traverse array again and return // first element with count 1. for (int i = 0; i < n; i++) if (mp[arr[i]] == 1) return arr[i]; return -1;} // Driver codeint main(){ int arr[] = { 9, 4, 9, 6, 7, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << firstNonRepeating(arr, n); return 0;} // Efficient Java program to find first non-// repeating element.import java.util.*; class GFG { static int firstNonRepeating(int arr[], int n) { // Insert all array elements in hash // table Map<Integer, Integer> m = new HashMap<>(); for (int i = 0; i < n; i++) { if (m.containsKey(arr[i])) { m.put(arr[i], m.get(arr[i]) + 1); } else { m.put(arr[i], 1); } } // Traverse array again and return // first element with count 1. for (int i = 0; i < n; i++) if (m.get(arr[i]) == 1) return arr[i]; return -1; } // Driver code public static void main(String[] args) { int arr[] = { 9, 4, 9, 6, 7, 4 }; int n = arr.length; System.out.println(firstNonRepeating(arr, n)); }} // This code contributed by Rajput-Ji # Efficient Python3 program to find first# non-repeating element.from collections import defaultdict def firstNonRepeating(arr, n): mp = defaultdict(lambda:0) # Insert all array elements in hash table for i in range(n): mp[arr[i]] += 1 # Traverse array again and return # first element with count 1. for i in range(n): if mp[arr[i]] == 1: return arr[i] return -1 # Driver Codearr = [9, 4, 9, 6, 7, 4]n = len(arr)print(firstNonRepeating(arr, n)) # This code is contributed by Shrikant13 // Efficient C# program to find first non-// repeating element.using System;using System.Collections.Generic; class GFG { static int firstNonRepeating(int[] arr, int n) { // Insert all array elements in hash // table Dictionary<int, int> m = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { if (m.ContainsKey(arr[i])) { var val = m[arr[i]]; m.Remove(arr[i]); m.Add(arr[i], val + 1); } else { m.Add(arr[i], 1); } } // Traverse array again and return // first element with count 1. for (int i = 0; i < n; i++) if (m[arr[i]] == 1) return arr[i]; return -1; } // Driver code public static void Main(String[] args) { int[] arr = { 9, 4, 9, 6, 7, 4 }; int n = arr.Length; Console.WriteLine(firstNonRepeating(arr, n)); }} // This code has been contributed by 29AjayKumar <script>// Efficient javascript program to find first non-// repeating element. function firstNonRepeating(arr , n){ // Insert all array elements in hash // table const m = new Map(); for (var i = 0; i < n; i++) { if (m.has(arr[i])) { m.set(arr[i], m.get(arr[i]) + 1); } else { m.set(arr[i], 1); } } // Traverse array again and return // first element with count 1. for (var i = 0; i < n; i++) if (m.get(arr[i]) == 1) return arr[i]; return -1;} // Driver codevar arr = [ 9, 4, 9, 6, 7, 4 ];var n = arr.length;document.write(firstNonRepeating(arr, n)); // This code contributed by shikhasingrajput</script> 6 Time Complexity: O(n)Auxiliary Space: O(n) Further Optimization: If array has many duplicates, we can also store index in hash table, using a hash table where value is a pair. Now we only need to traverse keys in hash table (not complete array) to find first non repeating. Printing all non-repeating elements: C++ Java Python3 C# Javascript // Efficient CPP program to print all non-// repeating elements.#include <bits/stdc++.h>using namespace std; void firstNonRepeating(int arr[], int n){ // Insert all array elements in hash // table unordered_map<int, int> mp; for (int i = 0; i < n; i++) mp[arr[i]]++; // Traverse through map only and for (auto x : mp) if (x.second == 1) cout << x.first << " ";} // Driver codeint main(){ int arr[] = { 9, 4, 9, 6, 7, 4 }; int n = sizeof(arr) / sizeof(arr[0]); firstNonRepeating(arr, n); return 0;} // Efficient Java program to print all non-// repeating elements.import java.util.*; class GFG { static void firstNonRepeating(int arr[], int n) { // Insert all array elements in hash // table Map<Integer, Integer> m = new HashMap<>(); for (int i = 0; i < n; i++) { if (m.containsKey(arr[i])) { m.put(arr[i], m.get(arr[i]) + 1); } else { m.put(arr[i], 1); } } // Traverse through map only and // using for-each loop for iteration over Map.entrySet() for (Map.Entry<Integer, Integer> x : m.entrySet()) if (x.getValue() == 1) System.out.print(x.getKey() + " "); } // Driver code public static void main(String[] args) { int arr[] = { 9, 4, 9, 6, 7, 4 }; int n = arr.length; firstNonRepeating(arr, n); }} // This code has been contributed by 29AjayKumar # Efficient Python program to print all non-# repeating elements. def firstNonRepeating(arr, n): # Insert all array elements in hash # table mp={} for i in range(n): if arr[i] not in mp: mp[arr[i]]=0 mp[arr[i]]+=1 # Traverse through map only and for x in mp: if (mp[x]== 1): print(x,end=" ") # Driver codearr = [ 9, 4, 9, 6, 7, 4 ]n = len(arr)firstNonRepeating(arr, n) # This code is contributed by shivanisinghss2110 // Efficient C# program to print all non-// repeating elements.using System;using System.Collections.Generic; class GFG { static void firstNonRepeating(int[] arr, int n) { // Insert all array elements in hash // table Dictionary<int, int> m = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { if (m.ContainsKey(arr[i])) { var val = m[arr[i]]; m.Remove(arr[i]); m.Add(arr[i], val + 1); } else { m.Add(arr[i], 1); } } // Traverse through map only and // using for-each loop for iteration over Map.entrySet() foreach(KeyValuePair<int, int> x in m) { if (x.Value == 1) { Console.Write(x.Key + " "); } } } // Driver code public static void Main(String[] args) { int[] arr = { 9, 4, 9, 6, 7, 4 }; int n = arr.Length; firstNonRepeating(arr, n); }} /* This code contributed by PrinciRaj1992 */ <script>// Efficient Javascript program to print all non-// repeating elements. function firstNonRepeating(arr, n){ // Insert all array elements in hash // table const mp = new Map(); for (var i = 0; i< n; i++) { if(mp.has(arr[i])) mp.set(arr[i], mp.get(arr[i]) + 1); else mp.set(arr[i],1); } // Traverse through map only and for (var x of mp.keys()) { if (mp.get(x) == 1) document.write(x+" "); } } // Driver code var arr = [ 9, 4, 9, 6, 7, 4 ]; var n = arr.length; firstNonRepeating(arr, n); // This code contributed by Palak Gupta</script> 7 6 jit_t shrikanth13 Rajput-Ji 29AjayKumar princiraj1992 shivanisinghss2110 lokeshpotta20 shikhasingrajput ninja_hattori cpp-unordered_map Arrays Hash Searching Arrays Searching Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Count pairs with given sum Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing)
[ { "code": null, "e": 26031, "s": 26003, "text": "\n25 Feb, 2022" }, { "code": null, "e": 26098, "s": 26031, "text": "Find the first non-repeating element in a given array of integers." }, { "code": null, "e": 26108, "s": 26098, "text": "Examples:" }, { "code": null, "e": 26232, "s": 26108, "text": "Input : -1 2 -1 3 2\nOutput : 3\nExplanation : The first number that does not \nrepeat is : 3\n\nInput : 9 4 9 6 7 4\nOutput : 6\n" }, { "code": null, "e": 26383, "s": 26232, "text": "A Simple Solution is to use two loops. The outer loop picks elements one by one and inner loop checks if the element is present more than once or not." }, { "code": null, "e": 26387, "s": 26383, "text": "C++" }, { "code": null, "e": 26392, "s": 26387, "text": "Java" }, { "code": null, "e": 26400, "s": 26392, "text": "Python3" }, { "code": null, "e": 26403, "s": 26400, "text": "C#" }, { "code": null, "e": 26407, "s": 26403, "text": "PHP" }, { "code": null, "e": 26418, "s": 26407, "text": "JavaScript" }, { "code": "// Simple CPP program to find first non-// repeating element.#include <bits/stdc++.h>using namespace std; int firstNonRepeating(int arr[], int n){ for (int i = 0; i < n; i++) { int j; for (j = 0; j < n; j++) if (i != j && arr[i] == arr[j]) break; if (j == n) return arr[i]; } return -1;} // Driver codeint main(){ int arr[] = { 9, 4, 9, 6, 7, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << firstNonRepeating(arr, n); return 0;}", "e": 26929, "s": 26418, "text": null }, { "code": "// Java program to find first non-repeating// element.class GFG { static int firstNonRepeating(int arr[], int n) { for (int i = 0; i < n; i++) { int j; for (j = 0; j < n; j++) if (i != j && arr[i] == arr[j]) break; if (j == n) return arr[i]; } return -1; } // Driver code public static void main(String[] args) { int arr[] = { 9, 4, 9, 6, 7, 4 }; int n = arr.length; System.out.print(firstNonRepeating(arr, n)); }} // This code is contributed by Anant Agarwal.", "e": 27540, "s": 26929, "text": null }, { "code": "# Python3 program to find first# non-repeating element. def firstNonRepeating(arr, n): for i in range(n): j = 0 while(j < n): if (i != j and arr[i] == arr[j]): break j += 1 if (j == n): return arr[i] return -1 # Driver codearr = [ 9, 4, 9, 6, 7, 4 ]n = len(arr)print(firstNonRepeating(arr, n)) # This code is contributed by Anant Agarwal.", "e": 27964, "s": 27540, "text": null }, { "code": "// C# program to find first non-// repeating element.using System; class GFG { static int firstNonRepeating(int[] arr, int n) { for (int i = 0; i < n; i++) { int j; for (j = 0; j < n; j++) if (i != j && arr[i] == arr[j]) break; if (j == n) return arr[i]; } return -1; } // Driver code public static void Main() { int[] arr = { 9, 4, 9, 6, 7, 4 }; int n = arr.Length; Console.Write(firstNonRepeating(arr, n)); }}// This code is contributed by Anant Agarwal.", "e": 28567, "s": 27964, "text": null }, { "code": "<?php// Simple PHP program to find first non-// repeating element. function firstNonRepeating($arr, $n){ for ($i = 0; $i < $n; $i++) { $j; for ($j = 0; $j< $n; $j++) if ($i != $j && $arr[$i] == $arr[$j]) break; if ($j == $n) return $arr[$i]; } return -1;} // Driver code $arr = array(9, 4, 9, 6, 7, 4); $n = sizeof($arr) ; echo firstNonRepeating($arr, $n); // This code is contributed by ajit?>", "e": 29049, "s": 28567, "text": null }, { "code": " <script> // JavaScript code for the above approach function firstNonRepeating(arr, n) { for (let i = 0; i < n; i++) { let j; for (j = 0; j < n; j++) if (i != j && arr[i] == arr[j]) break; if (j == n) return arr[i]; } return -1; } // Driver code let arr = [9, 4, 9, 6, 7, 4]; let n = arr.length; document.write(firstNonRepeating(arr, n)); // This code is contributed by Potta Lokesh </script>", "e": 29604, "s": 29049, "text": null }, { "code": null, "e": 29607, "s": 29604, "text": "6\n" }, { "code": null, "e": 29788, "s": 29607, "text": "An Efficient Solution is to use hashing.1) Traverse array and insert elements and their counts in hash table.2) Traverse array again and print first element with count equals to 1." }, { "code": null, "e": 29792, "s": 29788, "text": "C++" }, { "code": null, "e": 29797, "s": 29792, "text": "Java" }, { "code": null, "e": 29805, "s": 29797, "text": "Python3" }, { "code": null, "e": 29808, "s": 29805, "text": "C#" }, { "code": null, "e": 29819, "s": 29808, "text": "Javascript" }, { "code": "// Efficient CPP program to find first non-// repeating element.#include <bits/stdc++.h>using namespace std; int firstNonRepeating(int arr[], int n){ // Insert all array elements in hash // table unordered_map<int, int> mp; for (int i = 0; i < n; i++) mp[arr[i]]++; // Traverse array again and return // first element with count 1. for (int i = 0; i < n; i++) if (mp[arr[i]] == 1) return arr[i]; return -1;} // Driver codeint main(){ int arr[] = { 9, 4, 9, 6, 7, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << firstNonRepeating(arr, n); return 0;}", "e": 30433, "s": 29819, "text": null }, { "code": "// Efficient Java program to find first non-// repeating element.import java.util.*; class GFG { static int firstNonRepeating(int arr[], int n) { // Insert all array elements in hash // table Map<Integer, Integer> m = new HashMap<>(); for (int i = 0; i < n; i++) { if (m.containsKey(arr[i])) { m.put(arr[i], m.get(arr[i]) + 1); } else { m.put(arr[i], 1); } } // Traverse array again and return // first element with count 1. for (int i = 0; i < n; i++) if (m.get(arr[i]) == 1) return arr[i]; return -1; } // Driver code public static void main(String[] args) { int arr[] = { 9, 4, 9, 6, 7, 4 }; int n = arr.length; System.out.println(firstNonRepeating(arr, n)); }} // This code contributed by Rajput-Ji", "e": 31344, "s": 30433, "text": null }, { "code": "# Efficient Python3 program to find first# non-repeating element.from collections import defaultdict def firstNonRepeating(arr, n): mp = defaultdict(lambda:0) # Insert all array elements in hash table for i in range(n): mp[arr[i]] += 1 # Traverse array again and return # first element with count 1. for i in range(n): if mp[arr[i]] == 1: return arr[i] return -1 # Driver Codearr = [9, 4, 9, 6, 7, 4]n = len(arr)print(firstNonRepeating(arr, n)) # This code is contributed by Shrikant13", "e": 31878, "s": 31344, "text": null }, { "code": "// Efficient C# program to find first non-// repeating element.using System;using System.Collections.Generic; class GFG { static int firstNonRepeating(int[] arr, int n) { // Insert all array elements in hash // table Dictionary<int, int> m = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { if (m.ContainsKey(arr[i])) { var val = m[arr[i]]; m.Remove(arr[i]); m.Add(arr[i], val + 1); } else { m.Add(arr[i], 1); } } // Traverse array again and return // first element with count 1. for (int i = 0; i < n; i++) if (m[arr[i]] == 1) return arr[i]; return -1; } // Driver code public static void Main(String[] args) { int[] arr = { 9, 4, 9, 6, 7, 4 }; int n = arr.Length; Console.WriteLine(firstNonRepeating(arr, n)); }} // This code has been contributed by 29AjayKumar", "e": 32890, "s": 31878, "text": null }, { "code": "<script>// Efficient javascript program to find first non-// repeating element. function firstNonRepeating(arr , n){ // Insert all array elements in hash // table const m = new Map(); for (var i = 0; i < n; i++) { if (m.has(arr[i])) { m.set(arr[i], m.get(arr[i]) + 1); } else { m.set(arr[i], 1); } } // Traverse array again and return // first element with count 1. for (var i = 0; i < n; i++) if (m.get(arr[i]) == 1) return arr[i]; return -1;} // Driver codevar arr = [ 9, 4, 9, 6, 7, 4 ];var n = arr.length;document.write(firstNonRepeating(arr, n)); // This code contributed by shikhasingrajput</script>", "e": 33592, "s": 32890, "text": null }, { "code": null, "e": 33595, "s": 33592, "text": "6\n" }, { "code": null, "e": 33638, "s": 33595, "text": "Time Complexity: O(n)Auxiliary Space: O(n)" }, { "code": null, "e": 33869, "s": 33638, "text": "Further Optimization: If array has many duplicates, we can also store index in hash table, using a hash table where value is a pair. Now we only need to traverse keys in hash table (not complete array) to find first non repeating." }, { "code": null, "e": 33906, "s": 33869, "text": "Printing all non-repeating elements:" }, { "code": null, "e": 33910, "s": 33906, "text": "C++" }, { "code": null, "e": 33915, "s": 33910, "text": "Java" }, { "code": null, "e": 33923, "s": 33915, "text": "Python3" }, { "code": null, "e": 33926, "s": 33923, "text": "C#" }, { "code": null, "e": 33937, "s": 33926, "text": "Javascript" }, { "code": "// Efficient CPP program to print all non-// repeating elements.#include <bits/stdc++.h>using namespace std; void firstNonRepeating(int arr[], int n){ // Insert all array elements in hash // table unordered_map<int, int> mp; for (int i = 0; i < n; i++) mp[arr[i]]++; // Traverse through map only and for (auto x : mp) if (x.second == 1) cout << x.first << \" \";} // Driver codeint main(){ int arr[] = { 9, 4, 9, 6, 7, 4 }; int n = sizeof(arr) / sizeof(arr[0]); firstNonRepeating(arr, n); return 0;}", "e": 34491, "s": 33937, "text": null }, { "code": "// Efficient Java program to print all non-// repeating elements.import java.util.*; class GFG { static void firstNonRepeating(int arr[], int n) { // Insert all array elements in hash // table Map<Integer, Integer> m = new HashMap<>(); for (int i = 0; i < n; i++) { if (m.containsKey(arr[i])) { m.put(arr[i], m.get(arr[i]) + 1); } else { m.put(arr[i], 1); } } // Traverse through map only and // using for-each loop for iteration over Map.entrySet() for (Map.Entry<Integer, Integer> x : m.entrySet()) if (x.getValue() == 1) System.out.print(x.getKey() + \" \"); } // Driver code public static void main(String[] args) { int arr[] = { 9, 4, 9, 6, 7, 4 }; int n = arr.length; firstNonRepeating(arr, n); }} // This code has been contributed by 29AjayKumar", "e": 35443, "s": 34491, "text": null }, { "code": "# Efficient Python program to print all non-# repeating elements. def firstNonRepeating(arr, n): # Insert all array elements in hash # table mp={} for i in range(n): if arr[i] not in mp: mp[arr[i]]=0 mp[arr[i]]+=1 # Traverse through map only and for x in mp: if (mp[x]== 1): print(x,end=\" \") # Driver codearr = [ 9, 4, 9, 6, 7, 4 ]n = len(arr)firstNonRepeating(arr, n) # This code is contributed by shivanisinghss2110", "e": 35949, "s": 35443, "text": null }, { "code": "// Efficient C# program to print all non-// repeating elements.using System;using System.Collections.Generic; class GFG { static void firstNonRepeating(int[] arr, int n) { // Insert all array elements in hash // table Dictionary<int, int> m = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { if (m.ContainsKey(arr[i])) { var val = m[arr[i]]; m.Remove(arr[i]); m.Add(arr[i], val + 1); } else { m.Add(arr[i], 1); } } // Traverse through map only and // using for-each loop for iteration over Map.entrySet() foreach(KeyValuePair<int, int> x in m) { if (x.Value == 1) { Console.Write(x.Key + \" \"); } } } // Driver code public static void Main(String[] args) { int[] arr = { 9, 4, 9, 6, 7, 4 }; int n = arr.Length; firstNonRepeating(arr, n); }} /* This code contributed by PrinciRaj1992 */", "e": 36999, "s": 35949, "text": null }, { "code": "<script>// Efficient Javascript program to print all non-// repeating elements. function firstNonRepeating(arr, n){ // Insert all array elements in hash // table const mp = new Map(); for (var i = 0; i< n; i++) { if(mp.has(arr[i])) mp.set(arr[i], mp.get(arr[i]) + 1); else mp.set(arr[i],1); } // Traverse through map only and for (var x of mp.keys()) { if (mp.get(x) == 1) document.write(x+\" \"); } } // Driver code var arr = [ 9, 4, 9, 6, 7, 4 ]; var n = arr.length; firstNonRepeating(arr, n); // This code contributed by Palak Gupta</script>", "e": 37657, "s": 36999, "text": null }, { "code": null, "e": 37662, "s": 37657, "text": "7 6\n" }, { "code": null, "e": 37668, "s": 37662, "text": "jit_t" }, { "code": null, "e": 37680, "s": 37668, "text": "shrikanth13" }, { "code": null, "e": 37690, "s": 37680, "text": "Rajput-Ji" }, { "code": null, "e": 37702, "s": 37690, "text": "29AjayKumar" }, { "code": null, "e": 37716, "s": 37702, "text": "princiraj1992" }, { "code": null, "e": 37735, "s": 37716, "text": "shivanisinghss2110" }, { "code": null, "e": 37749, "s": 37735, "text": "lokeshpotta20" }, { "code": null, "e": 37766, "s": 37749, "text": "shikhasingrajput" }, { "code": null, "e": 37780, "s": 37766, "text": "ninja_hattori" }, { "code": null, "e": 37798, "s": 37780, "text": "cpp-unordered_map" }, { "code": null, "e": 37805, "s": 37798, "text": "Arrays" }, { "code": null, "e": 37810, "s": 37805, "text": "Hash" }, { "code": null, "e": 37820, "s": 37810, "text": "Searching" }, { "code": null, "e": 37827, "s": 37820, "text": "Arrays" }, { "code": null, "e": 37837, "s": 37827, "text": "Searching" }, { "code": null, "e": 37842, "s": 37837, "text": "Hash" }, { "code": null, "e": 37940, "s": 37842, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38008, "s": 37940, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 38052, "s": 38008, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 38100, "s": 38052, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 38123, "s": 38100, "text": "Introduction to Arrays" }, { "code": null, "e": 38155, "s": 38123, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 38240, "s": 38155, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 38276, "s": 38240, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 38303, "s": 38276, "text": "Count pairs with given sum" }, { "code": null, "e": 38334, "s": 38303, "text": "Hashing | Set 1 (Introduction)" } ]
How to remove an array element in a foreach loop? - GeeksforGeeks
21 Feb, 2019 Use unset() function to remove array elements in a foreach loop. The unset() function is an inbuilt function in PHP which is used to unset a specified variable. The behavior of this function depends on different things. If the function is called from inside of any user defined function then it unsets the value associated with the variables inside it, leaving the value which is initialized outside it. Syntax: unset( $variable ) Return Value: This function does not returns any value. Below examples use unset() function to remove an array element in foreach loop. Example 1: <?php // Declare an array and initialize it$Array = array( "GeeksForGeeks_1", "GeeksForGeeks_2", "GeeksForGeeks_3"); // Display the array elementsprint_r($Array); // Use foreach loop to remove array elementforeach($Array as $k => $val) { if($val == "GeeksForGeeks_3") { unset($Array[$k]); }} // Display the array elementsprint_r($Array); ?> Array ( [0] => GeeksForGeeks_1 [1] => GeeksForGeeks_2 [2] => GeeksForGeeks_3 ) Array ( [0] => GeeksForGeeks_1 [1] => GeeksForGeeks_2 ) Example 2: <?php // Declare an array and initialize it$Array = array( array(0 => 1), array(4 => 10), array(6 => 100)); // Display the array elementsprint_r($Array); // Use foreach loop to remove // array elementforeach($Array as $k => $val) { if(key($val) > 5) { unset($Array[$k]); }} // Display the array elementsprint_r($Array); ?> Array ( [0] => Array ( [0] => 1 ) [1] => Array ( [4] => 10 ) [2] => Array ( [6] => 100 ) ) Array ( [0] => Array ( [0] => 1 ) [1] => Array ( [4] => 10 ) ) Picked PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime How to pass JavaScript variables to PHP ? Split a comma delimited string into an array in PHP Download file from URL using PHP How to convert array to string in PHP ? How to call PHP function on the click of a Button ? How to pass JavaScript variables to PHP ? Split a comma delimited string into an array in PHP How to get parameters from a URL string in PHP?
[ { "code": null, "e": 25771, "s": 25743, "text": "\n21 Feb, 2019" }, { "code": null, "e": 26175, "s": 25771, "text": "Use unset() function to remove array elements in a foreach loop. The unset() function is an inbuilt function in PHP which is used to unset a specified variable. The behavior of this function depends on different things. If the function is called from inside of any user defined function then it unsets the value associated with the variables inside it, leaving the value which is initialized outside it." }, { "code": null, "e": 26183, "s": 26175, "text": "Syntax:" }, { "code": null, "e": 26202, "s": 26183, "text": "unset( $variable )" }, { "code": null, "e": 26258, "s": 26202, "text": "Return Value: This function does not returns any value." }, { "code": null, "e": 26338, "s": 26258, "text": "Below examples use unset() function to remove an array element in foreach loop." }, { "code": null, "e": 26349, "s": 26338, "text": "Example 1:" }, { "code": "<?php // Declare an array and initialize it$Array = array( \"GeeksForGeeks_1\", \"GeeksForGeeks_2\", \"GeeksForGeeks_3\"); // Display the array elementsprint_r($Array); // Use foreach loop to remove array elementforeach($Array as $k => $val) { if($val == \"GeeksForGeeks_3\") { unset($Array[$k]); }} // Display the array elementsprint_r($Array); ?>", "e": 26719, "s": 26349, "text": null }, { "code": null, "e": 26875, "s": 26719, "text": "Array\n(\n [0] => GeeksForGeeks_1\n [1] => GeeksForGeeks_2\n [2] => GeeksForGeeks_3\n)\nArray\n(\n [0] => GeeksForGeeks_1\n [1] => GeeksForGeeks_2\n)\n" }, { "code": null, "e": 26886, "s": 26875, "text": "Example 2:" }, { "code": "<?php // Declare an array and initialize it$Array = array( array(0 => 1), array(4 => 10), array(6 => 100)); // Display the array elementsprint_r($Array); // Use foreach loop to remove // array elementforeach($Array as $k => $val) { if(key($val) > 5) { unset($Array[$k]); }} // Display the array elementsprint_r($Array); ?>", "e": 27236, "s": 26886, "text": null }, { "code": null, "e": 27556, "s": 27236, "text": "Array\n(\n [0] => Array\n (\n [0] => 1\n )\n\n [1] => Array\n (\n [4] => 10\n )\n\n [2] => Array\n (\n [6] => 100\n )\n\n)\nArray\n(\n [0] => Array\n (\n [0] => 1\n )\n\n [1] => Array\n (\n [4] => 10\n )\n\n)\n" }, { "code": null, "e": 27563, "s": 27556, "text": "Picked" }, { "code": null, "e": 27567, "s": 27563, "text": "PHP" }, { "code": null, "e": 27580, "s": 27567, "text": "PHP Programs" }, { "code": null, "e": 27597, "s": 27580, "text": "Web Technologies" }, { "code": null, "e": 27601, "s": 27597, "text": "PHP" }, { "code": null, "e": 27699, "s": 27601, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27739, "s": 27699, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27784, "s": 27739, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 27826, "s": 27784, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 27878, "s": 27826, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 27911, "s": 27878, "text": "Download file from URL using PHP" }, { "code": null, "e": 27951, "s": 27911, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 28003, "s": 27951, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 28045, "s": 28003, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 28097, "s": 28045, "text": "Split a comma delimited string into an array in PHP" } ]
Find n-th term in the series 9, 33, 73,129 ... - GeeksforGeeks
16 Apr, 2021 Given a series 9, 33, 73, 129... Find the n-th term of the series.Examples: Input : n = 4 Output : 129 Input : n = 5 Output : 201 The given series has a pattern which is visible after subtracting it from itself after one shift S = 9 + 33 + 73 + 129 + ... tn-1 + tn S = 9 + 33 + 73 + ... tn-2 + tn-1 + tn ——————————————— 0 = 9 + (24 + 40 + 56 + ....) - tn Since 24 + 40 + 56.. series in A.P with common difference of 16, we get tn = 9 + [((n-1)/2)*(2*24 + (n-1-1)d)] On solving this we get tn = 8n2 + 1 Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // Program to find n-th element in the// series 9, 33, 73, 128..#include <bits/stdc++.h>using namespace std; // Returns n-th element of the seriesint series(int n){ return (8 * n * n) + 1;} // driver program to test the above functionint main(){ int n = 5; cout << series(n); return 0;} // Program to find n-th element in the// series 9, 33, 73, 128..import java.io.*; class GFG{ // Returns n-th element of the series static int series(int n) { return (8 * n * n) + 1; } // driver program to test the above // function public static void main(String args[]) { int n = 5; System.out.println(series(n)); }} /*This code is contributed by Nikita Tiwari.*/ # Python Program to find n-th element# in the series 9, 33, 73, 128... # Returns n-th element of the seriesdef series(n): print (( 8 * n ** 2) + 1) # Driver Codeseries(5) # This code is contributed by Abhishek Agrawal. // C# program to find n-th element in the// series 9, 33, 73, 128..using System; class GFG { // Returns n-th element of the series static int series(int n) { return (8 * n * n) + 1; } // driver function public static void Main() { int n = 5; Console.WriteLine(series(n)); }} /*This code is contributed by vt_m.*/ <?php// PHP Program to find n-th element// in the series 9, 33, 73, 128.. // Returns n-th element// of the seriesfunction series($n){ return (8 * $n * $n) + 1;} // Driver Code$n = 5;echo(series($n)); // This code is contributed by Ajit.?> <script> // Program to find n-th element in the// series 9, 33, 73, 128.. // Returns n-th element of the seriesfunction series(n){ return (8 * n * n) + 1;} // driver program to test the above functionlet n = 5;document.write(series(n)); </script> Output: 201 Time complexity: O(1)This article is contributed by Striver. 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. jit_t subhammahato348 series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Count all possible paths from top left to bottom right of a mXn matrix Modular multiplicative inverse Program to multiply two matrices Fizz Buzz Implementation Check if a number is Palindrome Count ways to reach the n'th stair Merge two sorted arrays with O(1) extra space Min Cost Path | DP-6
[ { "code": null, "e": 25962, "s": 25934, "text": "\n16 Apr, 2021" }, { "code": null, "e": 26040, "s": 25962, "text": "Given a series 9, 33, 73, 129... Find the n-th term of the series.Examples: " }, { "code": null, "e": 26096, "s": 26040, "text": "Input : n = 4\nOutput : 129 \n\nInput : n = 5\nOutput : 201" }, { "code": null, "e": 26196, "s": 26098, "text": "The given series has a pattern which is visible after subtracting it from itself after one shift " }, { "code": null, "e": 26485, "s": 26196, "text": "S = 9 + 33 + 73 + 129 + ... tn-1 + tn\nS = 9 + 33 + 73 + ... tn-2 + tn-1 + tn\n———————————————\n0 = 9 + (24 + 40 + 56 + ....) - tn \n\nSince 24 + 40 + 56.. series in A.P with\ncommon difference of 16, we get\n\n tn = 9 + [((n-1)/2)*(2*24 + (n-1-1)d)] \n\nOn solving this we get \n\n\n tn = 8n2 + 1" }, { "code": null, "e": 26538, "s": 26485, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26542, "s": 26538, "text": "C++" }, { "code": null, "e": 26547, "s": 26542, "text": "Java" }, { "code": null, "e": 26555, "s": 26547, "text": "Python3" }, { "code": null, "e": 26558, "s": 26555, "text": "C#" }, { "code": null, "e": 26562, "s": 26558, "text": "PHP" }, { "code": null, "e": 26573, "s": 26562, "text": "Javascript" }, { "code": "// Program to find n-th element in the// series 9, 33, 73, 128..#include <bits/stdc++.h>using namespace std; // Returns n-th element of the seriesint series(int n){ return (8 * n * n) + 1;} // driver program to test the above functionint main(){ int n = 5; cout << series(n); return 0;}", "e": 26873, "s": 26573, "text": null }, { "code": "// Program to find n-th element in the// series 9, 33, 73, 128..import java.io.*; class GFG{ // Returns n-th element of the series static int series(int n) { return (8 * n * n) + 1; } // driver program to test the above // function public static void main(String args[]) { int n = 5; System.out.println(series(n)); }} /*This code is contributed by Nikita Tiwari.*/", "e": 27297, "s": 26873, "text": null }, { "code": "# Python Program to find n-th element# in the series 9, 33, 73, 128... # Returns n-th element of the seriesdef series(n): print (( 8 * n ** 2) + 1) # Driver Codeseries(5) # This code is contributed by Abhishek Agrawal.", "e": 27523, "s": 27297, "text": null }, { "code": "// C# program to find n-th element in the// series 9, 33, 73, 128..using System; class GFG { // Returns n-th element of the series static int series(int n) { return (8 * n * n) + 1; } // driver function public static void Main() { int n = 5; Console.WriteLine(series(n)); }} /*This code is contributed by vt_m.*/", "e": 27883, "s": 27523, "text": null }, { "code": "<?php// PHP Program to find n-th element// in the series 9, 33, 73, 128.. // Returns n-th element// of the seriesfunction series($n){ return (8 * $n * $n) + 1;} // Driver Code$n = 5;echo(series($n)); // This code is contributed by Ajit.?>", "e": 28125, "s": 27883, "text": null }, { "code": "<script> // Program to find n-th element in the// series 9, 33, 73, 128.. // Returns n-th element of the seriesfunction series(n){ return (8 * n * n) + 1;} // driver program to test the above functionlet n = 5;document.write(series(n)); </script>", "e": 28376, "s": 28125, "text": null }, { "code": null, "e": 28385, "s": 28376, "text": "Output: " }, { "code": null, "e": 28389, "s": 28385, "text": "201" }, { "code": null, "e": 28826, "s": 28389, "text": "Time complexity: O(1)This article is contributed by Striver. 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": 28832, "s": 28826, "text": "jit_t" }, { "code": null, "e": 28848, "s": 28832, "text": "subhammahato348" }, { "code": null, "e": 28855, "s": 28848, "text": "series" }, { "code": null, "e": 28868, "s": 28855, "text": "Mathematical" }, { "code": null, "e": 28881, "s": 28868, "text": "Mathematical" }, { "code": null, "e": 28888, "s": 28881, "text": "series" }, { "code": null, "e": 28986, "s": 28888, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29030, "s": 28986, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 29072, "s": 29030, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 29143, "s": 29072, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 29174, "s": 29143, "text": "Modular multiplicative inverse" }, { "code": null, "e": 29207, "s": 29174, "text": "Program to multiply two matrices" }, { "code": null, "e": 29232, "s": 29207, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 29264, "s": 29232, "text": "Check if a number is Palindrome" }, { "code": null, "e": 29299, "s": 29264, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 29345, "s": 29299, "text": "Merge two sorted arrays with O(1) extra space" } ]
Javascript Program for Search an element in a sorted and rotated array - GeeksforGeeks
11 Dec, 2021 An element in a sorted array can be found in O(log n) time via binary search. But suppose we rotate an ascending order sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Devise a way to find an element in the rotated array in O(log n) time. Example: Input : arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3}; key = 3 Output : Found at index 8 Input : arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3}; key = 30 Output : Not found Input : arr[] = {30, 40, 50, 10, 20} key = 10 Output : Found at index 3 All solutions provided here assume that all elements in the array are distinct.Basic Solution: Approach: The idea is to find the pivot point, divide the array in two sub-arrays and perform binary search.The main idea for finding pivot is – for a sorted (in increasing order) and pivoted array, pivot element is the only element for which next element to it is smaller than it.Using the above statement and binary search pivot can be found.After the pivot is found out divide the array in two sub-arrays.Now the individual sub – arrays are sorted so the element can be searched using Binary Search. The idea is to find the pivot point, divide the array in two sub-arrays and perform binary search. The main idea for finding pivot is – for a sorted (in increasing order) and pivoted array, pivot element is the only element for which next element to it is smaller than it. Using the above statement and binary search pivot can be found. After the pivot is found out divide the array in two sub-arrays. Now the individual sub – arrays are sorted so the element can be searched using Binary Search. Implementation: Input arr[] = {3, 4, 5, 1, 2} Element to Search = 1 1) Find out pivot point and divide the array in two sub-arrays. (pivot = 2) /*Index of 5*/ 2) Now call binary search for one of the two sub-arrays. (a) If element is greater than 0th element then search in left array (b) Else Search in right array (1 will go in else as 1 < 0th element(3)) 3) If element is found in selected sub-array then return index Else return -1. Below is the implementation of the above approach: Javascript <script>/* JavaScript Program to search an element in a sorted and pivoted array*/ /* Standard Binary Search function*/function binarySearch( arr, low, high, key){ if (high < low) return -1; let mid = Math.floor((low + high) / 2); /*low + (high - low)/2;*/ if (key == arr[mid]) return mid; if (key > arr[mid]) return binarySearch(arr, (mid + 1), high, key); // else return binarySearch(arr, low, (mid - 1), key);} /* Function to get pivot. For array 3, 4, 5, 6, 1, 2 it returns 3 (index of 6) */function findPivot( arr, low, high){ // base cases if (high < low) return -1; if (high == low) return low; let mid = Math.floor((low + high) / 2); /*low + (high - low)/2;*/ if (mid < high && arr[mid] > arr[mid + 1]) return mid; if (mid > low && arr[mid] < arr[mid - 1]) return (mid - 1); if (arr[low] >= arr[mid]) return findPivot(arr, low, mid - 1); return findPivot(arr, mid + 1, high);} /* Searches an element key in a pivoted sorted array arr[] of size n */function pivotedBinarySearch( arr, n, key){ let pivot = findPivot(arr, 0, n - 1); // If we didn't find a pivot, // then array is not rotated at all if (pivot == -1) return binarySearch(arr, 0, n - 1, key); // If we found a pivot, then first compare with pivot // and then search in two subarrays around pivot if (arr[pivot] == key) return pivot; if (arr[0] <= key) return binarySearch(arr, 0, pivot - 1, key); return binarySearch(arr, pivot + 1, n - 1, key);} /* Driver program to check above functions */// Let us search 3 in below arraylet arr1 = [ 5, 6, 7, 8, 9, 10, 1, 2, 3 ];let n = arr1.length;let key = 3;// Function callingdocument.write( "Index of the element is : " + pivotedBinarySearch(arr1, n, key)); </script> Output: Index of the element is : 8 Complexity Analysis: Time Complexity: O(log n). Binary Search requires log n comparisons to find the element. So time complexity is O(log n). Space Complexity:O(1), No extra space is required. Thanks to Ajay Mishra for initial solution.Improved Solution: Approach: Instead of two or more pass of binary search the result can be found in one pass of binary search. The binary search needs to be modified to perform the search. The idea is to create a recursive function that takes l and r as range in input and the key. 1) Find middle point mid = (l + h)/2 2) If key is present at middle point, return mid. 3) Else If arr[l..mid] is sorted a) If key to be searched lies in range from arr[l] to arr[mid], recur for arr[l..mid]. b) Else recur for arr[mid+1..h] 4) Else (arr[mid+1..h] must be sorted) a) If key to be searched lies in range from arr[mid+1] to arr[h], recur for arr[mid+1..h]. b) Else recur for arr[l..mid] Below is the implementation of above idea: Javascript <script> // Search an element in sorted and rotated// array using single pass of Binary Search // Returns index of key in arr[l..h] if// key is present, otherwise returns -1function search(arr, l, h, key){ if (l > h) return -1; let mid = Math.floor((l + h) / 2); if (arr[mid] == key) return mid; /* If arr[l...mid] is sorted */ if (arr[l] <= arr[mid]) { /* As this subarray is sorted, we can quickly check if key lies in half or other half */ if (key >= arr[l] && key <= arr[mid]) return search(arr, l, mid - 1, key); /*If key not lies in first half subarray, Divide other half into two subarrays, such that we can quickly check if key lies in other half */ return search(arr, mid + 1, h, key); } /* If arr[l..mid] first subarray is not sorted, then arr[mid... h] must be sorted subarray */ if (key >= arr[mid] && key <= arr[h]) return search(arr, mid + 1, h, key); return search(arr, l, mid - 1, key);} // Driver programlet arr = [ 4, 5, 6, 7, 8, 9, 1, 2, 3 ];let n = arr.length;let key = 6;let i = search(arr, 0, n - 1, key);if (i != -1) document.write("Index: " +i +"");else document.write("Key not found"); </script> Output: Index: 2 Complexity Analysis: Time Complexity: O(log n). Binary Search requires log n comparisons to find the element. So time complexity is O(log n). Space Complexity: O(1). As no extra space is required. Thanks to Gaurav Ahirwar for suggesting above solution. How to handle duplicates? It doesn’t look possible to search in O(Logn) time in all cases when duplicates are allowed. For example consider searching 0 in {2, 2, 2, 2, 2, 2, 2, 2, 0, 2} and {2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}. It doesn’t look possible to decide whether to recur for the left half or right half by doing a constant number of comparisons at the middle. YouTubeGeeksforGeeks507K subscribersSearch an element in a sorted and rotated array | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 15:16•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=uN5QUBHUQaM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Similar Articles: Find the minimum element in a sorted and rotated array Given a sorted and rotated array, find if there is a pair with a given sum. Please write comments if you find any bug in the above codes/algorithms, or find other ways to solve the same problem. Please refer complete article on Search an element in a sorted and rotated array for more details! Adobe Amazon BankBazaar Binary Search D-E-Shaw FactSet Flipkart Hike MakeMyTrip Microsoft Paytm rotation Samsung SAP Labs Snapdeal Times Internet Arrays JavaScript Searching Paytm Flipkart Amazon Microsoft Samsung Snapdeal D-E-Shaw FactSet Hike MakeMyTrip Adobe BankBazaar Times Internet SAP Labs Arrays Searching Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Count pairs with given sum Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Remove elements from a JavaScript Array 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 calculate the number of days between two dates in javascript?
[ { "code": null, "e": 26041, "s": 26013, "text": "\n11 Dec, 2021" }, { "code": null, "e": 26337, "s": 26041, "text": "An element in a sorted array can be found in O(log n) time via binary search. But suppose we rotate an ascending order sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Devise a way to find an element in the rotated array in O(log n) time. " }, { "code": null, "e": 26348, "s": 26337, "text": "Example: " }, { "code": null, "e": 26607, "s": 26348, "text": "Input : arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3};\n key = 3\nOutput : Found at index 8\n\nInput : arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3};\n key = 30\nOutput : Not found\n\nInput : arr[] = {30, 40, 50, 10, 20}\n key = 10 \nOutput : Found at index 3" }, { "code": null, "e": 26718, "s": 26611, "text": "All solutions provided here assume that all elements in the array are distinct.Basic Solution: Approach: " }, { "code": null, "e": 27211, "s": 26718, "text": "The idea is to find the pivot point, divide the array in two sub-arrays and perform binary search.The main idea for finding pivot is – for a sorted (in increasing order) and pivoted array, pivot element is the only element for which next element to it is smaller than it.Using the above statement and binary search pivot can be found.After the pivot is found out divide the array in two sub-arrays.Now the individual sub – arrays are sorted so the element can be searched using Binary Search." }, { "code": null, "e": 27310, "s": 27211, "text": "The idea is to find the pivot point, divide the array in two sub-arrays and perform binary search." }, { "code": null, "e": 27484, "s": 27310, "text": "The main idea for finding pivot is – for a sorted (in increasing order) and pivoted array, pivot element is the only element for which next element to it is smaller than it." }, { "code": null, "e": 27548, "s": 27484, "text": "Using the above statement and binary search pivot can be found." }, { "code": null, "e": 27613, "s": 27548, "text": "After the pivot is found out divide the array in two sub-arrays." }, { "code": null, "e": 27708, "s": 27613, "text": "Now the individual sub – arrays are sorted so the element can be searched using Binary Search." }, { "code": null, "e": 27726, "s": 27708, "text": "Implementation: " }, { "code": null, "e": 28199, "s": 27726, "text": "Input arr[] = {3, 4, 5, 1, 2}\nElement to Search = 1\n 1) Find out pivot point and divide the array in two\n sub-arrays. (pivot = 2) /*Index of 5*/\n 2) Now call binary search for one of the two sub-arrays.\n (a) If element is greater than 0th element then\n search in left array\n (b) Else Search in right array\n (1 will go in else as 1 < 0th element(3))\n 3) If element is found in selected sub-array then return index\n Else return -1." }, { "code": null, "e": 28252, "s": 28199, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 28263, "s": 28252, "text": "Javascript" }, { "code": "<script>/* JavaScript Program to search an element in a sorted and pivoted array*/ /* Standard Binary Search function*/function binarySearch( arr, low, high, key){ if (high < low) return -1; let mid = Math.floor((low + high) / 2); /*low + (high - low)/2;*/ if (key == arr[mid]) return mid; if (key > arr[mid]) return binarySearch(arr, (mid + 1), high, key); // else return binarySearch(arr, low, (mid - 1), key);} /* Function to get pivot. For array 3, 4, 5, 6, 1, 2 it returns 3 (index of 6) */function findPivot( arr, low, high){ // base cases if (high < low) return -1; if (high == low) return low; let mid = Math.floor((low + high) / 2); /*low + (high - low)/2;*/ if (mid < high && arr[mid] > arr[mid + 1]) return mid; if (mid > low && arr[mid] < arr[mid - 1]) return (mid - 1); if (arr[low] >= arr[mid]) return findPivot(arr, low, mid - 1); return findPivot(arr, mid + 1, high);} /* Searches an element key in a pivoted sorted array arr[] of size n */function pivotedBinarySearch( arr, n, key){ let pivot = findPivot(arr, 0, n - 1); // If we didn't find a pivot, // then array is not rotated at all if (pivot == -1) return binarySearch(arr, 0, n - 1, key); // If we found a pivot, then first compare with pivot // and then search in two subarrays around pivot if (arr[pivot] == key) return pivot; if (arr[0] <= key) return binarySearch(arr, 0, pivot - 1, key); return binarySearch(arr, pivot + 1, n - 1, key);} /* Driver program to check above functions */// Let us search 3 in below arraylet arr1 = [ 5, 6, 7, 8, 9, 10, 1, 2, 3 ];let n = arr1.length;let key = 3;// Function callingdocument.write( \"Index of the element is : \" + pivotedBinarySearch(arr1, n, key)); </script>", "e": 30147, "s": 28263, "text": null }, { "code": null, "e": 30157, "s": 30147, "text": "Output: " }, { "code": null, "e": 30185, "s": 30157, "text": "Index of the element is : 8" }, { "code": null, "e": 30208, "s": 30185, "text": "Complexity Analysis: " }, { "code": null, "e": 30329, "s": 30208, "text": "Time Complexity: O(log n). Binary Search requires log n comparisons to find the element. So time complexity is O(log n)." }, { "code": null, "e": 30380, "s": 30329, "text": "Space Complexity:O(1), No extra space is required." }, { "code": null, "e": 30707, "s": 30380, "text": "Thanks to Ajay Mishra for initial solution.Improved Solution: Approach: Instead of two or more pass of binary search the result can be found in one pass of binary search. The binary search needs to be modified to perform the search. The idea is to create a recursive function that takes l and r as range in input and the key. " }, { "code": null, "e": 31137, "s": 30707, "text": "1) Find middle point mid = (l + h)/2\n2) If key is present at middle point, return mid.\n3) Else If arr[l..mid] is sorted\n a) If key to be searched lies in range from arr[l]\n to arr[mid], recur for arr[l..mid].\n b) Else recur for arr[mid+1..h]\n4) Else (arr[mid+1..h] must be sorted)\n a) If key to be searched lies in range from arr[mid+1]\n to arr[h], recur for arr[mid+1..h].\n b) Else recur for arr[l..mid] " }, { "code": null, "e": 31182, "s": 31137, "text": "Below is the implementation of above idea: " }, { "code": null, "e": 31193, "s": 31182, "text": "Javascript" }, { "code": "<script> // Search an element in sorted and rotated// array using single pass of Binary Search // Returns index of key in arr[l..h] if// key is present, otherwise returns -1function search(arr, l, h, key){ if (l > h) return -1; let mid = Math.floor((l + h) / 2); if (arr[mid] == key) return mid; /* If arr[l...mid] is sorted */ if (arr[l] <= arr[mid]) { /* As this subarray is sorted, we can quickly check if key lies in half or other half */ if (key >= arr[l] && key <= arr[mid]) return search(arr, l, mid - 1, key); /*If key not lies in first half subarray, Divide other half into two subarrays, such that we can quickly check if key lies in other half */ return search(arr, mid + 1, h, key); } /* If arr[l..mid] first subarray is not sorted, then arr[mid... h] must be sorted subarray */ if (key >= arr[mid] && key <= arr[h]) return search(arr, mid + 1, h, key); return search(arr, l, mid - 1, key);} // Driver programlet arr = [ 4, 5, 6, 7, 8, 9, 1, 2, 3 ];let n = arr.length;let key = 6;let i = search(arr, 0, n - 1, key);if (i != -1) document.write(\"Index: \" +i +\"\");else document.write(\"Key not found\"); </script>", "e": 32470, "s": 31193, "text": null }, { "code": null, "e": 32479, "s": 32470, "text": "Output: " }, { "code": null, "e": 32488, "s": 32479, "text": "Index: 2" }, { "code": null, "e": 32511, "s": 32488, "text": "Complexity Analysis: " }, { "code": null, "e": 32632, "s": 32511, "text": "Time Complexity: O(log n). Binary Search requires log n comparisons to find the element. So time complexity is O(log n)." }, { "code": null, "e": 32687, "s": 32632, "text": "Space Complexity: O(1). As no extra space is required." }, { "code": null, "e": 33113, "s": 32687, "text": "Thanks to Gaurav Ahirwar for suggesting above solution. How to handle duplicates? It doesn’t look possible to search in O(Logn) time in all cases when duplicates are allowed. For example consider searching 0 in {2, 2, 2, 2, 2, 2, 2, 2, 0, 2} and {2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}. It doesn’t look possible to decide whether to recur for the left half or right half by doing a constant number of comparisons at the middle. " }, { "code": null, "e": 33960, "s": 33113, "text": "YouTubeGeeksforGeeks507K subscribersSearch an element in a sorted and rotated array | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 15:16•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=uN5QUBHUQaM\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 33980, "s": 33960, "text": "Similar Articles: " }, { "code": null, "e": 34035, "s": 33980, "text": "Find the minimum element in a sorted and rotated array" }, { "code": null, "e": 34111, "s": 34035, "text": "Given a sorted and rotated array, find if there is a pair with a given sum." }, { "code": null, "e": 34231, "s": 34111, "text": "Please write comments if you find any bug in the above codes/algorithms, or find other ways to solve the same problem. " }, { "code": null, "e": 34330, "s": 34231, "text": "Please refer complete article on Search an element in a sorted and rotated array for more details!" }, { "code": null, "e": 34336, "s": 34330, "text": "Adobe" }, { "code": null, "e": 34343, "s": 34336, "text": "Amazon" }, { "code": null, "e": 34354, "s": 34343, "text": "BankBazaar" }, { "code": null, "e": 34368, "s": 34354, "text": "Binary Search" }, { "code": null, "e": 34377, "s": 34368, "text": "D-E-Shaw" }, { "code": null, "e": 34385, "s": 34377, "text": "FactSet" }, { "code": null, "e": 34394, "s": 34385, "text": "Flipkart" }, { "code": null, "e": 34399, "s": 34394, "text": "Hike" }, { "code": null, "e": 34410, "s": 34399, "text": "MakeMyTrip" }, { "code": null, "e": 34420, "s": 34410, "text": "Microsoft" }, { "code": null, "e": 34426, "s": 34420, "text": "Paytm" }, { "code": null, "e": 34435, "s": 34426, "text": "rotation" }, { "code": null, "e": 34443, "s": 34435, "text": "Samsung" }, { "code": null, "e": 34452, "s": 34443, "text": "SAP Labs" }, { "code": null, "e": 34461, "s": 34452, "text": "Snapdeal" }, { "code": null, "e": 34476, "s": 34461, "text": "Times Internet" }, { "code": null, "e": 34483, "s": 34476, "text": "Arrays" }, { "code": null, "e": 34494, "s": 34483, "text": "JavaScript" }, { "code": null, "e": 34504, "s": 34494, "text": "Searching" }, { "code": null, "e": 34510, "s": 34504, "text": "Paytm" }, { "code": null, "e": 34519, "s": 34510, "text": "Flipkart" }, { "code": null, "e": 34526, "s": 34519, "text": "Amazon" }, { "code": null, "e": 34536, "s": 34526, "text": "Microsoft" }, { "code": null, "e": 34544, "s": 34536, "text": "Samsung" }, { "code": null, "e": 34553, "s": 34544, "text": "Snapdeal" }, { "code": null, "e": 34562, "s": 34553, "text": "D-E-Shaw" }, { "code": null, "e": 34570, "s": 34562, "text": "FactSet" }, { "code": null, "e": 34575, "s": 34570, "text": "Hike" }, { "code": null, "e": 34586, "s": 34575, "text": "MakeMyTrip" }, { "code": null, "e": 34592, "s": 34586, "text": "Adobe" }, { "code": null, "e": 34603, "s": 34592, "text": "BankBazaar" }, { "code": null, "e": 34618, "s": 34603, "text": "Times Internet" }, { "code": null, "e": 34627, "s": 34618, "text": "SAP Labs" }, { "code": null, "e": 34634, "s": 34627, "text": "Arrays" }, { "code": null, "e": 34644, "s": 34634, "text": "Searching" }, { "code": null, "e": 34658, "s": 34644, "text": "Binary Search" }, { "code": null, "e": 34756, "s": 34658, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34787, "s": 34756, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 34814, "s": 34787, "text": "Count pairs with given sum" }, { "code": null, "e": 34839, "s": 34814, "text": "Window Sliding Technique" }, { "code": null, "e": 34877, "s": 34839, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 34898, "s": 34877, "text": "Next Greater Element" }, { "code": null, "e": 34938, "s": 34898, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 34983, "s": 34938, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 35044, "s": 34983, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 35116, "s": 35044, "text": "Differences between Functional Components and Class Components in React" } ]
PyQt5 – Add image icon on a Push button - GeeksforGeeks
22 Apr, 2020 In this article we will see how to add icon to a push button. Here, setting icon not like setting an background image, it is similar to the icon of main window. Icon of button appear at the left side and text is on right size. Below is the representation of pus button without and with icon. In order to do this we will use setIcon method. Syntax : button.setIcon(QIcon(‘logo.png’)) Argument : It takes file name if in same folder else file path Action performed : It sets icon to the button. Code : # importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a push button button = QPushButton("CLICK", self) # setting geometry of button button.setGeometry(200, 150, 100, 30) # adding action to a button button.clicked.connect(self.clickme) # setting icon to the button button.setIcon(QIcon('logo.png')) # action method def clickme(self): # printing pressed print("pressed") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Convert integer to string in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25417, "s": 25389, "text": "\n22 Apr, 2020" }, { "code": null, "e": 25644, "s": 25417, "text": "In this article we will see how to add icon to a push button. Here, setting icon not like setting an background image, it is similar to the icon of main window. Icon of button appear at the left side and text is on right size." }, { "code": null, "e": 25710, "s": 25644, "text": "Below is the representation of pus button without and with icon. " }, { "code": null, "e": 25758, "s": 25710, "text": "In order to do this we will use setIcon method." }, { "code": null, "e": 25801, "s": 25758, "text": "Syntax : button.setIcon(QIcon(‘logo.png’))" }, { "code": null, "e": 25864, "s": 25801, "text": "Argument : It takes file name if in same folder else file path" }, { "code": null, "e": 25911, "s": 25864, "text": "Action performed : It sets icon to the button." }, { "code": null, "e": 25918, "s": 25911, "text": "Code :" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a push button button = QPushButton(\"CLICK\", self) # setting geometry of button button.setGeometry(200, 150, 100, 30) # adding action to a button button.clicked.connect(self.clickme) # setting icon to the button button.setIcon(QIcon('logo.png')) # action method def clickme(self): # printing pressed print(\"pressed\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 26965, "s": 25918, "text": null }, { "code": null, "e": 26974, "s": 26965, "text": "Output :" }, { "code": null, "e": 26985, "s": 26974, "text": "Python-gui" }, { "code": null, "e": 26997, "s": 26985, "text": "Python-PyQt" }, { "code": null, "e": 27004, "s": 26997, "text": "Python" }, { "code": null, "e": 27102, "s": 27004, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27137, "s": 27102, "text": "Read a file line by line in Python" }, { "code": null, "e": 27169, "s": 27137, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27191, "s": 27169, "text": "Enumerate() in Python" }, { "code": null, "e": 27233, "s": 27191, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27263, "s": 27233, "text": "Iterate over a list in Python" }, { "code": null, "e": 27289, "s": 27263, "text": "Python String | replace()" }, { "code": null, "e": 27333, "s": 27289, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27362, "s": 27333, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27398, "s": 27362, "text": "Convert integer to string in Python" } ]
How to play sounds in Python with Tkinter? - GeeksforGeeks
06 Jun, 2021 Python GUI tkinter is very useful when we want to take data from users. User attracts from GUI. GUI is very helpful in day to day life. A graphical user interface helps us to make our daily tasks easier and very productive. If you want to play music with the help of python GUI tkinter, then you come in the right way. For playing sound/music with help of python you need to install the required modules. This, module will help to play sound. There are two modules to play sound with the help of tkinter python: pygame : It is a cross-platform module to create games and GUI’s.playsound: It is a cross-platform module and its function name is playsound() pygame : It is a cross-platform module to create games and GUI’s. playsound: It is a cross-platform module and its function name is playsound() Let’s see how we can play sound/music with help of tkinter python GUI. You have to save your mp3 file in the same folder where you save your python file or you have to give the full path of the mp3 file. The mp3 file used the below methods is given here. Method 1: (Using playsound) To install playsound use this command pip install playsound Steps Needed First importing required modules.Initializing the Tk() and putting it in the variable for further use.Define a function for trigger it with help of a button.Create a button to trigger a function with the help of a command. First importing required modules. Initializing the Tk() and putting it in the variable for further use. Define a function for trigger it with help of a button. Create a button to trigger a function with the help of a command. Syntax : playsound(sound, block=True) Python3 # importing required modulefrom playsound import playsoundfrom tkinter import* root = Tk()root.title('GeeksforGeeks sound player') #giving the title for our windowroot.geometry("500x400") # making functiondef play(): playsound('1.mp3') # title on the screen you can modify it title=Label(root,text="GeeksforGeeks",bd=9,relief=GROOVE, font=("times new roman",50,"bold"),bg="white",fg="green")title.pack(side=TOP,fill=X) # making a button which trigger the function so sound can be playeedplay_button = Button(root, text="Play Song", font=("Helvetica", 32), relief=GROOVE, command=play)play_button.pack(pady=20) info=Label(root,text="Click on the button above to play song ", font=("times new roman",10,"bold")).pack(pady=20)root.mainloop() Output: Method 2: (Using pygame) To install pygame use this command pip install pygame Steps Needed When code will run then there one window open.In the window, there is one button. When we click on it there one function will start which plays the song.The function needs to be defined above to play the sound.Then make a mp3 file that is present on the same folder or when the mp3 file is not present on the same folder then give its full path to play the sound. (Be careful about this) When code will run then there one window open. In the window, there is one button. When we click on it there one function will start which plays the song. The function needs to be defined above to play the sound. Then make a mp3 file that is present on the same folder or when the mp3 file is not present on the same folder then give its full path to play the sound. (Be careful about this) Syntax: mixer.music.load(“song.mp3”) Python3 # importing required librariesfrom tkinter import *import pygame root = Tk()root.title('GeeksforGeeks sound player') root.geometry("500x400") pygame.mixer.init()# initialise the pygame def play(): pygame.mixer.music.load("1.mp3") pygame.mixer.music.play(loops=0) title=Label(root,text="GeeksforGeeks",bd=9,relief=GROOVE, font=("times new roman",50,"bold"),bg="white",fg="green")title.pack(side=TOP,fill=X) play_button = Button(root, text="Play Song", font=("Helvetica", 32), command=play)play_button.pack(pady=20)root.mainloop() Output: sweetyty ruhelaa48 Picked Python Tkinter-exercises Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25561, "s": 25533, "text": "\n06 Jun, 2021" }, { "code": null, "e": 26004, "s": 25561, "text": "Python GUI tkinter is very useful when we want to take data from users. User attracts from GUI. GUI is very helpful in day to day life. A graphical user interface helps us to make our daily tasks easier and very productive. If you want to play music with the help of python GUI tkinter, then you come in the right way. For playing sound/music with help of python you need to install the required modules. This, module will help to play sound." }, { "code": null, "e": 26073, "s": 26004, "text": "There are two modules to play sound with the help of tkinter python:" }, { "code": null, "e": 26216, "s": 26073, "text": "pygame : It is a cross-platform module to create games and GUI’s.playsound: It is a cross-platform module and its function name is playsound()" }, { "code": null, "e": 26282, "s": 26216, "text": "pygame : It is a cross-platform module to create games and GUI’s." }, { "code": null, "e": 26360, "s": 26282, "text": "playsound: It is a cross-platform module and its function name is playsound()" }, { "code": null, "e": 26615, "s": 26360, "text": "Let’s see how we can play sound/music with help of tkinter python GUI. You have to save your mp3 file in the same folder where you save your python file or you have to give the full path of the mp3 file. The mp3 file used the below methods is given here." }, { "code": null, "e": 26643, "s": 26615, "text": "Method 1: (Using playsound)" }, { "code": null, "e": 26681, "s": 26643, "text": "To install playsound use this command" }, { "code": null, "e": 26704, "s": 26681, "text": "pip install playsound " }, { "code": null, "e": 26717, "s": 26704, "text": "Steps Needed" }, { "code": null, "e": 26940, "s": 26717, "text": "First importing required modules.Initializing the Tk() and putting it in the variable for further use.Define a function for trigger it with help of a button.Create a button to trigger a function with the help of a command." }, { "code": null, "e": 26974, "s": 26940, "text": "First importing required modules." }, { "code": null, "e": 27044, "s": 26974, "text": "Initializing the Tk() and putting it in the variable for further use." }, { "code": null, "e": 27100, "s": 27044, "text": "Define a function for trigger it with help of a button." }, { "code": null, "e": 27166, "s": 27100, "text": "Create a button to trigger a function with the help of a command." }, { "code": null, "e": 27204, "s": 27166, "text": "Syntax : playsound(sound, block=True)" }, { "code": null, "e": 27212, "s": 27204, "text": "Python3" }, { "code": "# importing required modulefrom playsound import playsoundfrom tkinter import* root = Tk()root.title('GeeksforGeeks sound player') #giving the title for our windowroot.geometry(\"500x400\") # making functiondef play(): playsound('1.mp3') # title on the screen you can modify it title=Label(root,text=\"GeeksforGeeks\",bd=9,relief=GROOVE, font=(\"times new roman\",50,\"bold\"),bg=\"white\",fg=\"green\")title.pack(side=TOP,fill=X) # making a button which trigger the function so sound can be playeedplay_button = Button(root, text=\"Play Song\", font=(\"Helvetica\", 32), relief=GROOVE, command=play)play_button.pack(pady=20) info=Label(root,text=\"Click on the button above to play song \", font=(\"times new roman\",10,\"bold\")).pack(pady=20)root.mainloop()", "e": 27998, "s": 27212, "text": null }, { "code": null, "e": 28009, "s": 28001, "text": "Output:" }, { "code": null, "e": 28038, "s": 28013, "text": "Method 2: (Using pygame)" }, { "code": null, "e": 28075, "s": 28040, "text": "To install pygame use this command" }, { "code": null, "e": 28096, "s": 28077, "text": "pip install pygame" }, { "code": null, "e": 28111, "s": 28098, "text": "Steps Needed" }, { "code": null, "e": 28501, "s": 28113, "text": "When code will run then there one window open.In the window, there is one button. When we click on it there one function will start which plays the song.The function needs to be defined above to play the sound.Then make a mp3 file that is present on the same folder or when the mp3 file is not present on the same folder then give its full path to play the sound. (Be careful about this)" }, { "code": null, "e": 28548, "s": 28501, "text": "When code will run then there one window open." }, { "code": null, "e": 28656, "s": 28548, "text": "In the window, there is one button. When we click on it there one function will start which plays the song." }, { "code": null, "e": 28714, "s": 28656, "text": "The function needs to be defined above to play the sound." }, { "code": null, "e": 28892, "s": 28714, "text": "Then make a mp3 file that is present on the same folder or when the mp3 file is not present on the same folder then give its full path to play the sound. (Be careful about this)" }, { "code": null, "e": 28929, "s": 28892, "text": "Syntax: mixer.music.load(“song.mp3”)" }, { "code": null, "e": 28939, "s": 28931, "text": "Python3" }, { "code": "# importing required librariesfrom tkinter import *import pygame root = Tk()root.title('GeeksforGeeks sound player') root.geometry(\"500x400\") pygame.mixer.init()# initialise the pygame def play(): pygame.mixer.music.load(\"1.mp3\") pygame.mixer.music.play(loops=0) title=Label(root,text=\"GeeksforGeeks\",bd=9,relief=GROOVE, font=(\"times new roman\",50,\"bold\"),bg=\"white\",fg=\"green\")title.pack(side=TOP,fill=X) play_button = Button(root, text=\"Play Song\", font=(\"Helvetica\", 32), command=play)play_button.pack(pady=20)root.mainloop()", "e": 29485, "s": 28939, "text": null }, { "code": null, "e": 29496, "s": 29488, "text": "Output:" }, { "code": null, "e": 29509, "s": 29500, "text": "sweetyty" }, { "code": null, "e": 29519, "s": 29509, "text": "ruhelaa48" }, { "code": null, "e": 29526, "s": 29519, "text": "Picked" }, { "code": null, "e": 29551, "s": 29526, "text": "Python Tkinter-exercises" }, { "code": null, "e": 29566, "s": 29551, "text": "Python-tkinter" }, { "code": null, "e": 29573, "s": 29566, "text": "Python" }, { "code": null, "e": 29671, "s": 29573, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29703, "s": 29671, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29745, "s": 29703, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29787, "s": 29745, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29814, "s": 29787, "text": "Python Classes and Objects" }, { "code": null, "e": 29870, "s": 29814, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29892, "s": 29870, "text": "Defaultdict in Python" }, { "code": null, "e": 29931, "s": 29892, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29962, "s": 29931, "text": "Python | os.path.join() method" }, { "code": null, "e": 29991, "s": 29962, "text": "Create a directory in Python" } ]
SQL query to find second highest salary? - GeeksforGeeks
02 Nov, 2021 Consider below simple table: Name Salary --------------- abc 100000 bcd 1000000 efg 40000 ghi 500000 How to find the employee whose salary is second highest. For example, in above table, “ghi” has the second highest salary as 500000. Below is simple query to find the employee whose salary is highest. select *from employee where salary=(select Max(salary) from employee); We can nest the above query to find the second largest salary. select *from employee group by salary order by salary desc limit 1,1; There are other ways : SELECT name, MAX(salary) AS salary FROM employee WHERE salary IN (SELECT salary FROM employee MINUS SELECT MAX(salary) FROM employee); SELECT name, MAX(salary) AS salary FROM employee WHERE salary <> (SELECT MAX(salary) FROM employee); IN SQL Server using Common Table Expression or CTE, we can find the second highest salary: WITH T AS ( SELECT * DENSE_RANK() OVER (ORDER BY Salary Desc) AS Rnk FROM Employees ) SELECT Name FROM T WHERE Rnk=2; How to find the third largest salary? Simple, we can do one more nesting. SELECT name, MAX(salary) AS salary FROM employee WHERE salary < (SELECT MAX(salary) FROM employee WHERE salary < (SELECT MAX(salary) FROM employee) ); Note that instead of nesting for second, third, etc largest salary, we can find nth salary using general query like in MySQL: SELECT salary FROM employee ORDER BY salary desc limit n-1,1 SELECT name, salary FROM employee A WHERE n-1 = (SELECT count(1) FROM employee B WHERE B.salary>A.salary) If multiple employee have same salary. Suppose you have to find 4th highest salary SELECT * FROM employee WHERE salary= (SELECT DISTINCT(salary) FROM employee ORDER BY salary LIMIT 3,1); Generic query will be SELECT * FROM employee WHERE salary= (SELECT DISTINCT(salary) FROM employee ORDER BY salary DESC LIMIT n-1,1); YouTubeGeeksforGeeks507K subscribers1. 2nd Highest Salary (Top 50 SQL Interview Questions)| GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:42•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=-6v7ctxC7yk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This Solution is provided by Mohit. This article is contributed by Kartik. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. p3arl pradeepthyadi hespacelti sj016267 ankitmishrar darshkaushik DBMS-SQL DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions Introduction of B-Tree CTE in SQL SQL Trigger | Student Database Difference between Clustered and Non-clustered index Data Preprocessing in Data Mining Introduction of ER Model Introduction of DBMS (Database Management System) | Set 1 Difference between SQL and NoSQL Difference between DDL and DML in DBMS
[ { "code": null, "e": 25979, "s": 25951, "text": "\n02 Nov, 2021" }, { "code": null, "e": 26009, "s": 25979, "text": "Consider below simple table: " }, { "code": null, "e": 26101, "s": 26009, "text": "Name Salary\n---------------\nabc 100000\nbcd 1000000\nefg 40000\nghi 500000" }, { "code": null, "e": 26235, "s": 26101, "text": "How to find the employee whose salary is second highest. For example, in above table, “ghi” has the second highest salary as 500000. " }, { "code": null, "e": 26304, "s": 26235, "text": "Below is simple query to find the employee whose salary is highest. " }, { "code": null, "e": 26377, "s": 26304, "text": " select *from employee where salary=(select Max(salary) from employee);" }, { "code": null, "e": 26441, "s": 26377, "text": "We can nest the above query to find the second largest salary. " }, { "code": null, "e": 26514, "s": 26441, "text": "select *from employee \ngroup by salary \norder by salary desc limit 1,1;" }, { "code": null, "e": 26537, "s": 26514, "text": "There are other ways :" }, { "code": null, "e": 26676, "s": 26537, "text": "SELECT name, MAX(salary) AS salary \nFROM employee \nWHERE salary IN\n(SELECT salary FROM employee MINUS SELECT MAX(salary) \nFROM employee); " }, { "code": null, "e": 26782, "s": 26678, "text": "SELECT name, MAX(salary) AS salary \nFROM employee \nWHERE salary <> (SELECT MAX(salary) \nFROM employee);" }, { "code": null, "e": 26874, "s": 26782, "text": "IN SQL Server using Common Table Expression or CTE, we can find the second highest salary: " }, { "code": null, "e": 26995, "s": 26874, "text": "WITH T AS\n(\nSELECT *\n DENSE_RANK() OVER (ORDER BY Salary Desc) AS Rnk\nFROM Employees\n)\nSELECT Name\nFROM T\nWHERE Rnk=2;" }, { "code": null, "e": 27071, "s": 26995, "text": "How to find the third largest salary? Simple, we can do one more nesting. " }, { "code": null, "e": 27294, "s": 27071, "text": "SELECT name, MAX(salary) AS salary\n FROM employee\n WHERE salary < (SELECT MAX(salary) \n FROM employee\n WHERE salary < (SELECT MAX(salary)\n FROM employee)\n ); " }, { "code": null, "e": 27421, "s": 27294, "text": "Note that instead of nesting for second, third, etc largest salary, we can find nth salary using general query like in MySQL: " }, { "code": null, "e": 27484, "s": 27421, "text": "SELECT salary \nFROM employee \nORDER BY salary desc limit n-1,1" }, { "code": null, "e": 27618, "s": 27484, "text": "SELECT name, salary\nFROM employee A\nWHERE n-1 = (SELECT count(1) \n FROM employee B \n WHERE B.salary>A.salary)" }, { "code": null, "e": 27702, "s": 27618, "text": "If multiple employee have same salary. Suppose you have to find 4th highest salary " }, { "code": null, "e": 27808, "s": 27702, "text": "SELECT * FROM employee \nWHERE salary= (SELECT DISTINCT(salary) \nFROM employee ORDER BY salary LIMIT 3,1);" }, { "code": null, "e": 27831, "s": 27808, "text": "Generic query will be " }, { "code": null, "e": 27944, "s": 27831, "text": "SELECT * FROM employee \nWHERE salary= (SELECT DISTINCT(salary) \nFROM employee ORDER BY salary DESC LIMIT n-1,1);" }, { "code": null, "e": 28798, "s": 27946, "text": "YouTubeGeeksforGeeks507K subscribers1. 2nd Highest Salary (Top 50 SQL Interview Questions)| GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:42•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=-6v7ctxC7yk\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 28834, "s": 28798, "text": "This Solution is provided by Mohit." }, { "code": null, "e": 28999, "s": 28834, "text": "This article is contributed by Kartik. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 29005, "s": 28999, "text": "p3arl" }, { "code": null, "e": 29019, "s": 29005, "text": "pradeepthyadi" }, { "code": null, "e": 29030, "s": 29019, "text": "hespacelti" }, { "code": null, "e": 29039, "s": 29030, "text": "sj016267" }, { "code": null, "e": 29052, "s": 29039, "text": "ankitmishrar" }, { "code": null, "e": 29065, "s": 29052, "text": "darshkaushik" }, { "code": null, "e": 29074, "s": 29065, "text": "DBMS-SQL" }, { "code": null, "e": 29079, "s": 29074, "text": "DBMS" }, { "code": null, "e": 29084, "s": 29079, "text": "DBMS" }, { "code": null, "e": 29182, "s": 29084, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29206, "s": 29182, "text": "SQL Interview Questions" }, { "code": null, "e": 29229, "s": 29206, "text": "Introduction of B-Tree" }, { "code": null, "e": 29240, "s": 29229, "text": "CTE in SQL" }, { "code": null, "e": 29271, "s": 29240, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 29324, "s": 29271, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 29358, "s": 29324, "text": "Data Preprocessing in Data Mining" }, { "code": null, "e": 29383, "s": 29358, "text": "Introduction of ER Model" }, { "code": null, "e": 29441, "s": 29383, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 29474, "s": 29441, "text": "Difference between SQL and NoSQL" } ]
HashMap compute() method in Java with Examples - GeeksforGeeks
25 Oct, 2021 The compute(Key, BiFunction) method of HashMap class allows you to update a value in HashMap. The compute() method tries to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping is found). This method is used to automatically update a value for given key in HashMap. If the remapping function passed in compute returns null, the mapping is removed from Map (or remains absent if initially absent). If the remapping function throws an exception, the exception is re-thrown, and the current mapping is left unchanged. During computation, remapping function should not be able to modify this map.The compute() method can be used to update an existing value inside HashMap.For example,Mapping to increment a int value of mapping: map.compute(key, (k, v) -> (v == null) ? 1 : v+1) Mapping to increment a int value of mapping: map.compute(key, (k, v) -> (v == null) ? 1 : v+1) The default implementation of this method takes no guarantee for detecting an error if the remapping function of compute() method modifies this map during computation. Exceptions :Non-concurrent implementations of this method should override this method and throw a ConcurrentModificationException if it is detected a change in mapping during computation. Concurrent implementations should override this method throw an IllegalStateException if it is detected a change in mapping during computation and as a result computation would never complete. The default implementation of this method takes no guarantees about synchronization or atomic properties of this method. Any implementation providing atomicity guarantees must override this method and document its concurrency properties. Syntax: default V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) Parameters: This method accepts two parameters: key: key with which associate the value. remappingFunction: function to compute the value. Returns: This method returns new value associated with the specified key, or null if none. Exception: This method throws: NullPointerException: if the key is null and this map does not support null keys, or the remappingFunction is null. UnsupportedOperationException: if the put operation is not supported by this map. ClassCastException: if the class of the key or value prevents it from being stored in this map. IllegalArgumentException: if some property of the key or value prevents it from being stored in this map. Below programs illustrate the compute(Key, BiFunction) method: Program 1: // Java program to demonstrate// compute(Key, BiFunction) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a Map and add some values Map<String, String> map = new HashMap<>(); map.put("Name", "Aman"); map.put("Address", "Kolkata"); // Print the map System.out.println("Map: " + map); // remap the values using compute() method map.compute("Name", (key, val) -> val.concat(" Singh")); map.compute("Address", (key, val) -> val.concat(" West-Bengal")); // print new mapping System.out.println("New Map: " + map); }} Map: {Address=Kolkata, Name=Aman} New Map: {Address=Kolkata West-Bengal, Name=Aman Singh} Program 2: // Java program to demonstrate// compute(Key, BiFunction) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a Map and add some values Map<String, Integer> map = new HashMap<>(); map.put("Key1", 12); map.put("Key2", 15); // print map details System.out.println("Map: " + map); // remap the values // using compute method map.compute("Key1", (key, val) -> (val == null) ? 1 : val + 1); map.compute("Key2", (key, val) -> (val == null) ? 1 : val + 5); // print new mapping System.out.println("New Map: " + map); }} Map: {Key2=15, Key1=12} New Map: {Key2=20, Key1=13} Program 3: To show NullPointerException // Java program to demonstrate Exception thrown by// compute(Key, BiFunction) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // create a Map and add some values Map<String, Integer> map = new HashMap<>(); map.put("Key1", 12); map.put("Key2", 15); // print map details System.out.println("Map: " + map); try { // remap the values using compute() method // passing null value will throw exception map.compute(null, (key, value) -> value + 3); System.out.println("New Map: " + map); } catch (NullPointerException e) { System.out.println("Exception: " + e); } }} Map: {Key2=15, Key1=12} Exception: java.lang.NullPointerException References: https://docs.oracle.com/javase/10/docs/api/java/util/HashMap.html#compute(K, java.util.function.BiFunction) hariomsingh25700 java-basics Java-Functions Java-HashMap Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java LinkedList in Java Collections in Java
[ { "code": null, "e": 24195, "s": 24167, "text": "\n25 Oct, 2021" }, { "code": null, "e": 24517, "s": 24195, "text": "The compute(Key, BiFunction) method of HashMap class allows you to update a value in HashMap. The compute() method tries to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping is found). This method is used to automatically update a value for given key in HashMap." }, { "code": null, "e": 24648, "s": 24517, "text": "If the remapping function passed in compute returns null, the mapping is removed from Map (or remains absent if initially absent)." }, { "code": null, "e": 24766, "s": 24648, "text": "If the remapping function throws an exception, the exception is re-thrown, and the current mapping is left unchanged." }, { "code": null, "e": 25026, "s": 24766, "text": "During computation, remapping function should not be able to modify this map.The compute() method can be used to update an existing value inside HashMap.For example,Mapping to increment a int value of mapping: map.compute(key, (k, v) -> (v == null) ? 1 : v+1)" }, { "code": null, "e": 25121, "s": 25026, "text": "Mapping to increment a int value of mapping: map.compute(key, (k, v) -> (v == null) ? 1 : v+1)" }, { "code": null, "e": 25289, "s": 25121, "text": "The default implementation of this method takes no guarantee for detecting an error if the remapping function of compute() method modifies this map during computation." }, { "code": null, "e": 25670, "s": 25289, "text": "Exceptions :Non-concurrent implementations of this method should override this method and throw a ConcurrentModificationException if it is detected a change in mapping during computation. Concurrent implementations should override this method throw an IllegalStateException if it is detected a change in mapping during computation and as a result computation would never complete." }, { "code": null, "e": 25908, "s": 25670, "text": "The default implementation of this method takes no guarantees about synchronization or atomic properties of this method. Any implementation providing atomicity guarantees must override this method and document its concurrency properties." }, { "code": null, "e": 25916, "s": 25908, "text": "Syntax:" }, { "code": null, "e": 26045, "s": 25916, "text": "default V \n compute(K key,\n BiFunction<? super K, ? super V, ? \n extends V> remappingFunction)" }, { "code": null, "e": 26093, "s": 26045, "text": "Parameters: This method accepts two parameters:" }, { "code": null, "e": 26134, "s": 26093, "text": "key: key with which associate the value." }, { "code": null, "e": 26184, "s": 26134, "text": "remappingFunction: function to compute the value." }, { "code": null, "e": 26275, "s": 26184, "text": "Returns: This method returns new value associated with the specified key, or null if none." }, { "code": null, "e": 26306, "s": 26275, "text": "Exception: This method throws:" }, { "code": null, "e": 26422, "s": 26306, "text": "NullPointerException: if the key is null and this map does not support null keys, or the remappingFunction is null." }, { "code": null, "e": 26504, "s": 26422, "text": "UnsupportedOperationException: if the put operation is not supported by this map." }, { "code": null, "e": 26600, "s": 26504, "text": "ClassCastException: if the class of the key or value prevents it from being stored in this map." }, { "code": null, "e": 26706, "s": 26600, "text": "IllegalArgumentException: if some property of the key or value prevents it from being stored in this map." }, { "code": null, "e": 26769, "s": 26706, "text": "Below programs illustrate the compute(Key, BiFunction) method:" }, { "code": null, "e": 26780, "s": 26769, "text": "Program 1:" }, { "code": "// Java program to demonstrate// compute(Key, BiFunction) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a Map and add some values Map<String, String> map = new HashMap<>(); map.put(\"Name\", \"Aman\"); map.put(\"Address\", \"Kolkata\"); // Print the map System.out.println(\"Map: \" + map); // remap the values using compute() method map.compute(\"Name\", (key, val) -> val.concat(\" Singh\")); map.compute(\"Address\", (key, val) -> val.concat(\" West-Bengal\")); // print new mapping System.out.println(\"New Map: \" + map); }}", "e": 27523, "s": 26780, "text": null }, { "code": null, "e": 27614, "s": 27523, "text": "Map: {Address=Kolkata, Name=Aman}\nNew Map: {Address=Kolkata West-Bengal, Name=Aman Singh}\n" }, { "code": null, "e": 27625, "s": 27614, "text": "Program 2:" }, { "code": "// Java program to demonstrate// compute(Key, BiFunction) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a Map and add some values Map<String, Integer> map = new HashMap<>(); map.put(\"Key1\", 12); map.put(\"Key2\", 15); // print map details System.out.println(\"Map: \" + map); // remap the values // using compute method map.compute(\"Key1\", (key, val) -> (val == null) ? 1 : val + 1); map.compute(\"Key2\", (key, val) -> (val == null) ? 1 : val + 5); // print new mapping System.out.println(\"New Map: \" + map); }}", "e": 28521, "s": 27625, "text": null }, { "code": null, "e": 28574, "s": 28521, "text": "Map: {Key2=15, Key1=12}\nNew Map: {Key2=20, Key1=13}\n" }, { "code": null, "e": 28614, "s": 28574, "text": "Program 3: To show NullPointerException" }, { "code": "// Java program to demonstrate Exception thrown by// compute(Key, BiFunction) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // create a Map and add some values Map<String, Integer> map = new HashMap<>(); map.put(\"Key1\", 12); map.put(\"Key2\", 15); // print map details System.out.println(\"Map: \" + map); try { // remap the values using compute() method // passing null value will throw exception map.compute(null, (key, value) -> value + 3); System.out.println(\"New Map: \" + map); } catch (NullPointerException e) { System.out.println(\"Exception: \" + e); } }}", "e": 29413, "s": 28614, "text": null }, { "code": null, "e": 29480, "s": 29413, "text": "Map: {Key2=15, Key1=12}\nException: java.lang.NullPointerException\n" }, { "code": null, "e": 29600, "s": 29480, "text": "References: https://docs.oracle.com/javase/10/docs/api/java/util/HashMap.html#compute(K, java.util.function.BiFunction)" }, { "code": null, "e": 29617, "s": 29600, "text": "hariomsingh25700" }, { "code": null, "e": 29629, "s": 29617, "text": "java-basics" }, { "code": null, "e": 29644, "s": 29629, "text": "Java-Functions" }, { "code": null, "e": 29657, "s": 29644, "text": "Java-HashMap" }, { "code": null, "e": 29662, "s": 29657, "text": "Java" }, { "code": null, "e": 29667, "s": 29662, "text": "Java" }, { "code": null, "e": 29765, "s": 29667, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29774, "s": 29765, "text": "Comments" }, { "code": null, "e": 29787, "s": 29774, "text": "Old Comments" }, { "code": null, "e": 29838, "s": 29787, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29869, "s": 29838, "text": "How to iterate any Map in Java" }, { "code": null, "e": 29901, "s": 29869, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29920, "s": 29901, "text": "Interfaces in Java" }, { "code": null, "e": 29938, "s": 29920, "text": "ArrayList in Java" }, { "code": null, "e": 29970, "s": 29938, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 29990, "s": 29970, "text": "Stack Class in Java" }, { "code": null, "e": 30014, "s": 29990, "text": "Singleton Class in Java" }, { "code": null, "e": 30033, "s": 30014, "text": "LinkedList in Java" } ]
Four Elements | Practice | GeeksforGeeks
Given an array A of N integers. You have to find whether a combination of four elements in the array whose sum is equal to a given value X exists or not. Example 1: Input: N = 6 A[] = {1, 5, 1, 0, 6, 0} X = 7 Output: 1 Explantion: 1, 5, 1, 0 are the four elements which makes sum 7. Your Task: You don't need to read input or print anything. Your task is to complete the function find4Numbers() which takes the array A[], its size N and an integer X as inputs and returns true if combination is found else false. Driver code will print 1 or 0 accordingly. Expected Time Complexity: O(N3) Expected Auxiliary Space: O(1) Constraints: 4 <= N <= 100 1 <= A[i] <= 1000 +1 cs190951 month ago bool find4Numbers(int A[], int n, int X) { for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { for(int k=j+1;k<n;k++) { for(int l=k+1;l<n;l++) { if(A[i]+A[j]+A[k]+A[l]==X) { return 1; } } } } } return 0; } +2 gaurabhkumarjha271020013 months ago bool find4Numbers(int nums[], int n, int target) { sort (nums, nums+n); for (int i=0; i< n; i++){ for (int j= i+1; j< n; j++){ int new_target= target - nums[i] - nums[j]; int k= n-1; int l= j+1; while (l< k){ int sum= nums[l]+nums[k]; if (sum > new_target) k--; else if (sum < new_target) l++; else{ return true; } } } } return false; } 0 amiransarimy3 months ago Python Solutions: Total Time Taken: 0.2/2.4 def find4Numbers( A, n, X): A.sort() #sort Array for i in range(n-3): for j in range(i+1,n-2): l=j+1 r=n-1 while l < r: curr_sum = A[i] +A[j] + A[l] + A[r] if curr_sum == X: return True elif curr_sum < X: l += 1 else: r -= 1 return False 0 kashifraza12084 months ago bool find4Numbers(int arr[], int n, int X) { sort(arr , arr+n); for(int i=0;i<n-3;i++){ for(int j=i+1;j<n-2;j++){ int front = j+1; int back = n-1; while(front<back){ int sum = arr[i]+arr[j]+ arr[front]+arr[back]; if(sum<X) front++; else if(sum>X) back--; else{ return true; } } } } return false;} 0 rhythmanand6Premium6 months ago Java Solution boolean find4Numbers(int A[], int n, int X) { int i, j, l, h; Arrays.sort(A); for(i=0; i<n-3; i++){ for(j=i+1; j<n-2; j++){ l = j+1; h = n-1; while(l<h){ int sum = A[i]+A[j]+A[l]+A[h]; if(sum == X) return true; else if(sum<X) l++; else h--; } } } return false; } +1 ankitsinha1112006 months ago bool find4Numbers(int a[], int n, int X) { int i,j,l,h; sort(a,a+n); for(i=0;i<n-3;i++) { for(j=i+1;j<n-2;j++) { l=j+1; h=n-1; int sum=a[i]+a[j]+a[l]+a[h]; while(l<h) { if(sum==X) return 1; if(sum<X) { sum-=a[l]; l++; sum+=a[l]; } else { sum-=a[h]; h--; sum+=a[h]; } } } } return 0; } 0 19eucs076zap6 months ago class Compute{ boolean find4Numbers(int A[], int n, int X) { int l,h,req,sum; Arrays.sort(A); for(int i=0;i<n-3;i++){ for(int j=i+1;j<n-2;j++){ req=X-(A[i]+A[j]); l=j+1; h=n-1; while(l<h){ sum=A[l]+A[h]; if(sum==req){ return true; } if(sum<req){ l++; } else{ h--; } } } } return false; }} 0 sanketsupekar6 months ago Java Solution 0.3 Sec class Compute { boolean find4Numbers(int A[], int n, int X) { Arrays.sort(A); int sum=0; for(int i=0;i<n-3;i++) { for(int j=i+1;j<n-2;j++) { sum=A[i]+A[j]; if(sum>=X) continue; int l=j+1,r=n-1; int diff=X-sum; while(l<r) { int curSum=A[l]+A[r]; if(curSum==diff) return true; else if(curSum<diff) l++; else r--; } } } return false; } } 0 mehteshamulhaq6 months ago How to reduce Time Complexity can any one Guide me? here Is my code def find4Numbers( A, n, X): A.sort() if len(A) <4 and len(A) >1000: return False for i in range(n-3): for j in range(i+1,n-2): for k in range(j+1,n-1): for l in range(k+1,n): if A[i]+A[j]+A[k]+A[l] == X: return True else: return False -1 shiva10906 months ago i have used sliding window technique, but the answer is getting wrong for some test cases please find where there is mistake in code. bool find4Numbers(int A[], int n, int X) { int sum=0; for(int i=0; i<4; i++){ sum+=A[i]; } if(sum==X){ return true; } for(int i=4; i<n; i++){ if(sum==X){ return true; break; } sum-=A[i-4]; sum+=A[i]; } return false; } 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": 394, "s": 238, "text": "Given an array A of N integers. You have to find whether a combination of four elements in the array whose sum is equal to a given value X exists or not.\n " }, { "code": null, "e": 405, "s": 394, "text": "Example 1:" }, { "code": null, "e": 524, "s": 405, "text": "Input:\nN = 6\nA[] = {1, 5, 1, 0, 6, 0}\nX = 7\nOutput:\n1\n\nExplantion:\n1, 5, 1, 0 are the four elements which makes sum 7." }, { "code": null, "e": 802, "s": 526, "text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function find4Numbers() which takes the array A[], its size N and an integer X as inputs and returns true if combination is found else false. Driver code will print 1 or 0 accordingly." }, { "code": null, "e": 867, "s": 804, "text": "Expected Time Complexity: O(N3)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 914, "s": 869, "text": "Constraints:\n4 <= N <= 100\n1 <= A[i] <= 1000" }, { "code": null, "e": 917, "s": 914, "text": "+1" }, { "code": null, "e": 936, "s": 917, "text": "cs190951 month ago" }, { "code": null, "e": 1348, "s": 936, "text": "bool find4Numbers(int A[], int n, int X) \n{\n for(int i=0;i<n;i++)\n {\n for(int j=i+1;j<n;j++)\n {\n for(int k=j+1;k<n;k++)\n {\n for(int l=k+1;l<n;l++)\n {\n if(A[i]+A[j]+A[k]+A[l]==X)\n {\n return 1;\n }\n }\n }\n }\n }\n return 0;\n}" }, { "code": null, "e": 1351, "s": 1348, "text": "+2" }, { "code": null, "e": 1387, "s": 1351, "text": "gaurabhkumarjha271020013 months ago" }, { "code": null, "e": 2040, "s": 1387, "text": "bool find4Numbers(int nums[], int n, int target) \n{\n sort (nums, nums+n);\n \n for (int i=0; i< n; i++){\n \n for (int j= i+1; j< n; j++){\n \n int new_target= target - nums[i] - nums[j];\n int k= n-1;\n int l= j+1;\n \n while (l< k){\n \n int sum= nums[l]+nums[k];\n \n if (sum > new_target)\n k--;\n \n else if (sum < new_target)\n l++;\n \n else{\n \n return true; \n } \n }\n }\n }\n \n return false;\n}" }, { "code": null, "e": 2042, "s": 2040, "text": "0" }, { "code": null, "e": 2067, "s": 2042, "text": "amiransarimy3 months ago" }, { "code": null, "e": 2085, "s": 2067, "text": "Python Solutions:" }, { "code": null, "e": 2111, "s": 2085, "text": "Total Time Taken: 0.2/2.4" }, { "code": null, "e": 2524, "s": 2113, "text": "def find4Numbers( A, n, X):\n A.sort() #sort Array\n for i in range(n-3):\n for j in range(i+1,n-2):\n l=j+1\n r=n-1\n while l < r:\n curr_sum = A[i] +A[j] + A[l] + A[r] \n if curr_sum == X:\n return True\n elif curr_sum < X:\n l += 1\n else:\n r -= 1\n return False" }, { "code": null, "e": 2528, "s": 2526, "text": "0" }, { "code": null, "e": 2555, "s": 2528, "text": "kashifraza12084 months ago" }, { "code": null, "e": 2626, "s": 2555, "text": "bool find4Numbers(int arr[], int n, int X) { sort(arr , arr+n);" }, { "code": null, "e": 3130, "s": 2634, "text": " for(int i=0;i<n-3;i++){ for(int j=i+1;j<n-2;j++){ int front = j+1; int back = n-1; while(front<back){ int sum = arr[i]+arr[j]+ arr[front]+arr[back]; if(sum<X) front++; else if(sum>X) back--; else{ return true; } } } } return false;}" }, { "code": null, "e": 3132, "s": 3130, "text": "0" }, { "code": null, "e": 3164, "s": 3132, "text": "rhythmanand6Premium6 months ago" }, { "code": null, "e": 3179, "s": 3164, "text": "Java Solution " }, { "code": null, "e": 3659, "s": 3179, "text": "boolean find4Numbers(int A[], int n, int X) \n {\n int i, j, l, h;\n Arrays.sort(A);\n for(i=0; i<n-3; i++){\n for(j=i+1; j<n-2; j++){\n l = j+1;\n h = n-1;\n while(l<h){\n int sum = A[i]+A[j]+A[l]+A[h];\n if(sum == X) return true;\n else if(sum<X) l++;\n else h--;\n }\n }\n }\n return false;\n }" }, { "code": null, "e": 3662, "s": 3659, "text": "+1" }, { "code": null, "e": 3691, "s": 3662, "text": "ankitsinha1112006 months ago" }, { "code": null, "e": 4323, "s": 3691, "text": "bool find4Numbers(int a[], int n, int X) \n{\n int i,j,l,h;\n sort(a,a+n);\n for(i=0;i<n-3;i++)\n {\n for(j=i+1;j<n-2;j++)\n {\n l=j+1;\n h=n-1;\n int sum=a[i]+a[j]+a[l]+a[h];\n while(l<h)\n {\n if(sum==X)\n return 1;\n if(sum<X)\n {\n sum-=a[l];\n l++;\n sum+=a[l];\n }\n else\n {\n sum-=a[h];\n h--;\n sum+=a[h];\n }\n }\n }\n }\n return 0;\n}" }, { "code": null, "e": 4325, "s": 4323, "text": "0" }, { "code": null, "e": 4350, "s": 4325, "text": "19eucs076zap6 months ago" }, { "code": null, "e": 4958, "s": 4350, "text": "class Compute{ boolean find4Numbers(int A[], int n, int X) { int l,h,req,sum; Arrays.sort(A); for(int i=0;i<n-3;i++){ for(int j=i+1;j<n-2;j++){ req=X-(A[i]+A[j]); l=j+1; h=n-1; while(l<h){ sum=A[l]+A[h]; if(sum==req){ return true; } if(sum<req){ l++; } else{ h--; } } } } return false; }}" }, { "code": null, "e": 4960, "s": 4958, "text": "0" }, { "code": null, "e": 4986, "s": 4960, "text": "sanketsupekar6 months ago" }, { "code": null, "e": 5008, "s": 4986, "text": "Java Solution 0.3 Sec" }, { "code": null, "e": 5708, "s": 5008, "text": "class Compute\n{\n boolean find4Numbers(int A[], int n, int X) \n {\n Arrays.sort(A);\n int sum=0;\n for(int i=0;i<n-3;i++)\n {\n for(int j=i+1;j<n-2;j++)\n {\n sum=A[i]+A[j];\n if(sum>=X)\n continue;\n int l=j+1,r=n-1;\n int diff=X-sum;\n while(l<r)\n {\n int curSum=A[l]+A[r];\n if(curSum==diff)\n return true;\n else if(curSum<diff)\n l++;\n else\n r--;\n }\n }\n }\n return false;\n }\n}" }, { "code": null, "e": 5710, "s": 5708, "text": "0" }, { "code": null, "e": 5737, "s": 5710, "text": "mehteshamulhaq6 months ago" }, { "code": null, "e": 5789, "s": 5737, "text": "How to reduce Time Complexity can any one Guide me?" }, { "code": null, "e": 5806, "s": 5789, "text": " here Is my code" }, { "code": null, "e": 6134, "s": 5806, "text": "def find4Numbers( A, n, X): A.sort() if len(A) <4 and len(A) >1000: return False for i in range(n-3): for j in range(i+1,n-2): for k in range(j+1,n-1): for l in range(k+1,n): if A[i]+A[j]+A[k]+A[l] == X: return True else: return False" }, { "code": null, "e": 6137, "s": 6134, "text": "-1" }, { "code": null, "e": 6159, "s": 6137, "text": "shiva10906 months ago" }, { "code": null, "e": 6293, "s": 6159, "text": "i have used sliding window technique, but the answer is getting wrong for some test cases please find where there is mistake in code." }, { "code": null, "e": 6587, "s": 6297, "text": "bool find4Numbers(int A[], int n, int X) { int sum=0; for(int i=0; i<4; i++){ sum+=A[i]; } if(sum==X){ return true; } for(int i=4; i<n; i++){ if(sum==X){ return true; break; } sum-=A[i-4]; sum+=A[i]; } return false; }" }, { "code": null, "e": 6733, "s": 6587, "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": 6769, "s": 6733, "text": " Login to access your submissions. " }, { "code": null, "e": 6779, "s": 6769, "text": "\nProblem\n" }, { "code": null, "e": 6789, "s": 6779, "text": "\nContest\n" }, { "code": null, "e": 6852, "s": 6789, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7000, "s": 6852, "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": 7208, "s": 7000, "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": 7314, "s": 7208, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
C Program For Removing Duplicates From A Sorted Linked List - GeeksforGeeks
13 Dec, 2021 Write a function that takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once. For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list to 11->21->43->60. Algorithm: Traverse the list from the head (or start) node. While traversing, compare each node with its next node. If the data of the next node is the same as the current node then delete the next node. Before we delete a node, we need to store the next pointer of the node Implementation: Functions other than removeDuplicates() are just to create a linked list and test removeDuplicates(). C // C Program to remove duplicates // from a sorted linked list #include<stdio.h>#include<stdlib.h> // Link list nodestruct Node{ int data; struct Node* next;}; // The function removes duplicates // from a sorted list void removeDuplicates(struct Node* head){ // Pointer to traverse the linked list struct Node* current = head; // Pointer to store the next pointer // of a node to be deleted struct Node* next_next; // Do nothing if the list is empty if (current == NULL) return; // Traverse the list till last node while (current->next != NULL) { // Compare current node with next node if (current->data == current->next->data) { // The sequence of steps is important next_next = current->next->next; free(current->next); current->next = next_next; } // This is tricky: only advance // if no deletion else { current = current->next; } }} // UTILITY FUNCTIONS // Function to insert a node at the// beginning of the linked list void push(struct Node** head_ref, int new_data){ // Allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // Put in the data new_node->data = new_data; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point to the // new node (*head_ref) = new_node;} // Function to print nodes in a given // linked list void printList(struct Node *node){ while (node!=NULL) { printf("%d ", node->data); node = node->next; }} // Driver codeint main(){ // Start with the empty list struct Node* head = NULL; /* Let us create a sorted linked list to test the functions. Created linked list will be 11->11->11->13->13->20 */ push(&head, 20); push(&head, 13); push(&head, 13); push(&head, 11); push(&head, 11); push(&head, 11); printf( "Linked list before duplicate removal "); printList(head); // Remove duplicates from linked list removeDuplicates(head); printf( "Linked list after duplicate removal "); printList(head); return 0;} Output: Linked list before duplicate removal 11 11 11 13 13 20 Linked list after duplicate removal 11 13 20 Time Complexity: O(n) where n is the number of nodes in the given linked list. Recursive Approach : C // C recursive Program to remove duplicates// from a sorted linked list#include<stdio.h>#include<stdlib.h> // Link list node struct Node{ int data; struct Node* next;}; // UTILITY FUNCTIONS // Function to insert a node at // the beginning of the linked list void push(struct Node** head_ref, int new_data){ // Allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // Put in the data new_node->data = new_data; // Link the old list off the // new node new_node->next = (*head_ref); // Move the head to point to the // new node (*head_ref) = new_node;} // Function to print nodes in a // given linked list void printList(struct Node *node){ while (node!=NULL) { printf("%d ", node->data); node = node->next; }} Node* deleteDuplicates(Node* head) { if (head == nullptr) return nullptr; if (head->next == nullptr) return head; if (head->data == head->next->data) { Node *tmp; // If find next element duplicate, // preserve the next pointer to be // deleted, skip it, and then delete // the stored one. Return head tmp = head->next; head->next = head->next->next; free(tmp); return deleteDuplicates(head); } else { // if doesn't find next element duplicate, leave head // and check from next element head->next = deleteDuplicates(head->next); return head; }} // Driver codeint main(){ // Start with the empty list struct Node* head = NULL; /* Let us create a sorted linked list to test the functions. Created linked list will be 11->11->11->13->13->20 */ push(&head, 20); push(&head, 13); push(&head, 13); push(&head, 11); push(&head, 11); push(&head, 11); printf( "Linked list before duplicate removal "); printList(head); // Remove duplicates from linked list head = deleteDuplicates(head); printf( "Linked list after duplicate removal "); printList(head); return 0;}// This code is contributed by Yogesh shukla Output: Linked list before duplicate removal 11 11 11 13 13 20 Linked list after duplicate removal 11 13 20 Please refer complete article on Remove duplicates from a sorted linked list for more details! Adobe Linked Lists Myntra Oracle Visa C Language C Programs Linked List Oracle Visa Adobe Myntra Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C Arrow operator -> in C/C++ with Examples 'this' 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": 23895, "s": 23867, "text": "\n13 Dec, 2021" }, { "code": null, "e": 24177, "s": 23895, "text": "Write a function that takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once. For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list to 11->21->43->60. " }, { "code": null, "e": 24453, "s": 24177, "text": "Algorithm: Traverse the list from the head (or start) node. While traversing, compare each node with its next node. If the data of the next node is the same as the current node then delete the next node. Before we delete a node, we need to store the next pointer of the node " }, { "code": null, "e": 24572, "s": 24453, "text": "Implementation: Functions other than removeDuplicates() are just to create a linked list and test removeDuplicates(). " }, { "code": null, "e": 24574, "s": 24572, "text": "C" }, { "code": "// C Program to remove duplicates // from a sorted linked list #include<stdio.h>#include<stdlib.h> // Link list nodestruct Node{ int data; struct Node* next;}; // The function removes duplicates // from a sorted list void removeDuplicates(struct Node* head){ // Pointer to traverse the linked list struct Node* current = head; // Pointer to store the next pointer // of a node to be deleted struct Node* next_next; // Do nothing if the list is empty if (current == NULL) return; // Traverse the list till last node while (current->next != NULL) { // Compare current node with next node if (current->data == current->next->data) { // The sequence of steps is important next_next = current->next->next; free(current->next); current->next = next_next; } // This is tricky: only advance // if no deletion else { current = current->next; } }} // UTILITY FUNCTIONS // Function to insert a node at the// beginning of the linked list void push(struct Node** head_ref, int new_data){ // Allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // Put in the data new_node->data = new_data; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point to the // new node (*head_ref) = new_node;} // Function to print nodes in a given // linked list void printList(struct Node *node){ while (node!=NULL) { printf(\"%d \", node->data); node = node->next; }} // Driver codeint main(){ // Start with the empty list struct Node* head = NULL; /* Let us create a sorted linked list to test the functions. Created linked list will be 11->11->11->13->13->20 */ push(&head, 20); push(&head, 13); push(&head, 13); push(&head, 11); push(&head, 11); push(&head, 11); printf( \"Linked list before duplicate removal \"); printList(head); // Remove duplicates from linked list removeDuplicates(head); printf( \"Linked list after duplicate removal \"); printList(head); return 0;}", "e": 26934, "s": 24574, "text": null }, { "code": null, "e": 26942, "s": 26934, "text": "Output:" }, { "code": null, "e": 27044, "s": 26942, "text": "Linked list before duplicate removal 11 11 11 13 13 20\nLinked list after duplicate removal 11 13 20" }, { "code": null, "e": 27123, "s": 27044, "text": "Time Complexity: O(n) where n is the number of nodes in the given linked list." }, { "code": null, "e": 27146, "s": 27123, "text": "Recursive Approach : " }, { "code": null, "e": 27148, "s": 27146, "text": "C" }, { "code": "// C recursive Program to remove duplicates// from a sorted linked list#include<stdio.h>#include<stdlib.h> // Link list node struct Node{ int data; struct Node* next;}; // UTILITY FUNCTIONS // Function to insert a node at // the beginning of the linked list void push(struct Node** head_ref, int new_data){ // Allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // Put in the data new_node->data = new_data; // Link the old list off the // new node new_node->next = (*head_ref); // Move the head to point to the // new node (*head_ref) = new_node;} // Function to print nodes in a // given linked list void printList(struct Node *node){ while (node!=NULL) { printf(\"%d \", node->data); node = node->next; }} Node* deleteDuplicates(Node* head) { if (head == nullptr) return nullptr; if (head->next == nullptr) return head; if (head->data == head->next->data) { Node *tmp; // If find next element duplicate, // preserve the next pointer to be // deleted, skip it, and then delete // the stored one. Return head tmp = head->next; head->next = head->next->next; free(tmp); return deleteDuplicates(head); } else { // if doesn't find next element duplicate, leave head // and check from next element head->next = deleteDuplicates(head->next); return head; }} // Driver codeint main(){ // Start with the empty list struct Node* head = NULL; /* Let us create a sorted linked list to test the functions. Created linked list will be 11->11->11->13->13->20 */ push(&head, 20); push(&head, 13); push(&head, 13); push(&head, 11); push(&head, 11); push(&head, 11); printf( \"Linked list before duplicate removal \"); printList(head); // Remove duplicates from linked list head = deleteDuplicates(head); printf( \"Linked list after duplicate removal \"); printList(head); return 0;}// This code is contributed by Yogesh shukla ", "e": 29418, "s": 27148, "text": null }, { "code": null, "e": 29426, "s": 29418, "text": "Output:" }, { "code": null, "e": 29528, "s": 29426, "text": "Linked list before duplicate removal 11 11 11 13 13 20\nLinked list after duplicate removal 11 13 20" }, { "code": null, "e": 29623, "s": 29528, "text": "Please refer complete article on Remove duplicates from a sorted linked list for more details!" }, { "code": null, "e": 29629, "s": 29623, "text": "Adobe" }, { "code": null, "e": 29642, "s": 29629, "text": "Linked Lists" }, { "code": null, "e": 29649, "s": 29642, "text": "Myntra" }, { "code": null, "e": 29656, "s": 29649, "text": "Oracle" }, { "code": null, "e": 29661, "s": 29656, "text": "Visa" }, { "code": null, "e": 29672, "s": 29661, "text": "C Language" }, { "code": null, "e": 29683, "s": 29672, "text": "C Programs" }, { "code": null, "e": 29695, "s": 29683, "text": "Linked List" }, { "code": null, "e": 29702, "s": 29695, "text": "Oracle" }, { "code": null, "e": 29707, "s": 29702, "text": "Visa" }, { "code": null, "e": 29713, "s": 29707, "text": "Adobe" }, { "code": null, "e": 29720, "s": 29713, "text": "Myntra" }, { "code": null, "e": 29732, "s": 29720, "text": "Linked List" }, { "code": null, "e": 29830, "s": 29732, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29839, "s": 29830, "text": "Comments" }, { "code": null, "e": 29852, "s": 29839, "text": "Old Comments" }, { "code": null, "e": 29890, "s": 29852, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 29916, "s": 29890, "text": "Exception Handling in C++" }, { "code": null, "e": 29936, "s": 29916, "text": "Multithreading in C" }, { "code": null, "e": 29977, "s": 29936, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 29999, "s": 29977, "text": "'this' pointer in C++" }, { "code": null, "e": 30012, "s": 29999, "text": "Strings in C" }, { "code": null, "e": 30053, "s": 30012, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 30094, "s": 30053, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 30132, "s": 30094, "text": "UDP Server-Client implementation in C" } ]
How to Build a DCGAN with PyTorch | by Conor Lazarou | Towards Data Science
In this tutorial, we’ll be building a simple DCGAN in PyTorch and training it to generate handwritten digits. As part of this tutorial we’ll be discussing the PyTorch DataLoader and how to use it to feed real image data into a PyTorch neural network for training. PyTorch is the focus of this tutorial, so I’ll be assuming you’re familiar with how GANs work. Python 3.7 or higher. Any lower and you’ll have to refactor the f-strings.PyTorch 1.5 Not sure how to install it? This might help.Matplotlib 3.1 or higherTwenty-two minutes or so of your time. Python 3.7 or higher. Any lower and you’ll have to refactor the f-strings. PyTorch 1.5 Not sure how to install it? This might help. Matplotlib 3.1 or higher Twenty-two minutes or so of your time. It’s not required but I recommended reading my vanilla GAN tutorial first; it explains a couple things that this tutorial takes for granted. I also recommend that you do this tutorial on a computer with a CUDA GPU, or keep a hefty book of Sudokus at the ready. Create a function G: Z → X where Z~N16(0, 1) and X~MNIST. That is to say, train a GAN that takes 16-dimensional random noise and produces images that look like real samples from the MNIST dataset. ...let’s do a little housekeeping. If you haven’t already, install the required versions of Python and the above libraries. Then, create your project directory. I called mine DCGAN. In that directory, make a directory called data. Then, navigate to this GitHub repo and download mnist_png.tar.gz. This compressed file contains the MNIST dataset as 70000 individual png files. Of course, we could be using PyTorch’s built-in MNIST dataset, but then you wouldn’t learn how to actually load image data for training. Decompress the file and put the mnist_png directory into your data directory. Create a file called dcgan_mnist.py, and put it in your DCGAN directory. You project directories should look like this: Finally, add the following to your dcgan_mnist.py script: import osimport torchfrom torch import nnfrom torch import optimimport torchvision as tvfrom torchvision.datasets import ImageFolderfrom torch.utils.data import DataLoader Alright, now we’re ready to start. Add the following to your dcgan_mnist.py script: The Generator inherits nn.Module, which is the base class for a PyTorch neural network. The Generator has three methods: The constructor, which stores the instance variables and calls _init_layers. There’s not much to say here. This method instantiates the PyTorch modules (or “layers”, as they’re called in other frameworks). These include: A linear (“fully-connected”) module, for mapping the latent space to a 7×7×256=12544-dimensional space. As we will see in the forward method, this 12544-length tensor is reshaped to a (256, 7, 7) “image” tensor (channels×height×width). In PyTorch, unlike TensorFlow, channels come before the spatial dimensions. A 1-dimensional batch normalization module, if specified. A leaky ReLU module. A 2-dimensional convolutional layer. Two 2-dimensional transposed convolutional layers; these are used for upscaling the image. Notice how the out-channels of one convolutional layer are the in-channels of the next. Two 2-dimensional batch normalization layers, if specified. A Tanh module as the output activation. We’ll be rescaling our images to the range [-1, 1], so our generator output activation should reflect that. These could have been instantiated in the __init__ method, but I like to keep the module instantiation separate from the constructor. It’s trivial for a model this simple, but helps keep the code simple as the model grows in complexity. This is the method our Generator uses to generate samples from random noise. The input tensor is passed to the first module, the output of that is passed to the next module, the output of that is passed to the next module, etc. It’s fairly straightforward, but I’d like to draw your attention to two interesting features: Note the line intermediate = intermediate.view((-1, 256, 7, 7)). Unlike Keras, PyTorch doesn’t use an explicit “reshape” module; instead, we manually reshape the Tensor using the PyTorch operation “view”. Other simple PyTorch operations can be applied during the forward pass as well, like multiplying a tensor by two, and PyTorch won’t bat an eye.Notice how there are if statements in the forward method. PyTorch uses a define-by-run strategy, which means that the computational graph is built on-the-fly during the forward pass. This makes PyTorch extremely flexible; there’s nothing stopping you from adding loops to your forward pass, or randomly selecting one of several modules to use. Note the line intermediate = intermediate.view((-1, 256, 7, 7)). Unlike Keras, PyTorch doesn’t use an explicit “reshape” module; instead, we manually reshape the Tensor using the PyTorch operation “view”. Other simple PyTorch operations can be applied during the forward pass as well, like multiplying a tensor by two, and PyTorch won’t bat an eye. Notice how there are if statements in the forward method. PyTorch uses a define-by-run strategy, which means that the computational graph is built on-the-fly during the forward pass. This makes PyTorch extremely flexible; there’s nothing stopping you from adding loops to your forward pass, or randomly selecting one of several modules to use. Add the following to your dcgan_mnist.py script: I won’t go into too much detail about this one since it’s very similar to the Generator but backwards. Take a good read through it and make sure you understand what it’s doing. Add the following to your dcgan_mnist.py script: Let’s step through the constructor line-by-line: self.generator = Generator(latent_dim).to(device)self.discriminator = Discriminator().to(device) The first two (non-docstring) lines of the constructor instantiate the Generator and the Discriminator, move them to the specified device, and store them as instance variables. The device is typically “cpu”, or “cuda” if you want to use a gpu. self.noise_fn = noise_fn Next, we store noise_fn as an instance variable; noise_fn is a function that takes an integer num as input and returns num latent vectors as a PyTorch tensor as output with shape (num, latent_dim). This PyTorch tensor must be on the specified device. self.dataloader = dataloader We store dataloader, a torch.utils.data.DataLoader object, as an instance variable; more on this later. self.batch_size = batch_sizeself.device = device Store the batch size and device as instance variables. Simple. self.criterion = nn.BCELoss()self.optim_d = optim.Adam(self.discriminator.parameters(), lr=lr_d, betas=(0.5, 0.999))self.optim_g = optim.Adam(self.generator.parameters(), lr=lr_g, betas=(0.5, 0.999)) Set the loss function to binary cross-entropy, and instantiate Adam optimizers for the generator and the discriminator. PyTorch optimizers need to know what they’re optimizing. For the discriminator, this means all trainable parameters within the Discriminator network. Because our Discriminator class inherits from nn.Module, it has the parameters() method which returns all the trainable parameters in all its instance variables that are also PyTorch Modules. The same goes for the Generator. self.target_ones = torch.ones((batch_size, 1), device=device)self.target_zeros = torch.zeros((batch_size, 1), device=device) Targets for training, set to the specified device. Remember, the Discriminator is trying to classify real samples as 1 and generated samples as 0, while the Generator is trying to get the the Discriminator to misclassify generated samples as 1. We define and store them here so we don’t have to remake them with each training step. A helper method for generating samples. Note that the no_grad context manager is used, which tells PyTorch not to keep track of gradients because this method is not used for training the network. Also note that, regardless of the specified device, the returned tensor is set to cpu, which is necessary for further use such as displaying samples or saving them to disk. This method performs one training step of the generator and returns the loss as a float. Let’s step through it: self.generator.zero_grad() Clear the generator’s gradient. This is necessary, since PyTorch automatically keeps track of gradients and the computational network. We don’t want one training step influencing the next. latent_vec = self.noise_fn(self.batch_size)generated = self.generator(latent_vec)classifications = self.discriminator(generated)loss = self.criterion(classifications, self.target_ones) Get a batch of latent vectors, use them to generate samples, discriminate how realistic each samples is, then calculate the loss using the binary cross-entropy criterion. Note that by chaining these networks together we are creating a single computation graph starting from the latent vector, including the Generator and Discriminator networks, and ending at the loss. loss.backward()self.optim_g.step() One of the main benefits of PyTorch is that it automatically keeps track of the computational graph and its gradients. By calling the backward method on the loss, PyTorch applies backpropagation and calculates the gradients of the loss with respect to each parameter in the computation graph. By then calling the Generator’s optimizer’s step method, the Generator’s parameters (and only the Generator’s parameters) are nudged slightly in the negative direction of their gradient. return loss.item() Finally, we return the loss. It’s important to use the item method, so that we’re returning a float instead of a PyTorch tensor. If we had instead returned the tensor, the Python garbage collector wouldn’t be able to clean up the underlying computational graph, and we would quickly run out of memory. This method is very similar to train_step_generator, but with two notable differences. First: with torch.no_grad(): fake_samples = self.generator(latent_vec) The context manager no_grad is used here to to tell PyTorch not to worry about keeping track of gradients. It’s not necessary, but cuts down on unnecessary computation. Second: loss = (loss_real + loss_fake) / 2 This line is really cool. loss_real is the Discriminator’s loss for the real samples (and attached to it is its computational graph), and loss_fake is the loss (and graph) for the fake samples. PyTorch is able to combine these into one computational graph using the + operator. We then apply backpropagation and parameter updates to that combined computational graph. If you don’t think that’s awesomely simple, try rewriting this in another framework. This function trains the generator and discriminator for one epoch, which is one pass over the entire dataset. We’ll come back to this after a brief detour. Add the following code to your script: This function builds, trains, and showcases the GAN. import matplotlib.pyplot as pltfrom time import timebatch_size = 32epochs = 100latent_dim = 16 Import pyplot (for visualizing the generated digits) and time (for timing the training). Set the training batch size to 32, the number of epochs to 100, and the latent dimension to 16. device = torch.device("cuda" if torch.cuda.is_available() else "cpu") This line checks if a cuda device is available. If it is, device is assigned that device; otherwise, device is assigned the cpu. transform = tv.transforms.Compose([ tv.transforms.Grayscale(num_output_channels=1), tv.transforms.ToTensor(), tv.transforms.Normalize((0.5,), (0.5,)) ]) This composite transform is used by the dataloader to pre-process images. The MNIST dataset that we downloaded earlier are .png files; when PyTorch loads them from disk, they have to be processed so that our neural network can use them properly. The transforms are, in order: Grayscale(num_output_channels=1): Convert the image to greyscale. When loaded, the MNIST digits are in RGB format with three channels. Greyscale reduces these three to one. ToTensor(): Convert the image to a PyTorch Tensor, with dimensions channels × height × width. This also rescales the pixel values, from integers between 0 and 255 to floats between 0.0 and 1.0. Normalize((0.5,), (0.5,)): Scale and translate the pixel values from the range [0.0, 1.0] to [-1.0, 1.0]. The first argument is μ and the second argument is σ, and the function applied to each pixel is: The reason that μ and σ are one-tuples is that this transform is applied per-channel. The equivalent transformation to an RGB image would be Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) dataset = ImageFolder( root=os.path.join("data", "mnist_png", "training"), transform=transform ) Here we create the dataset by specifying its root and the transformations to apply. This is used to create the DataLoader: dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=2 ) The DataLoader is an object that... well, it loads data from a dataset. Here we specify our batch size, tell the dataloader to shuffle the dataset between epochs, and use multiprocessing with two worker processes (if you’re using Windows and this causes issues, set num_workers to 0). You can iterate through this dataloader, and with each iteration it will return a tuple containing: a PyTorch tensor of shape (32, 1, 28, 28) corresponding to a batch (32 samples) of greyscale (1 channel) MNIST images (28×28 pixels).a PyTorch tensor of shape (32,) of digits 0 through 9, corresponding to the label (digit) of that image. These class labels were taken from the directory structure, as all the zeros were in directory 0, all the ones in 1, etc. a PyTorch tensor of shape (32, 1, 28, 28) corresponding to a batch (32 samples) of greyscale (1 channel) MNIST images (28×28 pixels). a PyTorch tensor of shape (32,) of digits 0 through 9, corresponding to the label (digit) of that image. These class labels were taken from the directory structure, as all the zeros were in directory 0, all the ones in 1, etc. noise_fn = lambda x: torch.rand((x, latent_dim), device=device) A function for generating random, normally-distributed noise. gan = DCGAN(latent_dim, noise_fn, dataloader, device=device)start = time()for i in range(10): print(f"Epoch {i+1}; Elapsed time = {int(time() - start)}s") gan.train_epoch() Build and train the GAN. Let’s revisit this one, now that we’ve discussed what a DataLoader is. The method is pretty self-explanatory, albeit verbose, but I’d like to focus on two lines: for batch, (real_samples, _) in enumerate(self.dataloader): real_samples = real_samples.to(self.device) Here, we iterate through the dataloader. We wrap the dataloader in an enumerator so that we can keep track of the batch number, but as you can see the dataloader does indeed return a tuple as promised. We assign the batch of images tensor to real_samples, and ignore the labels since we don’t need them. Then, in the loop, we move real_samples to the specified device. It’s important that the input to the model and the model itself are on the same device; don’t worry if you forget to do this, PyTorch will certainly let you know! Also, don’t worry about the dataloader “running out”. Once we’ve iterated through the whole dataset, the loop will end, but if we try to iterate through it again it’ll start back at the beginning (shuffling the images first, because we specified that when we made the dataloader). If you copy and pasted correctly, running the script should show you training stats for a couple of minutes followed by some generated digits. Hopefully, it looks something like this: If they look terrible and your loss exploded, try running it again (GANs are notoriously unstable). If it still doesn’t work, drop a comment down below and we’ll see if we can’t debug it. Just for fun, I modified the script to see what the Generator was capable of after every 10 training steps. Here were the results. I think that’s pretty good for only 1000 steps. Here’s the loss over those training steps, split into 10 step “epochs”. The DCGAN described in this tutorial is obviously very simple, but it should be enough to get you started implementing more complex GANs in PyTorch. Can you modify this script to make a Conditional GAN before I make a tutorial about it? The full script is available here. All images not cited are my own. Feel free to use them, but please cite this article ❤
[ { "code": null, "e": 531, "s": 172, "text": "In this tutorial, we’ll be building a simple DCGAN in PyTorch and training it to generate handwritten digits. As part of this tutorial we’ll be discussing the PyTorch DataLoader and how to use it to feed real image data into a PyTorch neural network for training. PyTorch is the focus of this tutorial, so I’ll be assuming you’re familiar with how GANs work." }, { "code": null, "e": 724, "s": 531, "text": "Python 3.7 or higher. Any lower and you’ll have to refactor the f-strings.PyTorch 1.5 Not sure how to install it? This might help.Matplotlib 3.1 or higherTwenty-two minutes or so of your time." }, { "code": null, "e": 799, "s": 724, "text": "Python 3.7 or higher. Any lower and you’ll have to refactor the f-strings." }, { "code": null, "e": 856, "s": 799, "text": "PyTorch 1.5 Not sure how to install it? This might help." }, { "code": null, "e": 881, "s": 856, "text": "Matplotlib 3.1 or higher" }, { "code": null, "e": 920, "s": 881, "text": "Twenty-two minutes or so of your time." }, { "code": null, "e": 1181, "s": 920, "text": "It’s not required but I recommended reading my vanilla GAN tutorial first; it explains a couple things that this tutorial takes for granted. I also recommend that you do this tutorial on a computer with a CUDA GPU, or keep a hefty book of Sudokus at the ready." }, { "code": null, "e": 1239, "s": 1181, "text": "Create a function G: Z → X where Z~N16(0, 1) and X~MNIST." }, { "code": null, "e": 1378, "s": 1239, "text": "That is to say, train a GAN that takes 16-dimensional random noise and produces images that look like real samples from the MNIST dataset." }, { "code": null, "e": 2089, "s": 1378, "text": "...let’s do a little housekeeping. If you haven’t already, install the required versions of Python and the above libraries. Then, create your project directory. I called mine DCGAN. In that directory, make a directory called data. Then, navigate to this GitHub repo and download mnist_png.tar.gz. This compressed file contains the MNIST dataset as 70000 individual png files. Of course, we could be using PyTorch’s built-in MNIST dataset, but then you wouldn’t learn how to actually load image data for training. Decompress the file and put the mnist_png directory into your data directory. Create a file called dcgan_mnist.py, and put it in your DCGAN directory. You project directories should look like this:" }, { "code": null, "e": 2147, "s": 2089, "text": "Finally, add the following to your dcgan_mnist.py script:" }, { "code": null, "e": 2319, "s": 2147, "text": "import osimport torchfrom torch import nnfrom torch import optimimport torchvision as tvfrom torchvision.datasets import ImageFolderfrom torch.utils.data import DataLoader" }, { "code": null, "e": 2354, "s": 2319, "text": "Alright, now we’re ready to start." }, { "code": null, "e": 2403, "s": 2354, "text": "Add the following to your dcgan_mnist.py script:" }, { "code": null, "e": 2524, "s": 2403, "text": "The Generator inherits nn.Module, which is the base class for a PyTorch neural network. The Generator has three methods:" }, { "code": null, "e": 2631, "s": 2524, "text": "The constructor, which stores the instance variables and calls _init_layers. There’s not much to say here." }, { "code": null, "e": 2745, "s": 2631, "text": "This method instantiates the PyTorch modules (or “layers”, as they’re called in other frameworks). These include:" }, { "code": null, "e": 3057, "s": 2745, "text": "A linear (“fully-connected”) module, for mapping the latent space to a 7×7×256=12544-dimensional space. As we will see in the forward method, this 12544-length tensor is reshaped to a (256, 7, 7) “image” tensor (channels×height×width). In PyTorch, unlike TensorFlow, channels come before the spatial dimensions." }, { "code": null, "e": 3115, "s": 3057, "text": "A 1-dimensional batch normalization module, if specified." }, { "code": null, "e": 3136, "s": 3115, "text": "A leaky ReLU module." }, { "code": null, "e": 3173, "s": 3136, "text": "A 2-dimensional convolutional layer." }, { "code": null, "e": 3352, "s": 3173, "text": "Two 2-dimensional transposed convolutional layers; these are used for upscaling the image. Notice how the out-channels of one convolutional layer are the in-channels of the next." }, { "code": null, "e": 3412, "s": 3352, "text": "Two 2-dimensional batch normalization layers, if specified." }, { "code": null, "e": 3560, "s": 3412, "text": "A Tanh module as the output activation. We’ll be rescaling our images to the range [-1, 1], so our generator output activation should reflect that." }, { "code": null, "e": 3797, "s": 3560, "text": "These could have been instantiated in the __init__ method, but I like to keep the module instantiation separate from the constructor. It’s trivial for a model this simple, but helps keep the code simple as the model grows in complexity." }, { "code": null, "e": 4119, "s": 3797, "text": "This is the method our Generator uses to generate samples from random noise. The input tensor is passed to the first module, the output of that is passed to the next module, the output of that is passed to the next module, etc. It’s fairly straightforward, but I’d like to draw your attention to two interesting features:" }, { "code": null, "e": 4811, "s": 4119, "text": "Note the line intermediate = intermediate.view((-1, 256, 7, 7)). Unlike Keras, PyTorch doesn’t use an explicit “reshape” module; instead, we manually reshape the Tensor using the PyTorch operation “view”. Other simple PyTorch operations can be applied during the forward pass as well, like multiplying a tensor by two, and PyTorch won’t bat an eye.Notice how there are if statements in the forward method. PyTorch uses a define-by-run strategy, which means that the computational graph is built on-the-fly during the forward pass. This makes PyTorch extremely flexible; there’s nothing stopping you from adding loops to your forward pass, or randomly selecting one of several modules to use." }, { "code": null, "e": 5160, "s": 4811, "text": "Note the line intermediate = intermediate.view((-1, 256, 7, 7)). Unlike Keras, PyTorch doesn’t use an explicit “reshape” module; instead, we manually reshape the Tensor using the PyTorch operation “view”. Other simple PyTorch operations can be applied during the forward pass as well, like multiplying a tensor by two, and PyTorch won’t bat an eye." }, { "code": null, "e": 5504, "s": 5160, "text": "Notice how there are if statements in the forward method. PyTorch uses a define-by-run strategy, which means that the computational graph is built on-the-fly during the forward pass. This makes PyTorch extremely flexible; there’s nothing stopping you from adding loops to your forward pass, or randomly selecting one of several modules to use." }, { "code": null, "e": 5553, "s": 5504, "text": "Add the following to your dcgan_mnist.py script:" }, { "code": null, "e": 5730, "s": 5553, "text": "I won’t go into too much detail about this one since it’s very similar to the Generator but backwards. Take a good read through it and make sure you understand what it’s doing." }, { "code": null, "e": 5779, "s": 5730, "text": "Add the following to your dcgan_mnist.py script:" }, { "code": null, "e": 5828, "s": 5779, "text": "Let’s step through the constructor line-by-line:" }, { "code": null, "e": 5925, "s": 5828, "text": "self.generator = Generator(latent_dim).to(device)self.discriminator = Discriminator().to(device)" }, { "code": null, "e": 6169, "s": 5925, "text": "The first two (non-docstring) lines of the constructor instantiate the Generator and the Discriminator, move them to the specified device, and store them as instance variables. The device is typically “cpu”, or “cuda” if you want to use a gpu." }, { "code": null, "e": 6194, "s": 6169, "text": "self.noise_fn = noise_fn" }, { "code": null, "e": 6445, "s": 6194, "text": "Next, we store noise_fn as an instance variable; noise_fn is a function that takes an integer num as input and returns num latent vectors as a PyTorch tensor as output with shape (num, latent_dim). This PyTorch tensor must be on the specified device." }, { "code": null, "e": 6474, "s": 6445, "text": "self.dataloader = dataloader" }, { "code": null, "e": 6578, "s": 6474, "text": "We store dataloader, a torch.utils.data.DataLoader object, as an instance variable; more on this later." }, { "code": null, "e": 6627, "s": 6578, "text": "self.batch_size = batch_sizeself.device = device" }, { "code": null, "e": 6690, "s": 6627, "text": "Store the batch size and device as instance variables. Simple." }, { "code": null, "e": 6890, "s": 6690, "text": "self.criterion = nn.BCELoss()self.optim_d = optim.Adam(self.discriminator.parameters(), lr=lr_d, betas=(0.5, 0.999))self.optim_g = optim.Adam(self.generator.parameters(), lr=lr_g, betas=(0.5, 0.999))" }, { "code": null, "e": 7385, "s": 6890, "text": "Set the loss function to binary cross-entropy, and instantiate Adam optimizers for the generator and the discriminator. PyTorch optimizers need to know what they’re optimizing. For the discriminator, this means all trainable parameters within the Discriminator network. Because our Discriminator class inherits from nn.Module, it has the parameters() method which returns all the trainable parameters in all its instance variables that are also PyTorch Modules. The same goes for the Generator." }, { "code": null, "e": 7510, "s": 7385, "text": "self.target_ones = torch.ones((batch_size, 1), device=device)self.target_zeros = torch.zeros((batch_size, 1), device=device)" }, { "code": null, "e": 7842, "s": 7510, "text": "Targets for training, set to the specified device. Remember, the Discriminator is trying to classify real samples as 1 and generated samples as 0, while the Generator is trying to get the the Discriminator to misclassify generated samples as 1. We define and store them here so we don’t have to remake them with each training step." }, { "code": null, "e": 8211, "s": 7842, "text": "A helper method for generating samples. Note that the no_grad context manager is used, which tells PyTorch not to keep track of gradients because this method is not used for training the network. Also note that, regardless of the specified device, the returned tensor is set to cpu, which is necessary for further use such as displaying samples or saving them to disk." }, { "code": null, "e": 8323, "s": 8211, "text": "This method performs one training step of the generator and returns the loss as a float. Let’s step through it:" }, { "code": null, "e": 8350, "s": 8323, "text": "self.generator.zero_grad()" }, { "code": null, "e": 8539, "s": 8350, "text": "Clear the generator’s gradient. This is necessary, since PyTorch automatically keeps track of gradients and the computational network. We don’t want one training step influencing the next." }, { "code": null, "e": 8724, "s": 8539, "text": "latent_vec = self.noise_fn(self.batch_size)generated = self.generator(latent_vec)classifications = self.discriminator(generated)loss = self.criterion(classifications, self.target_ones)" }, { "code": null, "e": 9093, "s": 8724, "text": "Get a batch of latent vectors, use them to generate samples, discriminate how realistic each samples is, then calculate the loss using the binary cross-entropy criterion. Note that by chaining these networks together we are creating a single computation graph starting from the latent vector, including the Generator and Discriminator networks, and ending at the loss." }, { "code": null, "e": 9128, "s": 9093, "text": "loss.backward()self.optim_g.step()" }, { "code": null, "e": 9608, "s": 9128, "text": "One of the main benefits of PyTorch is that it automatically keeps track of the computational graph and its gradients. By calling the backward method on the loss, PyTorch applies backpropagation and calculates the gradients of the loss with respect to each parameter in the computation graph. By then calling the Generator’s optimizer’s step method, the Generator’s parameters (and only the Generator’s parameters) are nudged slightly in the negative direction of their gradient." }, { "code": null, "e": 9627, "s": 9608, "text": "return loss.item()" }, { "code": null, "e": 9929, "s": 9627, "text": "Finally, we return the loss. It’s important to use the item method, so that we’re returning a float instead of a PyTorch tensor. If we had instead returned the tensor, the Python garbage collector wouldn’t be able to clean up the underlying computational graph, and we would quickly run out of memory." }, { "code": null, "e": 10023, "s": 9929, "text": "This method is very similar to train_step_generator, but with two notable differences. First:" }, { "code": null, "e": 10090, "s": 10023, "text": "with torch.no_grad(): fake_samples = self.generator(latent_vec)" }, { "code": null, "e": 10267, "s": 10090, "text": "The context manager no_grad is used here to to tell PyTorch not to worry about keeping track of gradients. It’s not necessary, but cuts down on unnecessary computation. Second:" }, { "code": null, "e": 10302, "s": 10267, "text": "loss = (loss_real + loss_fake) / 2" }, { "code": null, "e": 10755, "s": 10302, "text": "This line is really cool. loss_real is the Discriminator’s loss for the real samples (and attached to it is its computational graph), and loss_fake is the loss (and graph) for the fake samples. PyTorch is able to combine these into one computational graph using the + operator. We then apply backpropagation and parameter updates to that combined computational graph. If you don’t think that’s awesomely simple, try rewriting this in another framework." }, { "code": null, "e": 10912, "s": 10755, "text": "This function trains the generator and discriminator for one epoch, which is one pass over the entire dataset. We’ll come back to this after a brief detour." }, { "code": null, "e": 10951, "s": 10912, "text": "Add the following code to your script:" }, { "code": null, "e": 11004, "s": 10951, "text": "This function builds, trains, and showcases the GAN." }, { "code": null, "e": 11099, "s": 11004, "text": "import matplotlib.pyplot as pltfrom time import timebatch_size = 32epochs = 100latent_dim = 16" }, { "code": null, "e": 11284, "s": 11099, "text": "Import pyplot (for visualizing the generated digits) and time (for timing the training). Set the training batch size to 32, the number of epochs to 100, and the latent dimension to 16." }, { "code": null, "e": 11354, "s": 11284, "text": "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")" }, { "code": null, "e": 11483, "s": 11354, "text": "This line checks if a cuda device is available. If it is, device is assigned that device; otherwise, device is assigned the cpu." }, { "code": null, "e": 11680, "s": 11483, "text": "transform = tv.transforms.Compose([ tv.transforms.Grayscale(num_output_channels=1), tv.transforms.ToTensor(), tv.transforms.Normalize((0.5,), (0.5,)) ])" }, { "code": null, "e": 11956, "s": 11680, "text": "This composite transform is used by the dataloader to pre-process images. The MNIST dataset that we downloaded earlier are .png files; when PyTorch loads them from disk, they have to be processed so that our neural network can use them properly. The transforms are, in order:" }, { "code": null, "e": 12129, "s": 11956, "text": "Grayscale(num_output_channels=1): Convert the image to greyscale. When loaded, the MNIST digits are in RGB format with three channels. Greyscale reduces these three to one." }, { "code": null, "e": 12323, "s": 12129, "text": "ToTensor(): Convert the image to a PyTorch Tensor, with dimensions channels × height × width. This also rescales the pixel values, from integers between 0 and 255 to floats between 0.0 and 1.0." }, { "code": null, "e": 12526, "s": 12323, "text": "Normalize((0.5,), (0.5,)): Scale and translate the pixel values from the range [0.0, 1.0] to [-1.0, 1.0]. The first argument is μ and the second argument is σ, and the function applied to each pixel is:" }, { "code": null, "e": 12711, "s": 12526, "text": "The reason that μ and σ are one-tuples is that this transform is applied per-channel. The equivalent transformation to an RGB image would be Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))" }, { "code": null, "e": 12841, "s": 12711, "text": "dataset = ImageFolder( root=os.path.join(\"data\", \"mnist_png\", \"training\"), transform=transform )" }, { "code": null, "e": 12964, "s": 12841, "text": "Here we create the dataset by specifying its root and the transformations to apply. This is used to create the DataLoader:" }, { "code": null, "e": 13094, "s": 12964, "text": "dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=2 )" }, { "code": null, "e": 13479, "s": 13094, "text": "The DataLoader is an object that... well, it loads data from a dataset. Here we specify our batch size, tell the dataloader to shuffle the dataset between epochs, and use multiprocessing with two worker processes (if you’re using Windows and this causes issues, set num_workers to 0). You can iterate through this dataloader, and with each iteration it will return a tuple containing:" }, { "code": null, "e": 13839, "s": 13479, "text": "a PyTorch tensor of shape (32, 1, 28, 28) corresponding to a batch (32 samples) of greyscale (1 channel) MNIST images (28×28 pixels).a PyTorch tensor of shape (32,) of digits 0 through 9, corresponding to the label (digit) of that image. These class labels were taken from the directory structure, as all the zeros were in directory 0, all the ones in 1, etc." }, { "code": null, "e": 13973, "s": 13839, "text": "a PyTorch tensor of shape (32, 1, 28, 28) corresponding to a batch (32 samples) of greyscale (1 channel) MNIST images (28×28 pixels)." }, { "code": null, "e": 14200, "s": 13973, "text": "a PyTorch tensor of shape (32,) of digits 0 through 9, corresponding to the label (digit) of that image. These class labels were taken from the directory structure, as all the zeros were in directory 0, all the ones in 1, etc." }, { "code": null, "e": 14264, "s": 14200, "text": "noise_fn = lambda x: torch.rand((x, latent_dim), device=device)" }, { "code": null, "e": 14326, "s": 14264, "text": "A function for generating random, normally-distributed noise." }, { "code": null, "e": 14505, "s": 14326, "text": "gan = DCGAN(latent_dim, noise_fn, dataloader, device=device)start = time()for i in range(10): print(f\"Epoch {i+1}; Elapsed time = {int(time() - start)}s\") gan.train_epoch()" }, { "code": null, "e": 14530, "s": 14505, "text": "Build and train the GAN." }, { "code": null, "e": 14692, "s": 14530, "text": "Let’s revisit this one, now that we’ve discussed what a DataLoader is. The method is pretty self-explanatory, albeit verbose, but I’d like to focus on two lines:" }, { "code": null, "e": 14798, "s": 14692, "text": "for batch, (real_samples, _) in enumerate(self.dataloader): real_samples = real_samples.to(self.device)" }, { "code": null, "e": 15611, "s": 14798, "text": "Here, we iterate through the dataloader. We wrap the dataloader in an enumerator so that we can keep track of the batch number, but as you can see the dataloader does indeed return a tuple as promised. We assign the batch of images tensor to real_samples, and ignore the labels since we don’t need them. Then, in the loop, we move real_samples to the specified device. It’s important that the input to the model and the model itself are on the same device; don’t worry if you forget to do this, PyTorch will certainly let you know! Also, don’t worry about the dataloader “running out”. Once we’ve iterated through the whole dataset, the loop will end, but if we try to iterate through it again it’ll start back at the beginning (shuffling the images first, because we specified that when we made the dataloader)." }, { "code": null, "e": 15795, "s": 15611, "text": "If you copy and pasted correctly, running the script should show you training stats for a couple of minutes followed by some generated digits. Hopefully, it looks something like this:" }, { "code": null, "e": 15983, "s": 15795, "text": "If they look terrible and your loss exploded, try running it again (GANs are notoriously unstable). If it still doesn’t work, drop a comment down below and we’ll see if we can’t debug it." }, { "code": null, "e": 16114, "s": 15983, "text": "Just for fun, I modified the script to see what the Generator was capable of after every 10 training steps. Here were the results." }, { "code": null, "e": 16234, "s": 16114, "text": "I think that’s pretty good for only 1000 steps. Here’s the loss over those training steps, split into 10 step “epochs”." }, { "code": null, "e": 16383, "s": 16234, "text": "The DCGAN described in this tutorial is obviously very simple, but it should be enough to get you started implementing more complex GANs in PyTorch." }, { "code": null, "e": 16471, "s": 16383, "text": "Can you modify this script to make a Conditional GAN before I make a tutorial about it?" }, { "code": null, "e": 16506, "s": 16471, "text": "The full script is available here." } ]
Batch Script - IPCONFIG
This batch command displays Windows IP Configuration. Shows configuration by connection and the name of that connection. ipconfig @echo off ipconfig The above command will display the Windows IP configuration on the current machine. Following is an example of the output. Windows IP Configuration Wireless LAN adapter Local Area Connection* 11: Media State . . . . . . . . . . . : Media disconnected Connection-specific DNS Suffix . : Ethernet adapter Ethernet: Media State . . . . . . . . . . . : Media disconnected Connection-specific DNS Suffix . : Wireless LAN adapter Wi-Fi: Media State . . . . . . . . . . . : Media disconnected Connection-specific DNS Suffix . : Tunnel adapter Teredo Tunneling Pseudo-Interface: Media State . . . . . . . . . . . : Media disconnected Connection-specific DNS Suffix . : Print Add Notes Bookmark this page
[ { "code": null, "e": 2290, "s": 2169, "text": "This batch command displays Windows IP Configuration. Shows configuration by connection and the name of that connection." }, { "code": null, "e": 2300, "s": 2290, "text": "ipconfig\n" }, { "code": null, "e": 2320, "s": 2300, "text": "@echo off \nipconfig" }, { "code": null, "e": 2443, "s": 2320, "text": "The above command will display the Windows IP configuration on the current machine. Following is an example of the output." }, { "code": null, "e": 3013, "s": 2443, "text": "Windows IP Configuration\n\nWireless LAN adapter Local Area Connection* 11:\n Media State . . . . . . . . . . . : Media disconnected\n Connection-specific DNS Suffix . :\n\t\nEthernet adapter Ethernet:\n Media State . . . . . . . . . . . : Media disconnected\n Connection-specific DNS Suffix . :\n\t\nWireless LAN adapter Wi-Fi:\n Media State . . . . . . . . . . . : Media disconnected\n Connection-specific DNS Suffix . :\n \nTunnel adapter Teredo Tunneling Pseudo-Interface:\n Media State . . . . . . . . . . . : Media disconnected\n Connection-specific DNS Suffix . :\n" }, { "code": null, "e": 3020, "s": 3013, "text": " Print" }, { "code": null, "e": 3031, "s": 3020, "text": " Add Notes" } ]
How to add date and time picker using only one tag in HTML ? - GeeksforGeeks
07 Jan, 2022 In this article, we will discuss the overview of the datetime tag in HTML and mainly will focus on the example of datetime picker tag. We can add date and time picker in only one tag without using the two different tags. Let’s discuss it one by one. Syntax: For selecting a date we use the date tag in HTML. Date of Birth: <input type="date"> And for selecting a time we use the time tag in HTML. Enter Time: <input type="time"> But if we want to take the date and time at the same time then these two separate lines of code will take more time than the datetime-local tag. So to reduce the time required for coding we can use only one line of code. Let’s see the syntax and example for it: Date with Time: <input type="datetime-local"> When we click on the input box of date and time it will show a calendar and time, and it will show the current date, month, and time by default, then we have to select the date and time or we can also type it in the input box. Example: HTML <!DOCTYPE html><html> <head> <title>Page Title</title></head> <body> <h2>Welcome To GFG</h2> Select date and time: <input type="datetime-local" /></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Questions HTML-Tags HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments REST API (Introduction) Design a web page using HTML and CSS Form validation using jQuery How to place text on image using HTML and CSS? How to auto-resize an image to fit a div container using CSS? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript
[ { "code": null, "e": 24503, "s": 24475, "text": "\n07 Jan, 2022" }, { "code": null, "e": 24754, "s": 24503, "text": "In this article, we will discuss the overview of the datetime tag in HTML and mainly will focus on the example of datetime picker tag. We can add date and time picker in only one tag without using the two different tags. Let’s discuss it one by one. " }, { "code": null, "e": 24762, "s": 24754, "text": "Syntax:" }, { "code": null, "e": 24812, "s": 24762, "text": "For selecting a date we use the date tag in HTML." }, { "code": null, "e": 24847, "s": 24812, "text": "Date of Birth: <input type=\"date\">" }, { "code": null, "e": 24902, "s": 24847, "text": "And for selecting a time we use the time tag in HTML. " }, { "code": null, "e": 24934, "s": 24902, "text": "Enter Time: <input type=\"time\">" }, { "code": null, "e": 25196, "s": 24934, "text": "But if we want to take the date and time at the same time then these two separate lines of code will take more time than the datetime-local tag. So to reduce the time required for coding we can use only one line of code. Let’s see the syntax and example for it:" }, { "code": null, "e": 25242, "s": 25196, "text": "Date with Time: <input type=\"datetime-local\">" }, { "code": null, "e": 25469, "s": 25242, "text": "When we click on the input box of date and time it will show a calendar and time, and it will show the current date, month, and time by default, then we have to select the date and time or we can also type it in the input box." }, { "code": null, "e": 25478, "s": 25469, "text": "Example:" }, { "code": null, "e": 25483, "s": 25478, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Page Title</title></head> <body> <h2>Welcome To GFG</h2> Select date and time: <input type=\"datetime-local\" /></body> </html>", "e": 25667, "s": 25483, "text": null }, { "code": null, "e": 25675, "s": 25667, "text": "Output:" }, { "code": null, "e": 25812, "s": 25675, "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": 25827, "s": 25812, "text": "HTML-Questions" }, { "code": null, "e": 25837, "s": 25827, "text": "HTML-Tags" }, { "code": null, "e": 25842, "s": 25837, "text": "HTML" }, { "code": null, "e": 25859, "s": 25842, "text": "Web Technologies" }, { "code": null, "e": 25864, "s": 25859, "text": "HTML" }, { "code": null, "e": 25962, "s": 25864, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25971, "s": 25962, "text": "Comments" }, { "code": null, "e": 25984, "s": 25971, "text": "Old Comments" }, { "code": null, "e": 26008, "s": 25984, "text": "REST API (Introduction)" }, { "code": null, "e": 26045, "s": 26008, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 26074, "s": 26045, "text": "Form validation using jQuery" }, { "code": null, "e": 26121, "s": 26074, "text": "How to place text on image using HTML and CSS?" }, { "code": null, "e": 26183, "s": 26121, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 26239, "s": 26183, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26272, "s": 26239, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26315, "s": 26272, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26376, "s": 26315, "text": "Difference between var, let and const keywords in JavaScript" } ]
How to get only hidden files and folders in PowerShell?
To display only hidden files and folders –hidden parameter is used while using Get-ChildItem. Get-ChildItem D:\Temp\ -Hidden PS C:\WINDOWS\system32> Get-ChildItem D:\Temp\ -Hidden Directory: D:\Temp Mode LastWriteTime Length Name ---- ------------- ------ ---- -a-h-- 13-12-2019 09:52 6182 Hiddenfile1.xlsx Similarly, you can use this –Hidden with –Recurse or –Depth Get-ChildItem D:\Temp\ -Recurse -Hidden PS C:\WINDOWS\system32> Get-ChildItem D:\Temp\ -Recurse -Hidden Directory: D:\Temp Mode LastWriteTime Length Name ---- ------------- ------ ---- -a-h-- 13-12-2019 09:52 6182 Hiddenfile1.xlsx Directory: D:\Temp\GPO_backup Mode LastWriteTime Length Name ---- ------------- ------ ---- -a-h-- 13-12-2019 09:52 0 HiddenFile2.txt
[ { "code": null, "e": 1156, "s": 1062, "text": "To display only hidden files and folders –hidden parameter is used while using Get-ChildItem." }, { "code": null, "e": 1187, "s": 1156, "text": "Get-ChildItem D:\\Temp\\ -Hidden" }, { "code": null, "e": 1439, "s": 1187, "text": "PS C:\\WINDOWS\\system32> Get-ChildItem D:\\Temp\\ -Hidden\n Directory: D:\\Temp\nMode LastWriteTime Length Name\n---- ------------- ------ ----\n-a-h-- 13-12-2019 09:52 6182 Hiddenfile1.xlsx" }, { "code": null, "e": 1492, "s": 1439, "text": "Similarly, you can use this –Hidden with –Recurse or" }, { "code": null, "e": 1499, "s": 1492, "text": "–Depth" }, { "code": null, "e": 1539, "s": 1499, "text": "Get-ChildItem D:\\Temp\\ -Recurse -Hidden" }, { "code": null, "e": 2007, "s": 1539, "text": "PS C:\\WINDOWS\\system32> Get-ChildItem D:\\Temp\\ -Recurse -Hidden\n Directory: D:\\Temp\nMode LastWriteTime Length Name\n---- ------------- ------ ----\n-a-h-- 13-12-2019 09:52 6182 Hiddenfile1.xlsx\n Directory: D:\\Temp\\GPO_backup\nMode LastWriteTime Length Name\n---- ------------- ------ ----\n-a-h-- 13-12-2019 09:52 0 HiddenFile2.txt" } ]
Java Program to change JLabel text after creation
At first, set a text for JLabel − JLabel label; label = new JLabel("First Label"); Now change the above JLabel text using setText() − // changing text label.setText("Updated text"); import java.awt.Font; import javax.swing.*; public class SwingDemo { public static void main(String args[]) { JFrame frame = new JFrame("Label Example"); JLabel label; label = new JLabel("First Label"); label.setBounds(50, 50, 100, 30); label.setFont(new Font("Verdana", Font.PLAIN, 13)); // changing text label.setText("Updated text"); frame.add(label); frame.setSize(500,300); frame.setLayout(null); frame.setVisible(true); } }
[ { "code": null, "e": 1096, "s": 1062, "text": "At first, set a text for JLabel −" }, { "code": null, "e": 1145, "s": 1096, "text": "JLabel label;\nlabel = new JLabel(\"First Label\");" }, { "code": null, "e": 1196, "s": 1145, "text": "Now change the above JLabel text using setText() −" }, { "code": null, "e": 1244, "s": 1196, "text": "// changing text\nlabel.setText(\"Updated text\");" }, { "code": null, "e": 1746, "s": 1244, "text": "import java.awt.Font;\nimport javax.swing.*;\npublic class SwingDemo {\n public static void main(String args[]) {\n JFrame frame = new JFrame(\"Label Example\");\n JLabel label;\n label = new JLabel(\"First Label\");\n label.setBounds(50, 50, 100, 30);\n label.setFont(new Font(\"Verdana\", Font.PLAIN, 13));\n // changing text\n label.setText(\"Updated text\");\n frame.add(label);\n frame.setSize(500,300);\n frame.setLayout(null);\n frame.setVisible(true);\n }\n}" } ]
Intro to Recommender Systems with TensorFlow and TFRS | by Dimitris Poulopoulos | Towards Data Science
In his 2004 article entitled “The Long Tail,” Chris Anderson said that we are leaving the information age and entering the age of recommendation. Unless we can filter the information overload we absorb every day and retain only what is important to us, everything reduces to noise. A recommender system aims to predict the user’s behavioral patterns, preferences, or dislikes, and provide personalized recommendations on items users are likely to interact with. Moreover, we seem to diverge from the notion of search and embrace that of discovery. The difference is that when searching, a user is actively looking for something. Discovery suggests that something the user did not know existed, or did not know how to ask for, finds him. A recommender system aims to predict the user's behavioral patterns, preferences, or dislikes and provide personalized recommendations on items users are likely to interact with. So, are you curious about how such systems work? This story examines how to formulate a recommendation problem, the difference between implicit and explicit feedback, and how to build a movie recommender system with TensorFlow and TFRS. Learning Rate is my weekly newsletter for those who are curious about the world of AI and MLOps. You’ll hear from me every Friday with updates and thoughts on the latest AI news, research, repos and books. Subscribe here! The recommendation problem can be conceptually structured as a two-dimensional matrix, where rows correspond to users and columns correspond to items. Then, each cell’s value represents a user's preference for an item. A recommender system algorithm tries to predict the missing values in that matrix, and recommend the items that it predicts with a big score to an active user. Sometimes we have the user's explicit opinion for an item in the form of a rating score; we know what the user liked and what they could go without. When explicit feedback from the users is available, the system tries to solve a surrogate problem, where ratings are viewed as a proxy to preference. This is usually solved as a regression problem; thus, the algorithm tries to predict a real-valued rating to complete the user-item matrix's missing values. However, most of the time, we do not have access to explicit user feedback. In such cases, the system works passively in the background, trying to collect meaningful features. Those features can be used to implicitly discover user habits, preferences, and behavior, with some level of confidence. In binary implicit feedback, the user-item matrix is simplified to a Boolean matrix, where true values correspond to positive user-item interaction, and false values indicate no interaction. In any case, implicit feedback has consequences to both algorithmic design and evaluation measures. For this example, we use the well-known movielens dataset. However, we won’t consider the ratings given by users, but we will treat a user-movie interaction (i.e., a user u has seen movie m) as positive implicit feedback. On the other hand, we do not have any information about the void interactions; if a user has not seen a movie, we cannot be sure if this is because she doesn’t like the movie or hasn’t stumbled upon it yet. Although we could directly predict a user's recommendations, we will split the process into two parts: candidate extraction and candidate ranking. This is closer to what a real-world recommender, looking through millions of items, would do: Create a list of candidate items that a user might like, filtering out all the noise Rank those candidate items to produce a sorted list of personalized recommendations for the user This is actually what YouTube also does for generating video recommendations. You can read more in their relevant publication. In this article, we implement the first part of this process, the candidate extraction. In subsequent stories, we will see how to deploy this efficiently and how to rank those candidates. To generate valid candidates for our users, we build a retrieval model. Retrieval models are often composed of two sub-models: A query model computing the query representation, which essentially produces an embedding for each user. A candidate model computing the candidate representation, an embedding vector for each item. The two models' outputs are then multiplied together to give a query-candidate affinity score. This is the dot product between the user embedding vector and the corresponding item embedding vector; a higher score indicates a better match between the user and the item, or, in other words, the query and the candidate. In this tutorial, we see how to: Get our data and split it into a training and test set. Implement a retrieval model. Fit and evaluate the model. Serve the model efficiently by building an ANN index. First, let’s install the project’s dependencies and import the necessary libraries. We will install tensorflow-recommenders, tensorflow-datasets, and snann an optional dependency of TFRS, which will make our inference service orders of magnitude faster. We will see this last part in the next article, where we will talk about efficient deployment. !pip install -q tensorflow-recommenders!pip install -q --upgrade tensorflow-datasets!pip install -q scann Let’s now turn our attention to the data set. In this example, we use the MovieLens dataset from Tensorflow Datasets. Loading movielens/100k_ratings yields a tf.data.Dataset object containing the “ratings” data and loading movielens/100k_movies yields a tf.data.Dataset object containing only the “movies” data. The MovieLens data set does not have predefined splits, so we will load the train split. The ratings dataset holds a lot of info, such as the movie’s genre and the user’s age. Although you can use everything to build a more accurate model. Let’s simplify our problem a bit and keep only the user’s ID and the movie’s title. In the same way, let’s keep only the movie’s title from the movie dataset. Since we don’t have a train and test split predefined, let’s create one ourselves. First, we shuffle the examples and then take 80% for the training set and the remaining 20% for the validation set. Finally, we need to extract the unique user and movie IDs. This helps create our vocabularies, the list of users, and items we will embed. Choosing the architecture of our model is key in Deep Learning. In this case, our model consists of two parts: The query tower: the model that is responsible for learning the user embeddings The candidate tower: the model that is responsible for learning the movie embeddings We can build each tower separately and then combine them in the final model. Also, we should add an additional embedding to account for unknown tokens, and let’s agree on an embedding size of 32. Usually, more dimensions for the embedding layer will correspond to models that may be more accurate but will also be slower to fit and more prone to overfitting. We are now ready to combine the two towers in a single model: Instead of a forward method, we have a compute_loss method. This method will take the user and movie embeddings, compute the loss, update the weights, and evaluate the metrics, in one package. Under the hood, it’s still a plain Keras model. You could achieve the same functionality by inheriting from tf.keras.Model and overriding the train_step and test_step functions. But this is where TFRS shines! Next, let’s see how to define our loss and metric, and what those values mean. Using implicit feedback as our signal means that we only have info about the positive user-item interactions. Thus, to figure out how good our model is, we compare the score that the model calculates for a specific pair to the scores of all the other possible candidates; if the score for the positive pair is higher than for all other candidates, our model is highly accurate. To do this, we can use the tfrs.metrics.FactorizedTopK metric. The metric has one required argument: the dataset of candidates that are used as implicit negatives for evaluation. As for the loss, TFRS makes it easy, as it provides a wrapper called task. We are building a retrieval model, so we can use the Retrieval task object. A task object bundles together the loss function and metric computation. So, let’s specify the metric and the task: Finally, we are ready to train and evaluate the model. As we said, our recommender is nothing more than a Keras model, so we should compile it and fit it to the data. During training, and also after evaluation, you can monitor the performance of your model. We have this weird looking metric that says: factorized_top_k/top_10_categorical_accuracy': 0.02215000055730343 It’s actually quite simple: all it’s saying is that the movie that a user watched is in the top-10 recommended ones 2.2% of the time. This might look a bit low, but it’s actually a good result. To the best of my knowledge, the state of the art is around 5–6%. Moreover, the model is re-recommending some movies that the users have already watched. These known-positive watches can push test movies out of top K recommendations. This can be tackled by simply excluding previously seen movies from test recommendations. This story describes what a recommender is, how it works, and what’s the difference between implicit and explicit feedback. Next, we saw how to design modern, real-world recommenders by splitting the problem into a retrieval and a ranking challenge. Finally, we implemented a retrieval model using TensorFlow and TFRS. In the next articles, we will see how to efficiently deploy such a retrieval model and conclude our example by coding the ranking algorithm. Learning Rate is my weekly newsletter for those who are curious about the world of AI and MLOps. You’ll hear from me every Friday with updates and thoughts on the latest AI news, research, repos and books. Subscribe here! My name is Dimitris Poulopoulos, and I’m a machine learning engineer working for Arrikto. I have designed and implemented AI and software solutions for major clients such as the European Commission, Eurostat, IMF, the European Central Bank, OECD, and IKEA. If you are interested in reading more posts about Machine Learning, Deep Learning, Data Science, and DataOps, follow me on Medium, LinkedIn, or @james2pl on Twitter. Opinions expressed are solely my own and do not express the views or opinions of my employer.
[ { "code": null, "e": 453, "s": 171, "text": "In his 2004 article entitled “The Long Tail,” Chris Anderson said that we are leaving the information age and entering the age of recommendation. Unless we can filter the information overload we absorb every day and retain only what is important to us, everything reduces to noise." }, { "code": null, "e": 633, "s": 453, "text": "A recommender system aims to predict the user’s behavioral patterns, preferences, or dislikes, and provide personalized recommendations on items users are likely to interact with." }, { "code": null, "e": 908, "s": 633, "text": "Moreover, we seem to diverge from the notion of search and embrace that of discovery. The difference is that when searching, a user is actively looking for something. Discovery suggests that something the user did not know existed, or did not know how to ask for, finds him." }, { "code": null, "e": 1087, "s": 908, "text": "A recommender system aims to predict the user's behavioral patterns, preferences, or dislikes and provide personalized recommendations on items users are likely to interact with." }, { "code": null, "e": 1324, "s": 1087, "text": "So, are you curious about how such systems work? This story examines how to formulate a recommendation problem, the difference between implicit and explicit feedback, and how to build a movie recommender system with TensorFlow and TFRS." }, { "code": null, "e": 1546, "s": 1324, "text": "Learning Rate is my weekly newsletter for those who are curious about the world of AI and MLOps. You’ll hear from me every Friday with updates and thoughts on the latest AI news, research, repos and books. Subscribe here!" }, { "code": null, "e": 1765, "s": 1546, "text": "The recommendation problem can be conceptually structured as a two-dimensional matrix, where rows correspond to users and columns correspond to items. Then, each cell’s value represents a user's preference for an item." }, { "code": null, "e": 1925, "s": 1765, "text": "A recommender system algorithm tries to predict the missing values in that matrix, and recommend the items that it predicts with a big score to an active user." }, { "code": null, "e": 2381, "s": 1925, "text": "Sometimes we have the user's explicit opinion for an item in the form of a rating score; we know what the user liked and what they could go without. When explicit feedback from the users is available, the system tries to solve a surrogate problem, where ratings are viewed as a proxy to preference. This is usually solved as a regression problem; thus, the algorithm tries to predict a real-valued rating to complete the user-item matrix's missing values." }, { "code": null, "e": 2969, "s": 2381, "text": "However, most of the time, we do not have access to explicit user feedback. In such cases, the system works passively in the background, trying to collect meaningful features. Those features can be used to implicitly discover user habits, preferences, and behavior, with some level of confidence. In binary implicit feedback, the user-item matrix is simplified to a Boolean matrix, where true values correspond to positive user-item interaction, and false values indicate no interaction. In any case, implicit feedback has consequences to both algorithmic design and evaluation measures." }, { "code": null, "e": 3398, "s": 2969, "text": "For this example, we use the well-known movielens dataset. However, we won’t consider the ratings given by users, but we will treat a user-movie interaction (i.e., a user u has seen movie m) as positive implicit feedback. On the other hand, we do not have any information about the void interactions; if a user has not seen a movie, we cannot be sure if this is because she doesn’t like the movie or hasn’t stumbled upon it yet." }, { "code": null, "e": 3639, "s": 3398, "text": "Although we could directly predict a user's recommendations, we will split the process into two parts: candidate extraction and candidate ranking. This is closer to what a real-world recommender, looking through millions of items, would do:" }, { "code": null, "e": 3724, "s": 3639, "text": "Create a list of candidate items that a user might like, filtering out all the noise" }, { "code": null, "e": 3821, "s": 3724, "text": "Rank those candidate items to produce a sorted list of personalized recommendations for the user" }, { "code": null, "e": 3948, "s": 3821, "text": "This is actually what YouTube also does for generating video recommendations. You can read more in their relevant publication." }, { "code": null, "e": 4136, "s": 3948, "text": "In this article, we implement the first part of this process, the candidate extraction. In subsequent stories, we will see how to deploy this efficiently and how to rank those candidates." }, { "code": null, "e": 4263, "s": 4136, "text": "To generate valid candidates for our users, we build a retrieval model. Retrieval models are often composed of two sub-models:" }, { "code": null, "e": 4368, "s": 4263, "text": "A query model computing the query representation, which essentially produces an embedding for each user." }, { "code": null, "e": 4461, "s": 4368, "text": "A candidate model computing the candidate representation, an embedding vector for each item." }, { "code": null, "e": 4779, "s": 4461, "text": "The two models' outputs are then multiplied together to give a query-candidate affinity score. This is the dot product between the user embedding vector and the corresponding item embedding vector; a higher score indicates a better match between the user and the item, or, in other words, the query and the candidate." }, { "code": null, "e": 4812, "s": 4779, "text": "In this tutorial, we see how to:" }, { "code": null, "e": 4868, "s": 4812, "text": "Get our data and split it into a training and test set." }, { "code": null, "e": 4897, "s": 4868, "text": "Implement a retrieval model." }, { "code": null, "e": 4925, "s": 4897, "text": "Fit and evaluate the model." }, { "code": null, "e": 4979, "s": 4925, "text": "Serve the model efficiently by building an ANN index." }, { "code": null, "e": 5328, "s": 4979, "text": "First, let’s install the project’s dependencies and import the necessary libraries. We will install tensorflow-recommenders, tensorflow-datasets, and snann an optional dependency of TFRS, which will make our inference service orders of magnitude faster. We will see this last part in the next article, where we will talk about efficient deployment." }, { "code": null, "e": 5434, "s": 5328, "text": "!pip install -q tensorflow-recommenders!pip install -q --upgrade tensorflow-datasets!pip install -q scann" }, { "code": null, "e": 5746, "s": 5434, "text": "Let’s now turn our attention to the data set. In this example, we use the MovieLens dataset from Tensorflow Datasets. Loading movielens/100k_ratings yields a tf.data.Dataset object containing the “ratings” data and loading movielens/100k_movies yields a tf.data.Dataset object containing only the “movies” data." }, { "code": null, "e": 5835, "s": 5746, "text": "The MovieLens data set does not have predefined splits, so we will load the train split." }, { "code": null, "e": 6145, "s": 5835, "text": "The ratings dataset holds a lot of info, such as the movie’s genre and the user’s age. Although you can use everything to build a more accurate model. Let’s simplify our problem a bit and keep only the user’s ID and the movie’s title. In the same way, let’s keep only the movie’s title from the movie dataset." }, { "code": null, "e": 6344, "s": 6145, "text": "Since we don’t have a train and test split predefined, let’s create one ourselves. First, we shuffle the examples and then take 80% for the training set and the remaining 20% for the validation set." }, { "code": null, "e": 6483, "s": 6344, "text": "Finally, we need to extract the unique user and movie IDs. This helps create our vocabularies, the list of users, and items we will embed." }, { "code": null, "e": 6594, "s": 6483, "text": "Choosing the architecture of our model is key in Deep Learning. In this case, our model consists of two parts:" }, { "code": null, "e": 6674, "s": 6594, "text": "The query tower: the model that is responsible for learning the user embeddings" }, { "code": null, "e": 6759, "s": 6674, "text": "The candidate tower: the model that is responsible for learning the movie embeddings" }, { "code": null, "e": 7118, "s": 6759, "text": "We can build each tower separately and then combine them in the final model. Also, we should add an additional embedding to account for unknown tokens, and let’s agree on an embedding size of 32. Usually, more dimensions for the embedding layer will correspond to models that may be more accurate but will also be slower to fit and more prone to overfitting." }, { "code": null, "e": 7180, "s": 7118, "text": "We are now ready to combine the two towers in a single model:" }, { "code": null, "e": 7421, "s": 7180, "text": "Instead of a forward method, we have a compute_loss method. This method will take the user and movie embeddings, compute the loss, update the weights, and evaluate the metrics, in one package. Under the hood, it’s still a plain Keras model." }, { "code": null, "e": 7582, "s": 7421, "text": "You could achieve the same functionality by inheriting from tf.keras.Model and overriding the train_step and test_step functions. But this is where TFRS shines!" }, { "code": null, "e": 7661, "s": 7582, "text": "Next, let’s see how to define our loss and metric, and what those values mean." }, { "code": null, "e": 8039, "s": 7661, "text": "Using implicit feedback as our signal means that we only have info about the positive user-item interactions. Thus, to figure out how good our model is, we compare the score that the model calculates for a specific pair to the scores of all the other possible candidates; if the score for the positive pair is higher than for all other candidates, our model is highly accurate." }, { "code": null, "e": 8218, "s": 8039, "text": "To do this, we can use the tfrs.metrics.FactorizedTopK metric. The metric has one required argument: the dataset of candidates that are used as implicit negatives for evaluation." }, { "code": null, "e": 8485, "s": 8218, "text": "As for the loss, TFRS makes it easy, as it provides a wrapper called task. We are building a retrieval model, so we can use the Retrieval task object. A task object bundles together the loss function and metric computation. So, let’s specify the metric and the task:" }, { "code": null, "e": 8652, "s": 8485, "text": "Finally, we are ready to train and evaluate the model. As we said, our recommender is nothing more than a Keras model, so we should compile it and fit it to the data." }, { "code": null, "e": 8788, "s": 8652, "text": "During training, and also after evaluation, you can monitor the performance of your model. We have this weird looking metric that says:" }, { "code": null, "e": 8855, "s": 8788, "text": "factorized_top_k/top_10_categorical_accuracy': 0.02215000055730343" }, { "code": null, "e": 9115, "s": 8855, "text": "It’s actually quite simple: all it’s saying is that the movie that a user watched is in the top-10 recommended ones 2.2% of the time. This might look a bit low, but it’s actually a good result. To the best of my knowledge, the state of the art is around 5–6%." }, { "code": null, "e": 9373, "s": 9115, "text": "Moreover, the model is re-recommending some movies that the users have already watched. These known-positive watches can push test movies out of top K recommendations. This can be tackled by simply excluding previously seen movies from test recommendations." }, { "code": null, "e": 9692, "s": 9373, "text": "This story describes what a recommender is, how it works, and what’s the difference between implicit and explicit feedback. Next, we saw how to design modern, real-world recommenders by splitting the problem into a retrieval and a ranking challenge. Finally, we implemented a retrieval model using TensorFlow and TFRS." }, { "code": null, "e": 9833, "s": 9692, "text": "In the next articles, we will see how to efficiently deploy such a retrieval model and conclude our example by coding the ranking algorithm." }, { "code": null, "e": 10055, "s": 9833, "text": "Learning Rate is my weekly newsletter for those who are curious about the world of AI and MLOps. You’ll hear from me every Friday with updates and thoughts on the latest AI news, research, repos and books. Subscribe here!" }, { "code": null, "e": 10312, "s": 10055, "text": "My name is Dimitris Poulopoulos, and I’m a machine learning engineer working for Arrikto. I have designed and implemented AI and software solutions for major clients such as the European Commission, Eurostat, IMF, the European Central Bank, OECD, and IKEA." }, { "code": null, "e": 10478, "s": 10312, "text": "If you are interested in reading more posts about Machine Learning, Deep Learning, Data Science, and DataOps, follow me on Medium, LinkedIn, or @james2pl on Twitter." } ]
HTML <output> Tag - GeeksforGeeks
17 Mar, 2022 The <output> tag in HTML is used to represent the result of a calculation performed by the client-side script such as JavaScript. The <output> tag is a new tag in HTML 5, and it requires a starting and ends tag. Syntax: <output> Results... </output> Attributes: The output tag accepts three attributes which are listed below: for: This attribute contains an attribute value element_id which is used to specify the relation between result and calculations. form: This attribute contains an attribute value form_id which is used to specify one or more forms of output elements. name: This attribute contains an attribute value name that is used to specify the name of the output element. Example 1: html <!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML output Tag</h2> <form oninput="sumresult.value = parseInt(A.value) + parseInt(B.value) + parseInt(C.value)"> <input type="number" name="A" value="50" /> + <input type="range" name="B" value="0" /> + <input type="number" name="C" value="30" /> <br> <!-- output tag --> Result: <output name="sumresult"></output> </form></body> </html> Output: Example 2: In this example, <output> tag is used with for and form attribute. html <!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML output Tag</h2> <form oninput="sumresult.value = parseInt(A.value) + parseInt(B.value) + parseInt(C.value)"> <input type="number" name="A" value="50" /> + <input type="range" name="B" value="0" /> + <input type="number" name="C" value="50" /> <br /> Submit Result: <!-- output tag --> <output name="sumresult" for="A B C"></output> <br> <input type="submit"> </form></body> </html> Output: Supported Browsers: Google Chrome 10.0 Internet Explorer 13.0 Firefox 4.0 Opera 11.0 Apple Safari 5.1 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. ghoshsuman0129 HTML-Tags HTML HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ? Types of CSS (Cascading Style Sheet) Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form REST API (Introduction)
[ { "code": null, "e": 22707, "s": 22679, "text": "\n17 Mar, 2022" }, { "code": null, "e": 22920, "s": 22707, "text": "The <output> tag in HTML is used to represent the result of a calculation performed by the client-side script such as JavaScript. The <output> tag is a new tag in HTML 5, and it requires a starting and ends tag. " }, { "code": null, "e": 22929, "s": 22920, "text": "Syntax: " }, { "code": null, "e": 22959, "s": 22929, "text": "<output> Results... </output>" }, { "code": null, "e": 23036, "s": 22959, "text": "Attributes: The output tag accepts three attributes which are listed below: " }, { "code": null, "e": 23166, "s": 23036, "text": "for: This attribute contains an attribute value element_id which is used to specify the relation between result and calculations." }, { "code": null, "e": 23286, "s": 23166, "text": "form: This attribute contains an attribute value form_id which is used to specify one or more forms of output elements." }, { "code": null, "e": 23396, "s": 23286, "text": "name: This attribute contains an attribute value name that is used to specify the name of the output element." }, { "code": null, "e": 23408, "s": 23396, "text": "Example 1: " }, { "code": null, "e": 23413, "s": 23408, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML output Tag</h2> <form oninput=\"sumresult.value = parseInt(A.value) + parseInt(B.value) + parseInt(C.value)\"> <input type=\"number\" name=\"A\" value=\"50\" /> + <input type=\"range\" name=\"B\" value=\"0\" /> + <input type=\"number\" name=\"C\" value=\"30\" /> <br> <!-- output tag --> Result: <output name=\"sumresult\"></output> </form></body> </html>", "e": 23880, "s": 23413, "text": null }, { "code": null, "e": 23890, "s": 23880, "text": "Output: " }, { "code": null, "e": 23969, "s": 23890, "text": "Example 2: In this example, <output> tag is used with for and form attribute. " }, { "code": null, "e": 23974, "s": 23969, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML output Tag</h2> <form oninput=\"sumresult.value = parseInt(A.value) + parseInt(B.value) + parseInt(C.value)\"> <input type=\"number\" name=\"A\" value=\"50\" /> + <input type=\"range\" name=\"B\" value=\"0\" /> + <input type=\"number\" name=\"C\" value=\"50\" /> <br /> Submit Result: <!-- output tag --> <output name=\"sumresult\" for=\"A B C\"></output> <br> <input type=\"submit\"> </form></body> </html>", "e": 24503, "s": 23974, "text": null }, { "code": null, "e": 24513, "s": 24503, "text": "Output: " }, { "code": null, "e": 24534, "s": 24513, "text": "Supported Browsers: " }, { "code": null, "e": 24553, "s": 24534, "text": "Google Chrome 10.0" }, { "code": null, "e": 24576, "s": 24553, "text": "Internet Explorer 13.0" }, { "code": null, "e": 24588, "s": 24576, "text": "Firefox 4.0" }, { "code": null, "e": 24599, "s": 24588, "text": "Opera 11.0" }, { "code": null, "e": 24616, "s": 24599, "text": "Apple Safari 5.1" }, { "code": null, "e": 24753, "s": 24616, "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": 24768, "s": 24753, "text": "ghoshsuman0129" }, { "code": null, "e": 24778, "s": 24768, "text": "HTML-Tags" }, { "code": null, "e": 24783, "s": 24778, "text": "HTML" }, { "code": null, "e": 24788, "s": 24783, "text": "HTML" }, { "code": null, "e": 24886, "s": 24788, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24895, "s": 24886, "text": "Comments" }, { "code": null, "e": 24908, "s": 24895, "text": "Old Comments" }, { "code": null, "e": 24970, "s": 24908, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 25020, "s": 24970, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 25080, "s": 25020, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 25128, "s": 25080, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 25189, "s": 25128, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 25226, "s": 25189, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 25279, "s": 25226, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 25329, "s": 25279, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 25379, "s": 25329, "text": "CSS to put icon inside an input element in a form" } ]
A short tutorial on Fuzzy Time Series | by Petrônio Silva | Towards Data Science
Time series analysis and forecasting methods are indispensable on several fields, for instance on engineering, medicine, economy, meteorology, etc. There are several methods of analysis and forecasting, from the traditional and consecrated statistical tools (ARMA, ARIMA, SARIMA, Holt-Winters, etc), to the new computational intelligence tools (recurrent neural networks, LSTM, GRU, etc). There is no perfect method, neither the one I going to present here. But some key features distinguish the Fuzzy Time Series e turn it on a attractive option: Readability Manageability Simplicity Scalability Hereafter I going to assume that you don’t have a machine learning (with focus on fuzzy systems) and time series background and I will present the key concepts of these fields. Then the Fuzzy Time Series methods will be introduced with the help of the pyFTS library. Let’s go? If you already know about Fuzzy Logic and Fuzzy Sets, you can go ahead to the next section. Here are presented just the very introductory concepts! The logic theory and classical mathematics define a Set as a dichotomy: every element is in OR out of the set. The is no middle point! The membership of an element is a boolean value, that is, a value on set {0 , 1}, imposing to each set strong and inflexible boundaries. This dichotomous way of thinking is uncomfortable for the human being because innumerable realities are not so. We will have difficulty when we try to classify people into categories with strict limits, for example: weight = {thin, slender, fat}, age = {child, adolescent, young, adult, elderly}, height = {low, medium, high}. If we are to describe someone using these concepts in at least one of them we will find that the person could be in a middle category between these two values. But classic / rigid sets do not give us this flexibility. The Fuzzy Logic, proposed by Zadeh (1965), state a duality instead of this dichotomy: a certain element may belong and simultaneously do not belong to the same set at certain levels, such that the membership is a value in the interval [0, 1]. The fuzzy sets have no strict boundaries and they are usually overlapping, so — using the previous example — I can be medium high and medium, or 90% medium and 10% high for example. Given X, a Numerical Variable, such that X ∈ R — for instance an height measure — its Universe of Discourse, abbreviated to U, is the is the range of values that this variable can assume, such that U = [ min(X), max(X) ]. A linguistic variable A is the transformation of the values of the numerical variable X into a set of words / linguistic terms (what we call fuzzification). Each word/linguistic ter is a fuzzy set ã ∈ Ã, and each fuzzy set ã is associated to a function μ (mu greek letter), such that μã: X →[0,1] (this mean that μã receives an input value from X and return an output value on interval [0,1]). Let’s get back to the numerical variable height, measured in centimeters. We define U = [20,220] and the linguistic variable à as: à = {“very small”, “small”, “short”, “medium”, “tall”, “very tall”} Do you see what we’re trying to do? We want to stop working with the numerical data of X and start working with the vocabulary expressed by Ã, and for this we need to map the values of X for each set ã ∈ Ã. We will do this by dividing U into 6 overlapping intervals, one for each set ã ∈ Ã. For each interval we associate an μã(X) function. There are several types of membership functions but, just to simplify, we will use the triangular membership function. The triangular membership function can be defined as: def triangular(x, a, b, c): return max( min( (x-a)/(b-a), (c-x)/(c-b) ), 0 ) Where a, b and c draws a triangle with the a on the left , b on the top and c as right point. When a given input value x is equal to b we say that it is 100% inside the fuzzy set( in other words: its membership grade is equal to 1). In other hand, the membership increase linearly from 0 to 1 on interval [a, b], and linearly decrease from 1 to 0 on interval [b,c]. If x is smaller than a, or greater than c, we say that x is completely outside of the fuzzy set (int other words: its membership grade is equal to 0). So, what would our sets look like for the linguistic variable Ã? Suppose a person is 163cm tall. For the variable Ã, it would be .27 median and .73 tall, that is: μ_median(163) = triangular(163, 90, 130, 175) = 0.2666666... μ_high(163) = triangular(163, 130, 175,220) = 0.7333... Check out the code here! But is is only the beginning of a huge knowledge field. If you want to know more about Fuzzy Logic and Fuzzy Systems.... But where are here to talk about time series, right? So let’s talk about time! If you already know about time series, you can go to the next section, this one is very introductory! Time series are sets of data representing the behavior of one (or more) random variable over time, and its main characteristic is that the successive records of this variable are not independent of each other and their analysis must take into account the order in that were collected. According to Ehlers (2009), “the neighboring observations are dependent and we are interested in analyzing and modeling this dependence”. What does that mean? That to predict future values of the time series I use past / lagged values of the same series. A simple example is the autoregressive AR(p) model, where p indicates the number of lagged variables used on forecasting. Given a time series X(t), where t indicates a moment in time, if we going to use only use a lag in the forecast then we have an AR(1) model, that would be something like X(t) = α·X(t-1) + ε, where X(t-1) is the lagged value, α is a coefficient adjusted by statistical methods and ε represents the noise or random error, which indicates the uncertainty associated with this forecast, ε ~N(0,1). If we want to use the last two lags on forecasting we will have an AR(2) model, which would be something like X(t) = α0·X(t-1) +α1·X(t-2) +ε. What is the amount of lags and what lags should be used? To do this, it is necessary to study the components of the time series and analyze their properties, using graphs such as ACF and PACF. Usually time series are modeled (using an additive model) at high level as: X(t) =C(t) + T(t) + S(t) + R(t) Where: t is the time index; X(t) is a point estimate of the series at time t; C(t) is the cyclical component, foreseeable short / very short term fluctuations; T(t) is the trend component, which indicates the long-term behavior of the series. Generally the tendency is of growth / rise or reduction / descent, otherwise it is said that the series has no tendency; S(t) is the seasonal component, which is periodic fluctuations of medium and long term. A good example of seasonal component are ... guess what? The seasons of the year! These are intervals of 4 months that have a very characteristic of their own and are repeated annually — which makes any variable with this seasonality much more predictable. R(t) is the noise component, a random value with constant mean and variance. This random noise is not predictable! Not all time series have trend or seasonality. Some series are known to be stationary, meaning that their average values are (more or less) constant. In non-stationary series the average changes over time. In the homocedastic series, the variance is constant and in the heteroskedastic series the variance changes over time. To summarize: stationary and homoskedastic time series are “well behaved” and simpler to predict, and non-stationary and heteroskedastic series are much more complex. In the latter case we can apply mathematical transformations (such as differentiation, Box-Cox, etc.) to make the series stationary and homoskedastic. But.... Where do fuzzy sets come into this story? The use of fuzzy sets for modeling and predicting time series arises almost intuitively, first based on the ability of fuzzy models to approximate functions, but also on the readability of rules using linguistic variables that make them more accessible to experts and non-experts analysis. The pioneer work on fuzzy time series is Song and Chisson(1993) but here we present the evolution published by Chen(1996). The idea is to divide the Universe of Discourse from time series in intervals/partitions (the fuzzy sets), and learn how each area behaves (extracting rules through the time series patterns). The rules of these models tell how the partitions relate with themselves over the time, as values jump from one place to another. In other words: let’s create a linguistic variable to represent the numerical time series, and these areas will be the linguistic terms of our variable. When we create a linguistic variable to represent the universe of discourse, we create a “vocabulary,” and then the fuzzyfied series is composed of words in that vocabulary. The sequence of these words — the sentences or phrases — are the patterns we need to learned. To facilitate, I will divide the methodology of fuzzy time series into two procedures: training and forecasting. We will use in this tutorial a very known time series from the origins of the Fuzzy Time Series: the enrollments of Alabama University (Enrollments). You can see the data below: 1. Definition of the Universe of Discourse UFirst we need to know the universe of discourse U from the training data, such as U = [min(X), max(X)]. Usually we extrapolate the upper and lower bounds by 20%, as a security margin. 2. Create the Linguistic Variable à (Universe of Discourse Partitioning)Now we need to split U on several overlapping intervals (a.k.a partitions) and create a fuzzy set for each one of them. The number of intervals is one of the most important parameters on Fuzzy Time Series and it will directly imply on model’s accuracy. Beyond the number of partitions, the way we split U also have great impact on accuracy. Hereafter we adopt the simplest method for partitioning, the Grid Partitioning, where all partitions have the same length and format. To know other partitioning methods click here. For our example data we will use a 10 partitions scheme, such that the linguistic variable be à = { A0, A1, ..., A9 }. 3. FuzzyficationNow we can convert the numerical values of X(t) into fuzzy values of the linguistic variable Ã, giving rise to the fuzzy time series F(t). It is always good to remind that the fuzzy sets on à are overlapped, so for each x ∈ X(t) it is possible that it belongs to more than one fuzzy set Ai ∈ Ã. On Chen methods the things are a little bit simplier: just the maximum membership fuzzy set is choosen. However in other FTS methods all fuzzyfied values are considered. Using the Chen’s method the fuzzyfied values for our test data will be F(t) = { A1, A2, A2, A3, A4, A4, A4, A4, A5, A5, A5, A4, A4, A4, A4, A4, A5, A7, A8, A8, A8, A7 }. 4. Creating the temporal patterns A temporal patterns indicates two fuzzy sets that appear sequentially on fuzzy time series F(t) and have the format Precedent →Consequent, where the precedent indicates a fuzzy set on time t and the consequent the fuzzy set that appears soon after on time t+1. For the previous example, the generated temporal patterns will be: A1→A2, A2→A2, A2→A3, A3→A4, A4→A4, ..., A8→A8, A8→A7 5. Creating the rulesOur model rules also have the format Precedent →Consequent. Given the previously generated temporal patterns we will group them by its precedents. Our model will contain a rule for each distinct precedent found, and the consequent of each rule will be the union of all consequents of each temporal pattern with the same precedent. For the previous example, the generated rules will be:A1 →A2A2 →A2,A3A3 →A4A4 →A4,A5A5 →A4,A5,A7A7 →A8A8 →A7,A8 The rule set is, in fact, out FTS model. They describe how our time series behaves and, if it was stationary enough (well behaved) we can use this model to forecast the next values on the time. An simple and readable model like that has another advantages: a) it is very easy to parallelize/distribute, what makes it very attractive for big data; b) it is very easy to update, what makes it very attractive for frequently-changing data. But how we can use this rules on forecasting? Since we know the numerical value for time t, x(t) ∈ X(t), we now want to predict the next instant, x(t + 1). 1. Input value fuzzyficationThe input value x(t) will be converted into fuzzy values of the linguistic variable Ã, generating the value f(t). As in the training process only the most pertinent set is chosen. For the example data, for t = 1992 the value is x(t) = 18876. Fuzzyfying x(t) the set of most pertinent is A7, so f(t) = A7. 2. Find the compatible rules Find the rule whose precedent is equal to f(t). The consequence of the rule will be the fuzzy forecast for t + 1, that is, f(t + 1). For f(t) = A7 we have the rule A7 → A8. Then f(t + 1) = A8. 3. DefuzzyficationNow you need to convert f(t + 1) to a numeric value. For this we use the center-of-mass method, where the numerical value is equal to the mean of the centers of the fuzzy sets of f(t + 1), that is x(t+1) = n−1∑ Ai, for i = 0..n-1 and n equal to the number of sets in f(t+1). Since f(t + 1) has only one set, then x(t + 1) = 19366.46. This presented model is very simple, and I must say, archaic (it from 1996 !!!). But it is a good guide to understanding how fuzzy time series work. The most accurate methods now use more lags (this one use only the t-1 lag), weights in the rules (from the work of Yu (2005)), optimizers to find the best number of sets, lags, etc. In the next tutorials we will delve into more advanced models. All above explained procedures can be reproduced on this Google Colab notebook. Now it’s time to go play a little and get our hands dirty!!!! :-) The pyFTS: Fuzzy Time Series for Python library is developed on MINDS — Machine Intelligence and Data Science of Federal University of Minas Gerais (UFMG) at Brazil, and is intended for students, researchers, data scientists or whose want to exploit the Fuzzy Time Series methods. PyFTS is a project in continuous development and all contributions are welcome! Let’s know some of the main features of the library: 1. Test data In the pyFTS.data package there are several datasets of common time series such as TAIEX, NASDAQ, S&P 500, passengers, etc. Each dataset has its own features — some are univariate, others multivariate, etc — but all of them basically have two functions: get_data(): return the univariate time series get_dataset(): return the multivariate time series from pyFTS.data import Enrollmentstrain = Enrollments.get_data() 2. Data transformations In the package pyFTS.common.Transformations several data transformations can be used for the pre-processing and/or post-processing data, which directly impacts the partitioning of the universe of discourse. from pyFTS.common import Transformationstdiff = Transformations.Differential(1) 3. Partitioners In the pyFTS.partitioners package are the universe of discourse partitioners. Each partitioner has the function of representing the linguistic variable, creating the partitions of the Discourse Universe and its fuzzy sets. In all of them at least two constructor parameters are required: data: (mandatory!) the train data; npart: (mandatory!) the minimal number of fuzzy sets to build; mf: the membership function that will be used on fuzzy sets, which by default is triangular (trimf). The various membership functions can be found in pyFTS.common.Membership; transformation: if any transformation is used in the series, it should be reported here. from pyFTS.partitioners import Grid, Entropy, Util as pUtilfs = Grid.GridPartitioner(data=train, npart=20)print(fs) We can explore several several alternatives for universe of discourse partitioners, each one of them with its own characteristics and performance. 4. Fuzzy Time Series methods The various methods are found in the package pyFTS.models. All methods inherit from the class common.fts.FTS. For the end user there are two main methods to know: FTS.fit(data, partitioner=fs) : Trains the model from the training data on parameter data and the linguistic variable already constructed by the fs partitioner. It is advisable to study the help of this function because here it is already possible to do the distributed training using clusters dispy. As soon as possible also a version compatible with pySpark will be realeased. FTS.predict(data, type=’point’, steps_ahead=1): It uses the already trained model to make predictions from the lags contained in the data. There are three possible prediction types, indicated by the ‘type’ parameter: ‘point’ (default), ‘interval’ and ‘distribution’. One should be careful when choosing the method because not all of them work with all these types. Finally, the ‘steps_ahead’ parameter indicates the prediction horizon, or how many steps forward you want to predict. from pyFTS.models import chenmodel = chen.ConventionalFTS(partitioner=fs)model.fit(train)print(model)forecasts = model.predict(test) There are several models to be explored, so give a look on the example codes. On the second part of this tutorial I’m talking about weighted methods, high order models, multivariate models and multi step forecasting. I also apply these models to forecast photovoltaic energy. The third part talks about interval and probabilistic forecasting, non-stationarity, concept drift and time variant models. Be sure to read them! Chen Shyi-Ming. Forecasting enrollments based on fuzzy time series. Fuzzy sets and systems, vol. 81, number 3, pp. 311–319, 1996. URL: https://doi.org/10.1016/0165–0114(95)00220–0. Acess in 25/07/2018. Ehlers, R.S. Análise de séries temporais. Departamento de Estatística, Universidade Federal do Paraná. URL: http://conteudo.icmc.usp.br/pessoas/ehlers/stemp/stemp.pdf. Acess in 25/07/2018. Morettin, P.A. e Toloi, C.M.C. Análise de Séries Temporais. Blucher, 2004 Silva, P. C. L. et al. pyFTS: Fuzzy Time Series for Python, v4.0. URL: https://doi.org/10.5281/zenodo.597359. Acess in 25/07/2018. Song, Qiang; Chissom, Brad S. Fuzzy time series and its models. Fuzzy sets and systems, vol. 54, number 3, pp. 269–277, 1993. URL: https://doi.org/10.1016/0165-0114(93)90372-O. Acess in 25/07/2018. Yu, Hui-Kuang, Weighted fuzzy time series models for TAIEX forecasting. Physica A: Statistical Mechanics and its Applications, vol. 349, number 3, pp. 609–624, 2005. URL: https://doi.org/10.1016/j.physa.2004.11.006. Acess in 25/07/2018. Zadeh, L. A. Fuzzy sets. Information and Control 8 (3) 338–353, 1965. URL: https://doi.org/10.1016/S0019-9958(65)90241-X. Acess in 25/07/2018.
[ { "code": null, "e": 320, "s": 172, "text": "Time series analysis and forecasting methods are indispensable on several fields, for instance on engineering, medicine, economy, meteorology, etc." }, { "code": null, "e": 720, "s": 320, "text": "There are several methods of analysis and forecasting, from the traditional and consecrated statistical tools (ARMA, ARIMA, SARIMA, Holt-Winters, etc), to the new computational intelligence tools (recurrent neural networks, LSTM, GRU, etc). There is no perfect method, neither the one I going to present here. But some key features distinguish the Fuzzy Time Series e turn it on a attractive option:" }, { "code": null, "e": 732, "s": 720, "text": "Readability" }, { "code": null, "e": 746, "s": 732, "text": "Manageability" }, { "code": null, "e": 757, "s": 746, "text": "Simplicity" }, { "code": null, "e": 769, "s": 757, "text": "Scalability" }, { "code": null, "e": 1046, "s": 769, "text": "Hereafter I going to assume that you don’t have a machine learning (with focus on fuzzy systems) and time series background and I will present the key concepts of these fields. Then the Fuzzy Time Series methods will be introduced with the help of the pyFTS library. Let’s go?" }, { "code": null, "e": 1194, "s": 1046, "text": "If you already know about Fuzzy Logic and Fuzzy Sets, you can go ahead to the next section. Here are presented just the very introductory concepts!" }, { "code": null, "e": 1466, "s": 1194, "text": "The logic theory and classical mathematics define a Set as a dichotomy: every element is in OR out of the set. The is no middle point! The membership of an element is a boolean value, that is, a value on set {0 , 1}, imposing to each set strong and inflexible boundaries." }, { "code": null, "e": 2011, "s": 1466, "text": "This dichotomous way of thinking is uncomfortable for the human being because innumerable realities are not so. We will have difficulty when we try to classify people into categories with strict limits, for example: weight = {thin, slender, fat}, age = {child, adolescent, young, adult, elderly}, height = {low, medium, high}. If we are to describe someone using these concepts in at least one of them we will find that the person could be in a middle category between these two values. But classic / rigid sets do not give us this flexibility." }, { "code": null, "e": 2436, "s": 2011, "text": "The Fuzzy Logic, proposed by Zadeh (1965), state a duality instead of this dichotomy: a certain element may belong and simultaneously do not belong to the same set at certain levels, such that the membership is a value in the interval [0, 1]. The fuzzy sets have no strict boundaries and they are usually overlapping, so — using the previous example — I can be medium high and medium, or 90% medium and 10% high for example." }, { "code": null, "e": 2658, "s": 2436, "text": "Given X, a Numerical Variable, such that X ∈ R — for instance an height measure — its Universe of Discourse, abbreviated to U, is the is the range of values that this variable can assume, such that U = [ min(X), max(X) ]." }, { "code": null, "e": 3057, "s": 2658, "text": "A linguistic variable A is the transformation of the values of the numerical variable X into a set of words / linguistic terms (what we call fuzzification). Each word/linguistic ter is a fuzzy set ã ∈ Ã, and each fuzzy set ã is associated to a function μ (mu greek letter), such that μã: X →[0,1] (this mean that μã receives an input value from X and return an output value on interval [0,1])." }, { "code": null, "e": 3189, "s": 3057, "text": "Let’s get back to the numerical variable height, measured in centimeters. We define U = [20,220] and the linguistic variable à as:" }, { "code": null, "e": 3258, "s": 3189, "text": "à = {“very small”, “small”, “short”, “medium”, “tall”, “very tall”}" }, { "code": null, "e": 3468, "s": 3258, "text": "Do you see what we’re trying to do? We want to stop working with the numerical data of X and start working with the vocabulary expressed by Ã, and for this we need to map the values of X for each set ã ∈ Ã." }, { "code": null, "e": 3778, "s": 3468, "text": "We will do this by dividing U into 6 overlapping intervals, one for each set ã ∈ Ã. For each interval we associate an μã(X) function. There are several types of membership functions but, just to simplify, we will use the triangular membership function. The triangular membership function can be defined as:" }, { "code": null, "e": 3858, "s": 3778, "text": "def triangular(x, a, b, c): return max( min( (x-a)/(b-a), (c-x)/(c-b) ), 0 )" }, { "code": null, "e": 4375, "s": 3858, "text": "Where a, b and c draws a triangle with the a on the left , b on the top and c as right point. When a given input value x is equal to b we say that it is 100% inside the fuzzy set( in other words: its membership grade is equal to 1). In other hand, the membership increase linearly from 0 to 1 on interval [a, b], and linearly decrease from 1 to 0 on interval [b,c]. If x is smaller than a, or greater than c, we say that x is completely outside of the fuzzy set (int other words: its membership grade is equal to 0)." }, { "code": null, "e": 4441, "s": 4375, "text": "So, what would our sets look like for the linguistic variable Ã?" }, { "code": null, "e": 4540, "s": 4441, "text": "Suppose a person is 163cm tall. For the variable Ã, it would be .27 median and .73 tall, that is:" }, { "code": null, "e": 4601, "s": 4540, "text": "μ_median(163) = triangular(163, 90, 130, 175) = 0.2666666..." }, { "code": null, "e": 4657, "s": 4601, "text": "μ_high(163) = triangular(163, 130, 175,220) = 0.7333..." }, { "code": null, "e": 4682, "s": 4657, "text": "Check out the code here!" }, { "code": null, "e": 4803, "s": 4682, "text": "But is is only the beginning of a huge knowledge field. If you want to know more about Fuzzy Logic and Fuzzy Systems...." }, { "code": null, "e": 4882, "s": 4803, "text": "But where are here to talk about time series, right? So let’s talk about time!" }, { "code": null, "e": 4984, "s": 4882, "text": "If you already know about time series, you can go to the next section, this one is very introductory!" }, { "code": null, "e": 5269, "s": 4984, "text": "Time series are sets of data representing the behavior of one (or more) random variable over time, and its main characteristic is that the successive records of this variable are not independent of each other and their analysis must take into account the order in that were collected." }, { "code": null, "e": 5524, "s": 5269, "text": "According to Ehlers (2009), “the neighboring observations are dependent and we are interested in analyzing and modeling this dependence”. What does that mean? That to predict future values of the time series I use past / lagged values of the same series." }, { "code": null, "e": 6182, "s": 5524, "text": "A simple example is the autoregressive AR(p) model, where p indicates the number of lagged variables used on forecasting. Given a time series X(t), where t indicates a moment in time, if we going to use only use a lag in the forecast then we have an AR(1) model, that would be something like X(t) = α·X(t-1) + ε, where X(t-1) is the lagged value, α is a coefficient adjusted by statistical methods and ε represents the noise or random error, which indicates the uncertainty associated with this forecast, ε ~N(0,1). If we want to use the last two lags on forecasting we will have an AR(2) model, which would be something like X(t) = α0·X(t-1) +α1·X(t-2) +ε." }, { "code": null, "e": 6451, "s": 6182, "text": "What is the amount of lags and what lags should be used? To do this, it is necessary to study the components of the time series and analyze their properties, using graphs such as ACF and PACF. Usually time series are modeled (using an additive model) at high level as:" }, { "code": null, "e": 6483, "s": 6451, "text": "X(t) =C(t) + T(t) + S(t) + R(t)" }, { "code": null, "e": 6490, "s": 6483, "text": "Where:" }, { "code": null, "e": 6511, "s": 6490, "text": "t is the time index;" }, { "code": null, "e": 6561, "s": 6511, "text": "X(t) is a point estimate of the series at time t;" }, { "code": null, "e": 6643, "s": 6561, "text": "C(t) is the cyclical component, foreseeable short / very short term fluctuations;" }, { "code": null, "e": 6847, "s": 6643, "text": "T(t) is the trend component, which indicates the long-term behavior of the series. Generally the tendency is of growth / rise or reduction / descent, otherwise it is said that the series has no tendency;" }, { "code": null, "e": 7192, "s": 6847, "text": "S(t) is the seasonal component, which is periodic fluctuations of medium and long term. A good example of seasonal component are ... guess what? The seasons of the year! These are intervals of 4 months that have a very characteristic of their own and are repeated annually — which makes any variable with this seasonality much more predictable." }, { "code": null, "e": 7307, "s": 7192, "text": "R(t) is the noise component, a random value with constant mean and variance. This random noise is not predictable!" }, { "code": null, "e": 7950, "s": 7307, "text": "Not all time series have trend or seasonality. Some series are known to be stationary, meaning that their average values are (more or less) constant. In non-stationary series the average changes over time. In the homocedastic series, the variance is constant and in the heteroskedastic series the variance changes over time. To summarize: stationary and homoskedastic time series are “well behaved” and simpler to predict, and non-stationary and heteroskedastic series are much more complex. In the latter case we can apply mathematical transformations (such as differentiation, Box-Cox, etc.) to make the series stationary and homoskedastic." }, { "code": null, "e": 8000, "s": 7950, "text": "But.... Where do fuzzy sets come into this story?" }, { "code": null, "e": 8290, "s": 8000, "text": "The use of fuzzy sets for modeling and predicting time series arises almost intuitively, first based on the ability of fuzzy models to approximate functions, but also on the readability of rules using linguistic variables that make them more accessible to experts and non-experts analysis." }, { "code": null, "e": 8888, "s": 8290, "text": "The pioneer work on fuzzy time series is Song and Chisson(1993) but here we present the evolution published by Chen(1996). The idea is to divide the Universe of Discourse from time series in intervals/partitions (the fuzzy sets), and learn how each area behaves (extracting rules through the time series patterns). The rules of these models tell how the partitions relate with themselves over the time, as values jump from one place to another. In other words: let’s create a linguistic variable to represent the numerical time series, and these areas will be the linguistic terms of our variable." }, { "code": null, "e": 9156, "s": 8888, "text": "When we create a linguistic variable to represent the universe of discourse, we create a “vocabulary,” and then the fuzzyfied series is composed of words in that vocabulary. The sequence of these words — the sentences or phrases — are the patterns we need to learned." }, { "code": null, "e": 9269, "s": 9156, "text": "To facilitate, I will divide the methodology of fuzzy time series into two procedures: training and forecasting." }, { "code": null, "e": 9447, "s": 9269, "text": "We will use in this tutorial a very known time series from the origins of the Fuzzy Time Series: the enrollments of Alabama University (Enrollments). You can see the data below:" }, { "code": null, "e": 9675, "s": 9447, "text": "1. Definition of the Universe of Discourse UFirst we need to know the universe of discourse U from the training data, such as U = [min(X), max(X)]. Usually we extrapolate the upper and lower bounds by 20%, as a security margin." }, { "code": null, "e": 10001, "s": 9675, "text": "2. Create the Linguistic Variable à (Universe of Discourse Partitioning)Now we need to split U on several overlapping intervals (a.k.a partitions) and create a fuzzy set for each one of them. The number of intervals is one of the most important parameters on Fuzzy Time Series and it will directly imply on model’s accuracy." }, { "code": null, "e": 10390, "s": 10001, "text": "Beyond the number of partitions, the way we split U also have great impact on accuracy. Hereafter we adopt the simplest method for partitioning, the Grid Partitioning, where all partitions have the same length and format. To know other partitioning methods click here. For our example data we will use a 10 partitions scheme, such that the linguistic variable be à = { A0, A1, ..., A9 }." }, { "code": null, "e": 10874, "s": 10390, "text": "3. FuzzyficationNow we can convert the numerical values of X(t) into fuzzy values of the linguistic variable Ã, giving rise to the fuzzy time series F(t). It is always good to remind that the fuzzy sets on à are overlapped, so for each x ∈ X(t) it is possible that it belongs to more than one fuzzy set Ai ∈ Ã. On Chen methods the things are a little bit simplier: just the maximum membership fuzzy set is choosen. However in other FTS methods all fuzzyfied values are considered." }, { "code": null, "e": 11044, "s": 10874, "text": "Using the Chen’s method the fuzzyfied values for our test data will be F(t) = { A1, A2, A2, A3, A4, A4, A4, A4, A5, A5, A5, A4, A4, A4, A4, A4, A5, A7, A8, A8, A8, A7 }." }, { "code": null, "e": 11339, "s": 11044, "text": "4. Creating the temporal patterns A temporal patterns indicates two fuzzy sets that appear sequentially on fuzzy time series F(t) and have the format Precedent →Consequent, where the precedent indicates a fuzzy set on time t and the consequent the fuzzy set that appears soon after on time t+1." }, { "code": null, "e": 11459, "s": 11339, "text": "For the previous example, the generated temporal patterns will be: A1→A2, A2→A2, A2→A3, A3→A4, A4→A4, ..., A8→A8, A8→A7" }, { "code": null, "e": 11811, "s": 11459, "text": "5. Creating the rulesOur model rules also have the format Precedent →Consequent. Given the previously generated temporal patterns we will group them by its precedents. Our model will contain a rule for each distinct precedent found, and the consequent of each rule will be the union of all consequents of each temporal pattern with the same precedent." }, { "code": null, "e": 11923, "s": 11811, "text": "For the previous example, the generated rules will be:A1 →A2A2 →A2,A3A3 →A4A4 →A4,A5A5 →A4,A5,A7A7 →A8A8 →A7,A8" }, { "code": null, "e": 12117, "s": 11923, "text": "The rule set is, in fact, out FTS model. They describe how our time series behaves and, if it was stationary enough (well behaved) we can use this model to forecast the next values on the time." }, { "code": null, "e": 12180, "s": 12117, "text": "An simple and readable model like that has another advantages:" }, { "code": null, "e": 12270, "s": 12180, "text": "a) it is very easy to parallelize/distribute, what makes it very attractive for big data;" }, { "code": null, "e": 12360, "s": 12270, "text": "b) it is very easy to update, what makes it very attractive for frequently-changing data." }, { "code": null, "e": 12406, "s": 12360, "text": "But how we can use this rules on forecasting?" }, { "code": null, "e": 12516, "s": 12406, "text": "Since we know the numerical value for time t, x(t) ∈ X(t), we now want to predict the next instant, x(t + 1)." }, { "code": null, "e": 12725, "s": 12516, "text": "1. Input value fuzzyficationThe input value x(t) will be converted into fuzzy values of the linguistic variable Ã, generating the value f(t). As in the training process only the most pertinent set is chosen." }, { "code": null, "e": 12850, "s": 12725, "text": "For the example data, for t = 1992 the value is x(t) = 18876. Fuzzyfying x(t) the set of most pertinent is A7, so f(t) = A7." }, { "code": null, "e": 13012, "s": 12850, "text": "2. Find the compatible rules Find the rule whose precedent is equal to f(t). The consequence of the rule will be the fuzzy forecast for t + 1, that is, f(t + 1)." }, { "code": null, "e": 13072, "s": 13012, "text": "For f(t) = A7 we have the rule A7 → A8. Then f(t + 1) = A8." }, { "code": null, "e": 13365, "s": 13072, "text": "3. DefuzzyficationNow you need to convert f(t + 1) to a numeric value. For this we use the center-of-mass method, where the numerical value is equal to the mean of the centers of the fuzzy sets of f(t + 1), that is x(t+1) = n−1∑ Ai, for i = 0..n-1 and n equal to the number of sets in f(t+1)." }, { "code": null, "e": 13424, "s": 13365, "text": "Since f(t + 1) has only one set, then x(t + 1) = 19366.46." }, { "code": null, "e": 13819, "s": 13424, "text": "This presented model is very simple, and I must say, archaic (it from 1996 !!!). But it is a good guide to understanding how fuzzy time series work. The most accurate methods now use more lags (this one use only the t-1 lag), weights in the rules (from the work of Yu (2005)), optimizers to find the best number of sets, lags, etc. In the next tutorials we will delve into more advanced models." }, { "code": null, "e": 13899, "s": 13819, "text": "All above explained procedures can be reproduced on this Google Colab notebook." }, { "code": null, "e": 13965, "s": 13899, "text": "Now it’s time to go play a little and get our hands dirty!!!! :-)" }, { "code": null, "e": 14326, "s": 13965, "text": "The pyFTS: Fuzzy Time Series for Python library is developed on MINDS — Machine Intelligence and Data Science of Federal University of Minas Gerais (UFMG) at Brazil, and is intended for students, researchers, data scientists or whose want to exploit the Fuzzy Time Series methods. PyFTS is a project in continuous development and all contributions are welcome!" }, { "code": null, "e": 14379, "s": 14326, "text": "Let’s know some of the main features of the library:" }, { "code": null, "e": 14392, "s": 14379, "text": "1. Test data" }, { "code": null, "e": 14646, "s": 14392, "text": "In the pyFTS.data package there are several datasets of common time series such as TAIEX, NASDAQ, S&P 500, passengers, etc. Each dataset has its own features — some are univariate, others multivariate, etc — but all of them basically have two functions:" }, { "code": null, "e": 14692, "s": 14646, "text": "get_data(): return the univariate time series" }, { "code": null, "e": 14743, "s": 14692, "text": "get_dataset(): return the multivariate time series" }, { "code": null, "e": 14808, "s": 14743, "text": "from pyFTS.data import Enrollmentstrain = Enrollments.get_data()" }, { "code": null, "e": 14832, "s": 14808, "text": "2. Data transformations" }, { "code": null, "e": 15039, "s": 14832, "text": "In the package pyFTS.common.Transformations several data transformations can be used for the pre-processing and/or post-processing data, which directly impacts the partitioning of the universe of discourse." }, { "code": null, "e": 15119, "s": 15039, "text": "from pyFTS.common import Transformationstdiff = Transformations.Differential(1)" }, { "code": null, "e": 15135, "s": 15119, "text": "3. Partitioners" }, { "code": null, "e": 15423, "s": 15135, "text": "In the pyFTS.partitioners package are the universe of discourse partitioners. Each partitioner has the function of representing the linguistic variable, creating the partitions of the Discourse Universe and its fuzzy sets. In all of them at least two constructor parameters are required:" }, { "code": null, "e": 15458, "s": 15423, "text": "data: (mandatory!) the train data;" }, { "code": null, "e": 15521, "s": 15458, "text": "npart: (mandatory!) the minimal number of fuzzy sets to build;" }, { "code": null, "e": 15696, "s": 15521, "text": "mf: the membership function that will be used on fuzzy sets, which by default is triangular (trimf). The various membership functions can be found in pyFTS.common.Membership;" }, { "code": null, "e": 15785, "s": 15696, "text": "transformation: if any transformation is used in the series, it should be reported here." }, { "code": null, "e": 15901, "s": 15785, "text": "from pyFTS.partitioners import Grid, Entropy, Util as pUtilfs = Grid.GridPartitioner(data=train, npart=20)print(fs)" }, { "code": null, "e": 16048, "s": 15901, "text": "We can explore several several alternatives for universe of discourse partitioners, each one of them with its own characteristics and performance." }, { "code": null, "e": 16077, "s": 16048, "text": "4. Fuzzy Time Series methods" }, { "code": null, "e": 16240, "s": 16077, "text": "The various methods are found in the package pyFTS.models. All methods inherit from the class common.fts.FTS. For the end user there are two main methods to know:" }, { "code": null, "e": 16619, "s": 16240, "text": "FTS.fit(data, partitioner=fs) : Trains the model from the training data on parameter data and the linguistic variable already constructed by the fs partitioner. It is advisable to study the help of this function because here it is already possible to do the distributed training using clusters dispy. As soon as possible also a version compatible with pySpark will be realeased." }, { "code": null, "e": 17102, "s": 16619, "text": "FTS.predict(data, type=’point’, steps_ahead=1): It uses the already trained model to make predictions from the lags contained in the data. There are three possible prediction types, indicated by the ‘type’ parameter: ‘point’ (default), ‘interval’ and ‘distribution’. One should be careful when choosing the method because not all of them work with all these types. Finally, the ‘steps_ahead’ parameter indicates the prediction horizon, or how many steps forward you want to predict." }, { "code": null, "e": 17235, "s": 17102, "text": "from pyFTS.models import chenmodel = chen.ConventionalFTS(partitioner=fs)model.fit(train)print(model)forecasts = model.predict(test)" }, { "code": null, "e": 17313, "s": 17235, "text": "There are several models to be explored, so give a look on the example codes." }, { "code": null, "e": 17511, "s": 17313, "text": "On the second part of this tutorial I’m talking about weighted methods, high order models, multivariate models and multi step forecasting. I also apply these models to forecast photovoltaic energy." }, { "code": null, "e": 17635, "s": 17511, "text": "The third part talks about interval and probabilistic forecasting, non-stationarity, concept drift and time variant models." }, { "code": null, "e": 17657, "s": 17635, "text": "Be sure to read them!" }, { "code": null, "e": 17859, "s": 17657, "text": "Chen Shyi-Ming. Forecasting enrollments based on fuzzy time series. Fuzzy sets and systems, vol. 81, number 3, pp. 311–319, 1996. URL: https://doi.org/10.1016/0165–0114(95)00220–0. Acess in 25/07/2018." }, { "code": null, "e": 18052, "s": 17859, "text": "Ehlers, R.S. Análise de séries temporais. Departamento de Estatística, Universidade Federal do Paraná. URL: http://conteudo.icmc.usp.br/pessoas/ehlers/stemp/stemp.pdf. Acess in 25/07/2018." }, { "code": null, "e": 18128, "s": 18052, "text": "Morettin, P.A. e Toloi, C.M.C. Análise de Séries Temporais. Blucher, 2004" }, { "code": null, "e": 18259, "s": 18128, "text": "Silva, P. C. L. et al. pyFTS: Fuzzy Time Series for Python, v4.0. URL: https://doi.org/10.5281/zenodo.597359. Acess in 25/07/2018." }, { "code": null, "e": 18457, "s": 18259, "text": "Song, Qiang; Chissom, Brad S. Fuzzy time series and its models. Fuzzy sets and systems, vol. 54, number 3, pp. 269–277, 1993. URL: https://doi.org/10.1016/0165-0114(93)90372-O. Acess in 25/07/2018." }, { "code": null, "e": 18694, "s": 18457, "text": "Yu, Hui-Kuang, Weighted fuzzy time series models for TAIEX forecasting. Physica A: Statistical Mechanics and its Applications, vol. 349, number 3, pp. 609–624, 2005. URL: https://doi.org/10.1016/j.physa.2004.11.006. Acess in 25/07/2018." } ]
Java do-while loop example
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. Following is the syntax of a do...while loop − do { // Statements }while(Boolean_expression); Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested. If the Boolean expression is true, the control jumps back up to do statement, and the statements in the loop execute again. This process repeats until the Boolean expression is false. Live Demo public class Test { public static void main(String args[]) { int x = 10; do { System.out.print("value of x : " + x ); x++; System.out.print("\n"); }while( x < 20 ); } } value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19
[ { "code": null, "e": 1182, "s": 1062, "text": "A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time." }, { "code": null, "e": 1229, "s": 1182, "text": "Following is the syntax of a do...while loop −" }, { "code": null, "e": 1279, "s": 1229, "text": "do {\n // Statements\n}while(Boolean_expression);" }, { "code": null, "e": 1419, "s": 1279, "text": "Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested." }, { "code": null, "e": 1603, "s": 1419, "text": "If the Boolean expression is true, the control jumps back up to do statement, and the statements in the loop execute again. This process repeats until the Boolean expression is false." }, { "code": null, "e": 1613, "s": 1603, "text": "Live Demo" }, { "code": null, "e": 1834, "s": 1613, "text": "public class Test {\n\n public static void main(String args[]) {\n int x = 10;\n do {\n System.out.print(\"value of x : \" + x );\n x++;\n System.out.print(\"\\n\");\n }while( x < 20 );\n }\n}" }, { "code": null, "e": 1994, "s": 1834, "text": "value of x : 10\nvalue of x : 11\nvalue of x : 12\nvalue of x : 13\nvalue of x : 14\nvalue of x : 15\nvalue of x : 16\nvalue of x : 17\nvalue of x : 18\nvalue of x : 19" } ]
DAX Filter - VALUES function
Returns a one-column table that contains the distinct values from the specified table or column. In other words, duplicate values are removed and only unique values are returned. VALUES (<TableNameOrColumnName>) TableNameOrColumnName The table or column from which unique values are to be returned. A column of unique values. You can use DAX VALUES function as an intermediate function, nested in a formula, to get a list of distinct values that can be counted, or used to filter or sum other values. When you use the DAX VALUES function in a context that has been filtered, such as in a PivotTable, the unique values returned by VALUES are affected by the filter. = COUNTROWS (VALUES (Sales[Salesperson ID])) Returns the number of rows that have unique Salesperson IDs. 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2180, "s": 2001, "text": "Returns a one-column table that contains the distinct values from the specified table or column. In other words, duplicate values are removed and only unique values are returned." }, { "code": null, "e": 2215, "s": 2180, "text": "VALUES (<TableNameOrColumnName>) \n" }, { "code": null, "e": 2237, "s": 2215, "text": "TableNameOrColumnName" }, { "code": null, "e": 2302, "s": 2237, "text": "The table or column from which unique values are to be returned." }, { "code": null, "e": 2329, "s": 2302, "text": "A column of unique values." }, { "code": null, "e": 2504, "s": 2329, "text": "You can use DAX VALUES function as an intermediate function, nested in a formula, to get a list of distinct values that can be counted, or used to filter or sum other values." }, { "code": null, "e": 2668, "s": 2504, "text": "When you use the DAX VALUES function in a context that has been filtered, such as in a PivotTable, the unique values returned by VALUES are affected by the filter." }, { "code": null, "e": 2714, "s": 2668, "text": "= COUNTROWS (VALUES (Sales[Salesperson ID])) " }, { "code": null, "e": 2775, "s": 2714, "text": "Returns the number of rows that have unique Salesperson IDs." }, { "code": null, "e": 2810, "s": 2775, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 2824, "s": 2810, "text": " Abhay Gadiya" }, { "code": null, "e": 2857, "s": 2824, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 2871, "s": 2857, "text": " Randy Minder" }, { "code": null, "e": 2906, "s": 2871, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 2920, "s": 2906, "text": " Randy Minder" }, { "code": null, "e": 2927, "s": 2920, "text": " Print" }, { "code": null, "e": 2938, "s": 2927, "text": " Add Notes" } ]
How should I validate an e-mail address in Android using Kotlin?.
This example demonstrates how to validate an e-mail address in Android using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="8dp" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:text="Tutorials Point" android:textAlignment="center" android:textColor="@android:color/holo_green_dark" android:textSize="32sp" android:textStyle="bold" /> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:hint="Enter Email Address" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/editText" android:layout_alignParentEnd="true" android:layout_marginTop="5dp" android:onClick="validateEmail" android:text="Validate" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android. import android.os.Bundle import android.view.View import android.widget.EditText import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { private lateinit var editText: EditText private lateinit var email: String private val emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" editText = findViewById(R.id.editText) email = editText.text.toString().trim() } fun validateEmail(view: View?) { if (email.matches(emailPattern.toRegex())) { Toast.makeText(applicationContext, "Valid email address", Toast.LENGTH_SHORT).show() } else { Toast.makeText(applicationContext, "Invalid email address", Toast.LENGTH_SHORT).show() } } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
[ { "code": null, "e": 1147, "s": 1062, "text": "This example demonstrates how to validate an e-mail address in Android using Kotlin." }, { "code": null, "e": 1276, "s": 1147, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1340, "s": 1276, "text": "Step 2 − Add the following code to res/layout/activity_main.xml" }, { "code": null, "e": 2543, "s": 1340, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"8dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n <EditText\n android:id=\"@+id/editText\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:hint=\"Enter Email Address\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/editText\"\n android:layout_alignParentEnd=\"true\"\n android:layout_marginTop=\"5dp\"\n android:onClick=\"validateEmail\"\n android:text=\"Validate\" />\n</RelativeLayout>" }, { "code": null, "e": 2614, "s": 2543, "text": "Step 3 − Add the following code to src/MainActivity.kt import android." }, { "code": null, "e": 3549, "s": 2614, "text": "import android.os.Bundle\nimport android.view.View\nimport android.widget.EditText\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n private lateinit var editText: EditText\n private lateinit var email: String\n private val emailPattern = \"[a-zA-Z0-9._-]+@[a-z]+\\\\.+[a-z]+\"\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n editText = findViewById(R.id.editText)\n email = editText.text.toString().trim()\n }\n fun validateEmail(view: View?) {\n if (email.matches(emailPattern.toRegex())) {\n Toast.makeText(applicationContext, \"Valid email address\",\n Toast.LENGTH_SHORT).show()\n } else {\n Toast.makeText(applicationContext, \"Invalid email address\",\n Toast.LENGTH_SHORT).show()\n }\n }\n}" }, { "code": null, "e": 3604, "s": 3549, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4271, "s": 3604, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4619, "s": 4271, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" } ]
Gii - Generating Module
Let us see how to generate a Module. Step 1 − To generate a module, open the module generation interface and fill in the form. Step 2 − Then, click the “Preview” button and “Generate”. Step 3 − We need to activate the module. Modify the modules application component in the config/web.php file. 'modules' => [ 'admin' => [ 'class' => 'app\modules\admin\Module', ], ], Step 4 − To check whether our newly generated module works, type the UR http://localhost:8080/index.php?r=admin/default/index in the web browser. Print Add Notes Bookmark this page
[ { "code": null, "e": 2870, "s": 2833, "text": "Let us see how to generate a Module." }, { "code": null, "e": 2960, "s": 2870, "text": "Step 1 − To generate a module, open the module generation interface and fill in the form." }, { "code": null, "e": 3018, "s": 2960, "text": "Step 2 − Then, click the “Preview” button and “Generate”." }, { "code": null, "e": 3128, "s": 3018, "text": "Step 3 − We need to activate the module. Modify the modules application component in the config/web.php file." }, { "code": null, "e": 3213, "s": 3128, "text": "'modules' => [\n 'admin' => [\n 'class' => 'app\\modules\\admin\\Module',\n ],\n]," }, { "code": null, "e": 3359, "s": 3213, "text": "Step 4 − To check whether our newly generated module works, type the UR http://localhost:8080/index.php?r=admin/default/index in the web browser." }, { "code": null, "e": 3366, "s": 3359, "text": " Print" }, { "code": null, "e": 3377, "s": 3366, "text": " Add Notes" } ]
Tryit Editor v3.7
Tryit: HTML small text
[]
How to create an S4 object in R?
To create an S4 object, we can use setClass function where we will pass the object name, column names, and the type of the data that will be stored in the columns. For example, if we want to create an S4 with name data and two numerical columns called by x and y then we can use setClass("data",representation(x1="numeric",x2="numeric")). > setClass("data1",representation(x1="numeric",x2="numeric")) > data1<-new("data1",x1=rnorm(20),x2=rexp(20,1.12)) > data1 An object of class "data1" Slot "x1": [1] -0.586187627 0.853689097 -0.602612795 -2.194235741 -1.318522292 [6] -0.984882420 0.273584140 0.364691611 1.025472248 1.198547297 [11] -0.709282551 -0.001441127 -0.201348012 1.296811172 1.520093861 [16] 2.071031215 0.472877022 0.616211695 0.642165615 -0.122773000 Slot "x2": [1] 0.38902289 0.20631450 0.02105516 0.24891420 2.37347874 0.43704064 [7] 0.79887672 1.95711822 0.69214407 1.17875759 0.10490338 0.69417206 [13] 0.60324447 0.03573967 0.27204874 1.63015638 1.94575940 2.97829841 [19] 0.22643380 2.06821215 > setClass("data2",representation(x1="integer",x2="numeric")) > data2<-new("data2",x1=rpois(200,5),x2=rexp(50,1.12)) > data2 An object of class "data2" Slot "x1": [1] 3 7 4 8 5 7 5 11 6 4 5 3 2 7 5 5 4 3 7 8 12 6 10 6 3 [26] 7 7 6 4 2 6 6 8 7 8 8 5 2 3 4 7 2 4 1 3 4 7 4 10 5 [51] 7 2 4 3 8 6 4 4 6 7 8 4 5 5 3 4 2 7 7 6 1 6 3 5 2 [76] 5 6 7 3 7 5 7 5 8 2 4 4 2 3 6 1 6 5 5 3 4 3 8 5 7 [101] 4 3 8 2 6 3 3 5 1 2 4 6 4 6 2 4 4 4 4 9 4 4 7 2 9 [126] 4 3 4 3 4 7 5 5 2 2 6 4 6 5 5 6 8 4 7 6 3 7 7 7 8 [151] 8 6 4 7 4 4 3 10 4 6 2 5 5 4 4 6 7 5 7 0 6 8 5 8 9 [176] 3 5 5 4 8 4 4 6 5 7 9 6 2 2 2 5 9 3 5 3 3 4 6 2 6 Slot "x2": [1] 0.03141964 0.49307236 0.31423727 0.43521757 0.52619093 0.70795201 [7] 0.35462825 0.59378101 0.10527933 0.70027538 0.44882733 0.43956142 [13] 0.09664605 0.50706106 1.65260142 0.36428909 0.61297587 1.01703946 [19] 0.89316946 0.59825470 1.32223944 1.77853473 0.19214180 4.76283291 [25] 0.51096582 1.07728540 0.94746461 1.03008930 0.80508219 2.91018171 [31] 0.13807893 0.98123535 0.71989867 1.32550897 0.86492233 0.06968105 [37] 0.75559512 0.27958713 0.18840316 1.39449247 3.78111847 0.26038046 [43] 0.02072275 0.81411699 0.89175522 0.13439256 1.16051005 1.00565524 [49] 0.44863428 0.59886756 > setClass("data3",representation(x1="character",x2="numeric")) > data3<-new("data3",x1=sample(LETTERS[1:4],50,replace=TRUE),x2=rexp(50,1.12)) > data3 An object of class "data3" Slot "x1": [1] "C" "D" "A" "C" "D" "D" "C" "D" "C" "A" "A" "B" "C" "D" "C" "D" "C" "A" "D" [20] "C" "C" "A" "B" "B" "C" "D" "D" "B" "B" "C" "A" "C" "D" "A" "C" "D" "A" "C" [39] "C" "C" "B" "C" "B" "B" "D" "C" "A" "C" "A" "A" Slot "x2": [1] 0.15262639 0.18257750 0.66531800 0.90077904 0.31199878 0.15326597 [7] 0.14915567 0.09891334 1.91290294 1.64658850 0.17738544 0.07428495 [13] 0.51221999 1.19112341 0.16764472 1.29586175 0.67945778 0.33704154 [19] 0.21145555 0.28791368 0.95651553 0.48383674 0.76274501 0.71038690 [25] 1.34688895 1.77748828 0.63969314 0.29701294 0.04734766 1.02116237 [31] 0.27368908 0.04268661 0.77449047 3.70772112 0.40526753 0.06333750 [37] 0.26435011 1.03701168 0.08280528 0.86331936 0.15271265 1.45303032 [43] 0.04458336 0.54749522 0.44025731 0.20837975 0.21421977 0.16732185 [49] 1.46172264 0.70931165 > setClass("data4",representation(x1="logical",x2="numeric")) > data4<-new("data4",x1=sample(as.logical(c(0,1)),50,replace=TRUE),x2=rnorm(50,1,0.50)) > data4 An object of class "data4" Slot "x1": [1] FALSE TRUE FALSE TRUE TRUE FALSE TRUE TRUE FALSE FALSE TRUE TRUE [13] TRUE TRUE FALSE FALSE TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE [25] TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE TRUE [37] TRUE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE TRUE FALSE FALSE [49] TRUE FALSE Slot "x2": [1] 1.4535492 0.8230134 0.9926188 0.9236218 0.9568131 1.2355998 [7] -0.2649343 1.4839302 0.6435250 0.8384010 1.4399601 1.3696312 [13] 0.2847440 0.6539318 1.2568808 1.4457016 1.1884043 1.3024577 [19] 1.5923689 1.2796569 0.9942924 0.6104080 0.4510600 0.9901056 [25] 0.9496257 1.1278555 0.5048898 1.0492706 1.5142966 0.8459955 [31] 1.4398791 1.0121801 0.9473674 0.2266796 1.3360711 0.2354370 [37] 0.4838408 1.4131759 0.1566150 1.4218652 1.1542315 2.0074517 [43] 1.0019310 0.3909861 0.6707586 0.9373494 1.4065083 0.1781948 [49] 1.4708116 1.1577926
[ { "code": null, "e": 1401, "s": 1062, "text": "To create an S4 object, we can use setClass function where we will pass the object name, column names, and the type of the data that will be stored in the columns. For example, if we want to create an S4 with name data and two numerical columns called by x and y then we can use setClass(\"data\",representation(x1=\"numeric\",x2=\"numeric\"))." }, { "code": null, "e": 1523, "s": 1401, "text": "> setClass(\"data1\",representation(x1=\"numeric\",x2=\"numeric\"))\n> data1<-new(\"data1\",x1=rnorm(20),x2=rexp(20,1.12))\n> data1" }, { "code": null, "e": 2078, "s": 1523, "text": "An object of class \"data1\"\nSlot \"x1\":\n[1] -0.586187627 0.853689097 -0.602612795 -2.194235741 -1.318522292\n[6] -0.984882420 0.273584140 0.364691611 1.025472248 1.198547297\n[11] -0.709282551 -0.001441127 -0.201348012 1.296811172 1.520093861\n[16] 2.071031215 0.472877022 0.616211695 0.642165615 -0.122773000\n\nSlot \"x2\":\n[1] 0.38902289 0.20631450 0.02105516 0.24891420 2.37347874 0.43704064\n[7] 0.79887672 1.95711822 0.69214407 1.17875759 0.10490338 0.69417206\n[13] 0.60324447 0.03573967 0.27204874 1.63015638 1.94575940 2.97829841\n[19] 0.22643380 2.06821215" }, { "code": null, "e": 2203, "s": 2078, "text": "> setClass(\"data2\",representation(x1=\"integer\",x2=\"numeric\"))\n> data2<-new(\"data2\",x1=rpois(200,5),x2=rexp(50,1.12))\n> data2" }, { "code": null, "e": 3294, "s": 2203, "text": "An object of class \"data2\"\nSlot \"x1\":\n[1] 3 7 4 8 5 7 5 11 6 4 5 3 2 7 5 5 4 3 7 8 12 6 10 6 3\n[26] 7 7 6 4 2 6 6 8 7 8 8 5 2 3 4 7 2 4 1 3 4 7 4 10 5\n[51] 7 2 4 3 8 6 4 4 6 7 8 4 5 5 3 4 2 7 7 6 1 6 3 5 2\n[76] 5 6 7 3 7 5 7 5 8 2 4 4 2 3 6 1 6 5 5 3 4 3 8 5 7\n[101] 4 3 8 2 6 3 3 5 1 2 4 6 4 6 2 4 4 4 4 9 4 4 7 2 9\n[126] 4 3 4 3 4 7 5 5 2 2 6 4 6 5 5 6 8 4 7 6 3 7 7 7 8\n[151] 8 6 4 7 4 4 3 10 4 6 2 5 5 4 4 6 7 5 7 0 6 8 5 8 9\n[176] 3 5 5 4 8 4 4 6 5 7 9 6 2 2 2 5 9 3 5 3 3 4 6 2 6\n\nSlot \"x2\":\n[1] 0.03141964 0.49307236 0.31423727 0.43521757 0.52619093 0.70795201\n[7] 0.35462825 0.59378101 0.10527933 0.70027538 0.44882733 0.43956142\n[13] 0.09664605 0.50706106 1.65260142 0.36428909 0.61297587 1.01703946\n[19] 0.89316946 0.59825470 1.32223944 1.77853473 0.19214180 4.76283291\n[25] 0.51096582 1.07728540 0.94746461 1.03008930 0.80508219 2.91018171\n[31] 0.13807893 0.98123535 0.71989867 1.32550897 0.86492233 0.06968105\n[37] 0.75559512 0.27958713 0.18840316 1.39449247 3.78111847 0.26038046\n[43] 0.02072275 0.81411699 0.89175522 0.13439256 1.16051005 1.00565524\n[49] 0.44863428 0.59886756" }, { "code": null, "e": 3445, "s": 3294, "text": "> setClass(\"data3\",representation(x1=\"character\",x2=\"numeric\"))\n> data3<-new(\"data3\",x1=sample(LETTERS[1:4],50,replace=TRUE),x2=rexp(50,1.12))\n> data3" }, { "code": null, "e": 4302, "s": 3445, "text": "An object of class \"data3\"\nSlot \"x1\":\n[1] \"C\" \"D\" \"A\" \"C\" \"D\" \"D\" \"C\" \"D\" \"C\" \"A\" \"A\" \"B\" \"C\" \"D\" \"C\" \"D\" \"C\" \"A\" \"D\"\n[20] \"C\" \"C\" \"A\" \"B\" \"B\" \"C\" \"D\" \"D\" \"B\" \"B\" \"C\" \"A\" \"C\" \"D\" \"A\" \"C\" \"D\" \"A\" \"C\"\n[39] \"C\" \"C\" \"B\" \"C\" \"B\" \"B\" \"D\" \"C\" \"A\" \"C\" \"A\" \"A\"\n\nSlot \"x2\":\n[1] 0.15262639 0.18257750 0.66531800 0.90077904 0.31199878 0.15326597\n[7] 0.14915567 0.09891334 1.91290294 1.64658850 0.17738544 0.07428495\n[13] 0.51221999 1.19112341 0.16764472 1.29586175 0.67945778 0.33704154\n[19] 0.21145555 0.28791368 0.95651553 0.48383674 0.76274501 0.71038690\n[25] 1.34688895 1.77748828 0.63969314 0.29701294 0.04734766 1.02116237\n[31] 0.27368908 0.04268661 0.77449047 3.70772112 0.40526753 0.06333750\n[37] 0.26435011 1.03701168 0.08280528 0.86331936 0.15271265 1.45303032\n[43] 0.04458336 0.54749522 0.44025731 0.20837975 0.21421977 0.16732185\n[49] 1.46172264 0.70931165" }, { "code": null, "e": 4460, "s": 4302, "text": "> setClass(\"data4\",representation(x1=\"logical\",x2=\"numeric\"))\n> data4<-new(\"data4\",x1=sample(as.logical(c(0,1)),50,replace=TRUE),x2=rnorm(50,1,0.50))\n> data4" }, { "code": null, "e": 5350, "s": 4460, "text": "An object of class \"data4\"\nSlot \"x1\":\n[1] FALSE TRUE FALSE TRUE TRUE FALSE TRUE TRUE FALSE FALSE TRUE TRUE\n[13] TRUE TRUE FALSE FALSE TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE\n[25] TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE TRUE\n[37] TRUE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE TRUE FALSE FALSE\n[49] TRUE FALSE\n\nSlot \"x2\":\n[1] 1.4535492 0.8230134 0.9926188 0.9236218 0.9568131 1.2355998\n[7] -0.2649343 1.4839302 0.6435250 0.8384010 1.4399601 1.3696312\n[13] 0.2847440 0.6539318 1.2568808 1.4457016 1.1884043 1.3024577\n[19] 1.5923689 1.2796569 0.9942924 0.6104080 0.4510600 0.9901056\n[25] 0.9496257 1.1278555 0.5048898 1.0492706 1.5142966 0.8459955\n[31] 1.4398791 1.0121801 0.9473674 0.2266796 1.3360711 0.2354370\n[37] 0.4838408 1.4131759 0.1566150 1.4218652 1.1542315 2.0074517\n[43] 1.0019310 0.3909861 0.6707586 0.9373494 1.4065083 0.1781948\n[49] 1.4708116 1.1577926" } ]
Reverse an array in C++
The article showcase an array to be reversed in descending order using the C++ coding wherein the highest index is swapped to lowest index consequently by traversing the array in the loop. Live Demo #include <iostream> #include <algorithm> using namespace std; void reverseArray(int arr[], int n){ for (int low = 0, high = n - 1; low < high; low++, high--){ swap(arr[low], arr[high]); } for (int i = 0; i < n; i++){ cout << arr[i] << " "; } } int main(){ int arrInput[] = { 11, 12, 13, 14, 15 }; cout<<endl<<"Array::"; for (int i = 0; i < 5; i++){ cout << arrInput[i] << " "; } int n = sizeof(arrInput)/sizeof(arrInput[0]); cout<<endl<<"Reversed::"; reverseArray(arrInput, n); return 0; } As the integer type of array supplied in a bid to be reversed in descending order, the following yields as ; Array::11 12 13 14 15 Reversed::15 14 13 12 11
[ { "code": null, "e": 1251, "s": 1062, "text": "The article showcase an array to be reversed in descending order using the C++ coding wherein the highest index is swapped to lowest index consequently by traversing the array in the loop." }, { "code": null, "e": 1262, "s": 1251, "text": " Live Demo" }, { "code": null, "e": 1806, "s": 1262, "text": "#include <iostream>\n#include <algorithm>\nusing namespace std;\nvoid reverseArray(int arr[], int n){\n for (int low = 0, high = n - 1; low < high; low++, high--){\n swap(arr[low], arr[high]);\n }\n for (int i = 0; i < n; i++){\n cout << arr[i] << \" \";\n }\n}\nint main(){\n int arrInput[] = { 11, 12, 13, 14, 15 };\n cout<<endl<<\"Array::\";\n for (int i = 0; i < 5; i++){\n cout << arrInput[i] << \" \";\n }\n int n = sizeof(arrInput)/sizeof(arrInput[0]);\n cout<<endl<<\"Reversed::\";\n reverseArray(arrInput, n);\n return 0;\n}" }, { "code": null, "e": 1915, "s": 1806, "text": "As the integer type of array supplied in a bid to be reversed in descending order, the following yields as ;" }, { "code": null, "e": 1962, "s": 1915, "text": "Array::11 12 13 14 15\nReversed::15 14 13 12 11" } ]
What is strncat() Function in C language?
The C library function char *strncat(char *dest, const char *src, size_t n) appends the string pointed to by src to the end of the string pointed to by dest up to n characters long. An array of characters is called a string. Following is the declaration for an array − char stringname [size]; For example: char string[50]; string of length 50 characters Using single character constant − char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’} Using string constants − char string[10] = "Hello":; Accessing − There is a control string "%s" used for accessing the string till it encounters ‘\0’. This is used for combining or concatenating n characters of one string into another. This is used for combining or concatenating n characters of one string into another. The length of the destination string is greater than the source string. The length of the destination string is greater than the source string. The result concatenated string will be in the source string. The result concatenated string will be in the source string. The syntax is given below − strncat (Destination String, Source string,n); The following program shows the usage of strncat() function − Live Demo #include <string.h> main ( ){ char a [30] = "Hello \n"; char b [20] = "Good Morning \n"; strncat (a,b,4); a [9] = "\0"; printf("concatenated string = %s", a); } When the above program is executed, it produces the following result − Concatenated string = Hello Good. Let’s see another example − Given below is the C program to concatenate n characters from source string to destination string using strncat library function − Live Demo #include<stdio.h> #include<string.h> void main(){ //Declaring source and destination strings// char source[45],destination[50]; //Reading source string and destination string from user// printf("Enter the source string :"); gets(source); printf("Enter the destination string before :"); gets(destination); //Concatenate all the above results// destination[2]='\0'; strncat(destination,source,2); strncat(destination,&source[4],1); //Printing destination string// printf("The modified destination string :"); puts(destination); } When the above program is executed, it produces the following result − Enter the source string :Tutorials Point Enter the destination string before :Tutorials Point C Programming The modified destination string :TuTur
[ { "code": null, "e": 1244, "s": 1062, "text": "The C library function char *strncat(char *dest, const char *src, size_t n) appends the string pointed to by src to the end of the string pointed to by dest up to n characters long." }, { "code": null, "e": 1287, "s": 1244, "text": "An array of characters is called a string." }, { "code": null, "e": 1331, "s": 1287, "text": "Following is the declaration for an array −" }, { "code": null, "e": 1355, "s": 1331, "text": "char stringname [size];" }, { "code": null, "e": 1416, "s": 1355, "text": "For example: char string[50]; string of length 50 characters" }, { "code": null, "e": 1450, "s": 1416, "text": "Using single character constant −" }, { "code": null, "e": 1501, "s": 1450, "text": "char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\\0’}" }, { "code": null, "e": 1526, "s": 1501, "text": "Using string constants −" }, { "code": null, "e": 1554, "s": 1526, "text": "char string[10] = \"Hello\":;" }, { "code": null, "e": 1652, "s": 1554, "text": "Accessing − There is a control string \"%s\" used for accessing the string till it encounters ‘\\0’." }, { "code": null, "e": 1737, "s": 1652, "text": "This is used for combining or concatenating n characters of one string into another." }, { "code": null, "e": 1822, "s": 1737, "text": "This is used for combining or concatenating n characters of one string into another." }, { "code": null, "e": 1894, "s": 1822, "text": "The length of the destination string is greater than the source string." }, { "code": null, "e": 1966, "s": 1894, "text": "The length of the destination string is greater than the source string." }, { "code": null, "e": 2027, "s": 1966, "text": "The result concatenated string will be in the source string." }, { "code": null, "e": 2088, "s": 2027, "text": "The result concatenated string will be in the source string." }, { "code": null, "e": 2116, "s": 2088, "text": "The syntax is given below −" }, { "code": null, "e": 2163, "s": 2116, "text": "strncat (Destination String, Source string,n);" }, { "code": null, "e": 2225, "s": 2163, "text": "The following program shows the usage of strncat() function −" }, { "code": null, "e": 2236, "s": 2225, "text": " Live Demo" }, { "code": null, "e": 2412, "s": 2236, "text": "#include <string.h>\nmain ( ){\n char a [30] = \"Hello \\n\";\n char b [20] = \"Good Morning \\n\";\n strncat (a,b,4);\n a [9] = \"\\0\";\n printf(\"concatenated string = %s\", a);\n}" }, { "code": null, "e": 2483, "s": 2412, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2517, "s": 2483, "text": "Concatenated string = Hello Good." }, { "code": null, "e": 2545, "s": 2517, "text": "Let’s see another example −" }, { "code": null, "e": 2676, "s": 2545, "text": "Given below is the C program to concatenate n characters from source string to destination string using strncat library function −" }, { "code": null, "e": 2687, "s": 2676, "text": " Live Demo" }, { "code": null, "e": 3258, "s": 2687, "text": "#include<stdio.h>\n#include<string.h>\nvoid main(){\n //Declaring source and destination strings//\n char source[45],destination[50];\n //Reading source string and destination string from user//\n printf(\"Enter the source string :\");\n gets(source);\n printf(\"Enter the destination string before :\");\n gets(destination);\n //Concatenate all the above results//\n destination[2]='\\0';\n strncat(destination,source,2);\n strncat(destination,&source[4],1);\n //Printing destination string//\n printf(\"The modified destination string :\");\n puts(destination);\n}" }, { "code": null, "e": 3329, "s": 3258, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 3476, "s": 3329, "text": "Enter the source string :Tutorials Point\nEnter the destination string before :Tutorials Point C Programming\nThe modified destination string :TuTur" } ]
Python | os.path.lexists() method - GeeksforGeeks
12 Jun, 2019 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. os.path module is sub module of OS module in python used for common path name manipulation. os.path.lexists() method in Python is used to check whether the given path exists or not. Unlike os.path.exists() method, it returns True for broken symbolic link. This method behaves similar to os.path.exists() on the platform where os.path.lstat() method is not available. Syntax: os.path.lexists(path) 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. Return Type: This method returns a Boolean value of class bool. This method returns True if path exists otherwise returns False. It will return True for broken symbolic links. # Python program to explain os.path.lexists() method # importing os.path module import os.path # Pathpath = '/home/User/Desktop' # Check whether the Given# path exists or notpathExists = os.path.lexists(path)print(pathExists) # Pathpath = '/home/User/Downloads/file.txt' # Check whether the specified# path exists or notpathExists = os.path.lexists(path)print(pathExists) # os.path.lexists() method# will also return True if# the given path is# broken symbolic link True False Reference: https://docs.python.org/3/library/os.path.html Python OS-path-module python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Bar Plot in Matplotlib Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Python - Call function from another file loops in python Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method Python Lambda Functions
[ { "code": null, "e": 23901, "s": 23873, "text": "\n12 Jun, 2019" }, { "code": null, "e": 24212, "s": 23901, "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. os.path module is sub module of OS module in python used for common path name manipulation." }, { "code": null, "e": 24376, "s": 24212, "text": "os.path.lexists() method in Python is used to check whether the given path exists or not. Unlike os.path.exists() method, it returns True for broken symbolic link." }, { "code": null, "e": 24487, "s": 24376, "text": "This method behaves similar to os.path.exists() on the platform where os.path.lstat() method is not available." }, { "code": null, "e": 24517, "s": 24487, "text": "Syntax: os.path.lexists(path)" }, { "code": null, "e": 24660, "s": 24517, "text": "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." }, { "code": null, "e": 24836, "s": 24660, "text": "Return Type: This method returns a Boolean value of class bool. This method returns True if path exists otherwise returns False. It will return True for broken symbolic links." }, { "code": "# Python program to explain os.path.lexists() method # importing os.path module import os.path # Pathpath = '/home/User/Desktop' # Check whether the Given# path exists or notpathExists = os.path.lexists(path)print(pathExists) # Pathpath = '/home/User/Downloads/file.txt' # Check whether the specified# path exists or notpathExists = os.path.lexists(path)print(pathExists) # os.path.lexists() method# will also return True if# the given path is# broken symbolic link", "e": 25313, "s": 24836, "text": null }, { "code": null, "e": 25325, "s": 25313, "text": "True\nFalse\n" }, { "code": null, "e": 25383, "s": 25325, "text": "Reference: https://docs.python.org/3/library/os.path.html" }, { "code": null, "e": 25405, "s": 25383, "text": "Python OS-path-module" }, { "code": null, "e": 25422, "s": 25405, "text": "python-os-module" }, { "code": null, "e": 25429, "s": 25422, "text": "Python" }, { "code": null, "e": 25527, "s": 25429, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25536, "s": 25527, "text": "Comments" }, { "code": null, "e": 25549, "s": 25536, "text": "Old Comments" }, { "code": null, "e": 25585, "s": 25549, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 25608, "s": 25585, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 25647, "s": 25608, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25680, "s": 25647, "text": "Python | Convert set into a list" }, { "code": null, "e": 25729, "s": 25680, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 25770, "s": 25729, "text": "Python - Call function from another file" }, { "code": null, "e": 25786, "s": 25770, "text": "loops in python" }, { "code": null, "e": 25837, "s": 25786, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 25869, "s": 25837, "text": "Python Dictionary keys() method" } ]
Interface Arduino with LoRa module
In this article we will see how to interface Arduino with the LoRa module E32. LoRa stands for Long Range. It uses license-free sub-GHz RF bands for operation. These bands are different in different countries. In India, the permissible band is 865-867 MHz. LoRa is very ideal for IoT applications thanks to its long range and low power consumption. However, the achievable data rates are limited (0.3 to 27 kbits/second). Longer the range, lower the data rate. The E32 module that we will use looks like the one below. Depending on the frequency the module variant changes. For example, the one shown below is E32-TTL-100, which operates from 410-441 MHz. Similarly, the E32 module operating from 862 to 893 MHz is E32-868T30D. Similarly, there may be other variants for other frequencies. The E32 module works on UART (as you can see from the RX and TX pins on the module). It is based on SEMTECH's SX1276 RF chip. There are two configuration pins (M0 and M1),which together determine four operating modes. You can find more detailed description of these modes in the user manual. In this tutorial, we will work with the Normal mode only, on both the receiver and the transmitter, i.e., we will set both M0 and M1 to 0. Note that E32 module can be configured only in the following mode − M0 and M1 are both set to 1 (HIGH) M0 and M1 are both set to 1 (HIGH) Serial configuration is 8N1, with baud rate of 9600. Serial configuration is 8N1, with baud rate of 9600. The parameter setting command of E32 is 6 bytes long. The bytes are − Byte 0 − It can be either 0xC0 or 0xC2. C0 tells the module that the settings have to be preserved even after power down. C2 means that settings need not be remembered after power down. Byte 0 − It can be either 0xC0 or 0xC2. C0 tells the module that the settings have to be preserved even after power down. C2 means that settings need not be remembered after power down. Bytes 1 and 2 − These dictate the address of the module. Byte 1 is the higher byte of the address and byte 2 is the lower byte of the address. You can keep any values you wish. But keep distinct values for distinct modules. Bytes 1 and 2 − These dictate the address of the module. Byte 1 is the higher byte of the address and byte 2 is the lower byte of the address. You can keep any values you wish. But keep distinct values for distinct modules. Byte 3 − This byte dictates the data transfer parameters (both UART and air data transfer). The description of the individual bits can be obtained from the user manual. Byte 3 − This byte dictates the data transfer parameters (both UART and air data transfer). The description of the individual bits can be obtained from the user manual. Byte 4 − This byte dictates the operating frequency of LoRa. For different modules there are different default frequencies. For example, the module 868T30D has the default frequency of 868 MHz, but the frequency range is 862 to 893 MHz. To adjust the frequency to a number other than the default, you use this byte. Each module’s user manual tells you how to adjust this byte to get the desired frequency. The general rules are also mentioned in the global user manual. Byte 4 − This byte dictates the operating frequency of LoRa. For different modules there are different default frequencies. For example, the module 868T30D has the default frequency of 868 MHz, but the frequency range is 862 to 893 MHz. To adjust the frequency to a number other than the default, you use this byte. Each module’s user manual tells you how to adjust this byte to get the desired frequency. The general rules are also mentioned in the global user manual. Byte 5 − This byte contains various transmission related parameters, like mode (transparent or fixed), transmission power, etc. You can refer to the user manual for more details (the details are too large to reproduce here). However, this byte can be generally left to the default value (the default is 0x44 for most modules, but you can check your particular model’s user manual). Byte 5 − This byte contains various transmission related parameters, like mode (transparent or fixed), transmission power, etc. You can refer to the user manual for more details (the details are too large to reproduce here). However, this byte can be generally left to the default value (the default is 0x44 for most modules, but you can check your particular model’s user manual). The circuit diagram is shown below for one end (transmitter). The circuit will be exactly the same on the receiving side. Note that you need to get an antenna for the frequency range of your LoRa module. In this example, we are using a 433 MHz module (E32-TTL-100). If you are using a module of a different frequency, you may want an antenna of that same frequency. The connections between Arduino and LoRa module are quote straightforward. M0, M1, RXD and TXD are to be connected to 4 GPIOs (we have connected them to 11, 10, 9 and 8 respectively). Vcc is connected to 5V and GND to GND. Please note that on Arduino, pin 8 will be RX (since it is connected to TX of the LoRa module), and pin 9 will be TX. The code is given below (if you are using a board other than Arduino Uno, all digital pins may not support SoftwareSerial. Read the limitations of SoftwareSerial here) − // (Send and Receive) #include <SoftwareSerial.h> SoftwareSerial loraSerial(8,9); //RX, TX #define M0 11 #define M1 10 void setup() { Serial.begin(9600); pinMode(M0, OUTPUT); pinMode(M1, OUTPUT); //Set M0 and M1 to high for parameter setting digitalWrite(M0, HIGH); digitalWrite(M1, HIGH); loraSerial.begin(9600); while (loraSerial.available() && loraSerial.read()); //Send configuration commands to the module uint8_t config_struct[6]; config_struct[0] = 0xC0; //Store in internal flash config_struct[1] = 0x00; // Address High, set a different value on the receiving side config_struct[2] = 0x00; //Address Low config_struct[3] = 0x35; //8N1, 57600 Baud rate, 19.2 kbps Air data rate config_struct[4] = 0x17; //433 MHz config_struct[5] = 0x44; //Default Options loraSerial.write(config_struct,6); delay(2000); Serial.println("Config Complete"); digitalWrite(M0, LOW); digitalWrite(M1, LOW); loraSerial.begin(57600); } void loop() { if(Serial.available() > 0){ char input = Serial.read(); loraSerial.print(input); } if(loraSerial.available() > 0){ char input = loraSerial.read(); Serial.print(input); } } As you can see, in the setup, we first set M0 and M1 to HIGH, because we want to configure the LoRa module. The config struct (or rather array) is constructed (please remember to set a different value of the address on the receiving side). The comments explain the meaning of each byte’s value. You can also refer to E32-TTL-100’s user manual for more clarification here. Once the parameters are set, the M0 and M1 pins are set to LOW (Normal mode), and the baud rate of LoRa is changed to 57600 (because that’s what is configured via the parameters). Within the loop, we take Serial input from the user. Whatever the user sends gets transmitted over LoRa, and whatever is received over LoRa is printed over the Serial Monitor. Thus, if you give a Serial input to the Arduino, the same text should get printed on the Serial Monitor of the receiving side, and if they type something, it should be visible on your Serial Monitor. Go ahead and explore different configurations of the LoRa module, and also different commands that you can send to the module.
[ { "code": null, "e": 1523, "s": 1062, "text": "In this article we will see how to interface Arduino with the LoRa module E32. LoRa stands for Long Range. It uses license-free sub-GHz RF bands for operation. These bands are different in different countries. In India, the permissible band is 865-867 MHz. LoRa is very ideal for IoT applications thanks to its long range and low power consumption. However, the achievable data rates are limited (0.3 to 27 kbits/second). Longer the range, lower the data rate." }, { "code": null, "e": 1852, "s": 1523, "text": "The E32 module that we will use looks like the one below. Depending on the frequency the module variant changes. For example, the one shown below is E32-TTL-100, which operates from 410-441 MHz. Similarly, the E32 module operating from 862 to 893 MHz is E32-868T30D. Similarly, there may be other variants for other frequencies." }, { "code": null, "e": 2070, "s": 1852, "text": "The E32 module works on UART (as you can see from the RX and TX pins on the module). It is based on SEMTECH's SX1276 RF chip. There are two configuration pins (M0 and M1),which together determine four operating modes." }, { "code": null, "e": 2283, "s": 2070, "text": "You can find more detailed description of these modes in the user manual. In this tutorial, we will work with the Normal mode only, on both the receiver and the transmitter, i.e., we will set both M0 and M1 to 0." }, { "code": null, "e": 2351, "s": 2283, "text": "Note that E32 module can be configured only in the following mode −" }, { "code": null, "e": 2386, "s": 2351, "text": "M0 and M1 are both set to 1 (HIGH)" }, { "code": null, "e": 2421, "s": 2386, "text": "M0 and M1 are both set to 1 (HIGH)" }, { "code": null, "e": 2474, "s": 2421, "text": "Serial configuration is 8N1, with baud rate of 9600." }, { "code": null, "e": 2527, "s": 2474, "text": "Serial configuration is 8N1, with baud rate of 9600." }, { "code": null, "e": 2597, "s": 2527, "text": "The parameter setting command of E32 is 6 bytes long. The bytes are −" }, { "code": null, "e": 2783, "s": 2597, "text": "Byte 0 − It can be either 0xC0 or 0xC2. C0 tells the module that the settings have to be preserved even after power down. C2 means that settings need not be remembered after power down." }, { "code": null, "e": 2969, "s": 2783, "text": "Byte 0 − It can be either 0xC0 or 0xC2. C0 tells the module that the settings have to be preserved even after power down. C2 means that settings need not be remembered after power down." }, { "code": null, "e": 3193, "s": 2969, "text": "Bytes 1 and 2 − These dictate the address of the module. Byte 1 is the higher byte of the address and byte 2 is the lower byte of the address. You can keep any values you wish. But keep distinct values for distinct modules." }, { "code": null, "e": 3417, "s": 3193, "text": "Bytes 1 and 2 − These dictate the address of the module. Byte 1 is the higher byte of the address and byte 2 is the lower byte of the address. You can keep any values you wish. But keep distinct values for distinct modules." }, { "code": null, "e": 3586, "s": 3417, "text": "Byte 3 − This byte dictates the data transfer parameters (both UART and air data transfer). The description of the individual bits can be obtained from the user manual." }, { "code": null, "e": 3755, "s": 3586, "text": "Byte 3 − This byte dictates the data transfer parameters (both UART and air data transfer). The description of the individual bits can be obtained from the user manual." }, { "code": null, "e": 4225, "s": 3755, "text": "Byte 4 − This byte dictates the operating frequency of LoRa. For different modules there are different default frequencies. For example, the module 868T30D has the default frequency of 868 MHz, but the frequency range is 862 to 893 MHz. To adjust the frequency to a number other than the default, you use this byte. Each module’s user manual tells you how to adjust this byte to get the desired frequency. The general rules are also mentioned in the global user manual." }, { "code": null, "e": 4695, "s": 4225, "text": "Byte 4 − This byte dictates the operating frequency of LoRa. For different modules there are different default frequencies. For example, the module 868T30D has the default frequency of 868 MHz, but the frequency range is 862 to 893 MHz. To adjust the frequency to a number other than the default, you use this byte. Each module’s user manual tells you how to adjust this byte to get the desired frequency. The general rules are also mentioned in the global user manual." }, { "code": null, "e": 5077, "s": 4695, "text": "Byte 5 − This byte contains various transmission related parameters, like mode (transparent or fixed), transmission power, etc. You can refer to the user manual for more details (the details are too large to reproduce here). However, this byte can be generally left to the default value (the default is 0x44 for most modules, but you can check your particular model’s user manual)." }, { "code": null, "e": 5459, "s": 5077, "text": "Byte 5 − This byte contains various transmission related parameters, like mode (transparent or fixed), transmission power, etc. You can refer to the user manual for more details (the details are too large to reproduce here). However, this byte can be generally left to the default value (the default is 0x44 for most modules, but you can check your particular model’s user manual)." }, { "code": null, "e": 5581, "s": 5459, "text": "The circuit diagram is shown below for one end (transmitter). The circuit will be exactly the same on the receiving side." }, { "code": null, "e": 5825, "s": 5581, "text": "Note that you need to get an antenna for the frequency range of your LoRa module. In this example, we are using a 433 MHz module (E32-TTL-100). If you are using a module of a different frequency, you may want an antenna of that same frequency." }, { "code": null, "e": 6166, "s": 5825, "text": "The connections between Arduino and LoRa module are quote straightforward. M0, M1, RXD and TXD are to be connected to 4 GPIOs (we have connected them to 11, 10, 9 and 8 respectively). Vcc is connected to 5V and GND to GND. Please note that on Arduino, pin 8 will be RX (since it is connected to TX of the LoRa module), and pin 9 will be TX." }, { "code": null, "e": 6336, "s": 6166, "text": "The code is given below (if you are using a board other than Arduino Uno, all digital pins may not support SoftwareSerial. Read the limitations of SoftwareSerial here) −" }, { "code": null, "e": 7554, "s": 6336, "text": "// (Send and Receive)\n#include <SoftwareSerial.h>\nSoftwareSerial loraSerial(8,9); //RX, TX\n\n#define M0 11\n#define M1 10\n\nvoid setup() {\n Serial.begin(9600);\n pinMode(M0, OUTPUT);\n pinMode(M1, OUTPUT);\n\n //Set M0 and M1 to high for parameter setting\n digitalWrite(M0, HIGH);\n digitalWrite(M1, HIGH);\n\n loraSerial.begin(9600);\n while (loraSerial.available() && loraSerial.read());\n\n //Send configuration commands to the module\n uint8_t config_struct[6];\n config_struct[0] = 0xC0; //Store in internal flash\n config_struct[1] = 0x00; // Address High, set a different value on the receiving side\n config_struct[2] = 0x00; //Address Low\n config_struct[3] = 0x35; //8N1, 57600 Baud rate, 19.2 kbps Air data rate\n config_struct[4] = 0x17; //433 MHz\n config_struct[5] = 0x44; //Default Options\n\n loraSerial.write(config_struct,6);\n delay(2000);\n\n Serial.println(\"Config Complete\");\n digitalWrite(M0, LOW);\n digitalWrite(M1, LOW);\n loraSerial.begin(57600);\n\n}\n\nvoid loop() {\n if(Serial.available() > 0){\n char input = Serial.read();\n loraSerial.print(input);\n }\n\n if(loraSerial.available() > 0){\n char input = loraSerial.read();\n Serial.print(input);\n }\n}" }, { "code": null, "e": 8106, "s": 7554, "text": "As you can see, in the setup, we first set M0 and M1 to HIGH, because we want to configure the LoRa module. The config struct (or rather array) is constructed (please remember to set a different value of the address on the receiving side). The comments explain the meaning of each byte’s value. You can also refer to E32-TTL-100’s user manual for more clarification here. Once the parameters are set, the M0 and M1 pins are set to LOW (Normal mode), and the baud rate of LoRa is changed to 57600 (because that’s what is configured via the parameters)." }, { "code": null, "e": 8482, "s": 8106, "text": "Within the loop, we take Serial input from the user. Whatever the user sends gets transmitted over LoRa, and whatever is received over LoRa is printed over the Serial Monitor. Thus, if you give a Serial input to the Arduino, the same text should get printed on the Serial Monitor of the receiving side, and if they type something, it should be visible on your Serial Monitor." }, { "code": null, "e": 8609, "s": 8482, "text": "Go ahead and explore different configurations of the LoRa module, and also different commands that you can send to the module." } ]
Get only digits using regexp in MySQL?
If you want to get only digits using REGEXP, use the following regular expression( ^[0-9]*$) in where clause. Case 1 − If you want only those rows which have exactly 10 digits and all must be only digit, use the below regular expression. SELECT *FROM yourTableName WHERE yourColumnName REGEXP '^[0-9]{10}$'; Case 2 − If you want only those rows with the digit either 1 or more, the following is the syntax − SELECT *FROM yourTableName WHERE yourColumnName REGEXP '^[0-9]*$'; The above syntax will give only those rows that do not have any any characters. To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> insert into OnlyDigits(UserId, UserName) values('123User1','John'); Query OK, 1 row affected (0.16 sec) mysql> insert into OnlyDigits(UserId, UserName) values('3445User2','Carol'); Query OK, 1 row affected (0.19 sec) mysql> insert into OnlyDigits(UserId, UserName) values('145363User3','Mike'); Query OK, 1 row affected (0.20 sec) mysql> insert into OnlyDigits(UserId, UserName) values('13455User4','Larry'); Query OK, 1 row affected (0.22 sec) mysql> insert into OnlyDigits(UserId, UserName) values('123555User5','Sam'); Query OK, 1 row affected (0.15 sec) mysql> insert into OnlyDigits(UserId, UserName) values('596766User6','David'); Query OK, 1 row affected (0.24 sec) mysql> insert into OnlyDigits(UserId, UserName) values('96977User7','Robert'); Query OK, 1 row affected (0.15 sec) mysql> insert into OnlyDigits(UserId, UserName) values('99999User8','James'); Query OK, 1 row affected (0.20 sec) mysql> insert into OnlyDigits(UserId, UserName) values('9999999','James'); Query OK, 1 row affected (0.13 sec) mysql> insert into OnlyDigits(UserId, UserName) values('153545','Maxwell'); Query OK, 1 row affected (0.23 sec) mysql> insert into OnlyDigits(UserId, UserName) values('9999986787','Johnson'); Query OK, 1 row affected (0.20 sec) Now you can display all records from the table using select statement. The query is as follows − mysql> select *from OnlyDigits; The following is the output − +----+-------------+----------+ | Id | UserId | UserName | +----+-------------+----------+ | 1 | 123User1 | John | | 2 | 3445User2 | Carol | | 3 | 145363User3 | Mike | | 4 | 13455User4 | Larry | | 5 | 123555User5 | Sam | | 6 | 596766User6 | David | | 7 | 96977User7 | Robert | | 8 | 99999User8 | James | | 9 | 9999999 | James | | 10 | 153545 | Maxwell | | 11 | 9999986787 | Johnson | +----+-------------+----------+ 11 rows in set (0.00 sec) Case 1 − The following is the query with regex when you want exactly 10 digits in a string and all must be a number: mysql> select *from OnlyDigits -> where UserId REGEXP '^[0-9]{10}$'; The following is the output − +----+------------+----------+ | Id | UserId | UserName | +----+------------+----------+ | 11 | 9999986787 | Johnson | +----+------------+----------+ 1 row in set (0.00 sec) Alternate regular expression of case 1. The query is as follows: mysql> select *from OnlyDigits -> where UserId REGEXP '^[[:digit:]]{10}$'; The following is the output − +----+------------+----------+ | Id | UserId | UserName | +----+------------+----------+ | 11 | 9999986787 | Johnson | +----+------------+----------+ 1 row in set (0.00 sec) Case 2 − If you want only those rows with the one or more digit (Only the digits). The query is as follows: mysql> select *from OnlyDigits -> where UserId REGEXP'^[0-9]*$'; The following is the output: +----+------------+----------+ | Id | UserId | UserName | +----+------------+----------+ | 9 | 9999999 | James | | 10 | 153545 | Maxwell | | 11 | 9999986787 | Johnson | +----+------------+----------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1172, "s": 1062, "text": "If you want to get only digits using REGEXP, use the following regular expression( ^[0-9]*$) in where clause." }, { "code": null, "e": 1300, "s": 1172, "text": "Case 1 − If you want only those rows which have exactly 10 digits and all must be only digit, use the below regular expression." }, { "code": null, "e": 1370, "s": 1300, "text": "SELECT *FROM yourTableName\nWHERE yourColumnName REGEXP '^[0-9]{10}$';" }, { "code": null, "e": 1470, "s": 1370, "text": "Case 2 − If you want only those rows with the digit either 1 or more, the following is the syntax −" }, { "code": null, "e": 1537, "s": 1470, "text": "SELECT *FROM yourTableName\nWHERE yourColumnName REGEXP '^[0-9]*$';" }, { "code": null, "e": 1617, "s": 1537, "text": "The above syntax will give only those rows that do not have any any characters." }, { "code": null, "e": 1716, "s": 1617, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 2964, "s": 1716, "text": "mysql> insert into OnlyDigits(UserId, UserName) values('123User1','John');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into OnlyDigits(UserId, UserName) values('3445User2','Carol');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into OnlyDigits(UserId, UserName) values('145363User3','Mike');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into OnlyDigits(UserId, UserName) values('13455User4','Larry');\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into OnlyDigits(UserId, UserName) values('123555User5','Sam');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into OnlyDigits(UserId, UserName) values('596766User6','David');\nQuery OK, 1 row affected (0.24 sec)\nmysql> insert into OnlyDigits(UserId, UserName) values('96977User7','Robert');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into OnlyDigits(UserId, UserName) values('99999User8','James');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into OnlyDigits(UserId, UserName) values('9999999','James');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into OnlyDigits(UserId, UserName) values('153545','Maxwell');\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into OnlyDigits(UserId, UserName) values('9999986787','Johnson');\nQuery OK, 1 row affected (0.20 sec)" }, { "code": null, "e": 3061, "s": 2964, "text": "Now you can display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 3093, "s": 3061, "text": "mysql> select *from OnlyDigits;" }, { "code": null, "e": 3123, "s": 3093, "text": "The following is the output −" }, { "code": null, "e": 3627, "s": 3123, "text": "+----+-------------+----------+\n| Id | UserId | UserName |\n+----+-------------+----------+\n| 1 | 123User1 | John |\n| 2 | 3445User2 | Carol |\n| 3 | 145363User3 | Mike |\n| 4 | 13455User4 | Larry |\n| 5 | 123555User5 | Sam |\n| 6 | 596766User6 | David |\n| 7 | 96977User7 | Robert |\n| 8 | 99999User8 | James |\n| 9 | 9999999 | James |\n| 10 | 153545 | Maxwell |\n| 11 | 9999986787 | Johnson |\n+----+-------------+----------+\n11 rows in set (0.00 sec)" }, { "code": null, "e": 3744, "s": 3627, "text": "Case 1 − The following is the query with regex when you want exactly 10 digits in a string and all must be a number:" }, { "code": null, "e": 3813, "s": 3744, "text": "mysql> select *from OnlyDigits\n-> where UserId REGEXP '^[0-9]{10}$';" }, { "code": null, "e": 3843, "s": 3813, "text": "The following is the output −" }, { "code": null, "e": 4022, "s": 3843, "text": "+----+------------+----------+\n| Id | UserId | UserName |\n+----+------------+----------+\n| 11 | 9999986787 | Johnson |\n+----+------------+----------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 4087, "s": 4022, "text": "Alternate regular expression of case 1. The query is as follows:" }, { "code": null, "e": 4162, "s": 4087, "text": "mysql> select *from OnlyDigits\n-> where UserId REGEXP '^[[:digit:]]{10}$';" }, { "code": null, "e": 4192, "s": 4162, "text": "The following is the output −" }, { "code": null, "e": 4370, "s": 4192, "text": "+----+------------+----------+\n| Id | UserId | UserName |\n+----+------------+----------+\n| 11 | 9999986787 | Johnson |\n+----+------------+----------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 4478, "s": 4370, "text": "Case 2 − If you want only those rows with the one or more digit (Only the digits). The query is as follows:" }, { "code": null, "e": 4543, "s": 4478, "text": "mysql> select *from OnlyDigits\n-> where UserId REGEXP'^[0-9]*$';" }, { "code": null, "e": 4572, "s": 4543, "text": "The following is the output:" }, { "code": null, "e": 4814, "s": 4572, "text": "+----+------------+----------+\n| Id | UserId | UserName |\n+----+------------+----------+\n| 9 | 9999999 | James |\n| 10 | 153545 | Maxwell |\n| 11 | 9999986787 | Johnson |\n+----+------------+----------+\n3 rows in set (0.00 sec)" } ]
How to add an image to a button (action) in JavaFX?
A button controls in user interface applications, in general, on clicking the button it performs the respective action. You can create a Button by instantiating the javafx.scene.control.Button class. You can add a graphic object (node) to a button using the setGraphic() method of the Button class (inherited from javafx.scene.control.Labeled class). This method accepts an object of the Node class representing a graphic (icon). To add an image to a button − Create an Image object bypassing the path for the required graphic. Create an Image object bypassing the path for the required graphic. Create an ImageView object using the image object. Create an ImageView object using the image object. Create a button by instantiating the Button class. Create a button by instantiating the Button class. Finally, invoke the setGraphic() method on the button by passing the ImageView object as a parameter. Finally, invoke the setGraphic() method on the button by passing the ImageView object as a parameter. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.paint.Color; import javafx.stage.Stage; public class ButtonGraphis extends Application { public void start(Stage stage) { //Creating a graphic (image) Image img = new Image("UIControls/logo.png"); ImageView view = new ImageView(img); view.setFitHeight(80); view.setPreserveRatio(true); //Creating a Button Button button = new Button(); //Setting the location of the button button.setTranslateX(200); button.setTranslateY(25); //Setting the size of the button button.setPrefSize(80, 80); //Setting a graphic to the button button.setGraphic(view); //Setting the stage Group root = new Group(button); Scene scene = new Scene(root, 595, 170, Color.BEIGE); stage.setTitle("Button Graphics"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1262, "s": 1062, "text": "A button controls in user interface applications, in general, on clicking the button it performs the respective action. You can create a Button by instantiating the javafx.scene.control.Button class." }, { "code": null, "e": 1492, "s": 1262, "text": "You can add a graphic object (node) to a button using the setGraphic() method of the Button class (inherited from javafx.scene.control.Labeled class). This method accepts an object of the Node class representing a graphic (icon)." }, { "code": null, "e": 1522, "s": 1492, "text": "To add an image to a button −" }, { "code": null, "e": 1590, "s": 1522, "text": "Create an Image object bypassing the path for the required graphic." }, { "code": null, "e": 1658, "s": 1590, "text": "Create an Image object bypassing the path for the required graphic." }, { "code": null, "e": 1709, "s": 1658, "text": "Create an ImageView object using the image object." }, { "code": null, "e": 1760, "s": 1709, "text": "Create an ImageView object using the image object." }, { "code": null, "e": 1811, "s": 1760, "text": "Create a button by instantiating the Button class." }, { "code": null, "e": 1862, "s": 1811, "text": "Create a button by instantiating the Button class." }, { "code": null, "e": 1964, "s": 1862, "text": "Finally, invoke the setGraphic() method on the button by passing the ImageView object as a parameter." }, { "code": null, "e": 2066, "s": 1964, "text": "Finally, invoke the setGraphic() method on the button by passing the ImageView object as a parameter." }, { "code": null, "e": 3207, "s": 2066, "text": "import javafx.application.Application;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Button;\nimport javafx.scene.image.Image;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\npublic class ButtonGraphis extends Application {\n public void start(Stage stage) {\n //Creating a graphic (image)\n Image img = new Image(\"UIControls/logo.png\");\n ImageView view = new ImageView(img);\n view.setFitHeight(80);\n view.setPreserveRatio(true);\n //Creating a Button\n Button button = new Button();\n //Setting the location of the button\n button.setTranslateX(200);\n button.setTranslateY(25);\n //Setting the size of the button\n button.setPrefSize(80, 80);\n //Setting a graphic to the button\n button.setGraphic(view);\n //Setting the stage\n Group root = new Group(button);\n Scene scene = new Scene(root, 595, 170, Color.BEIGE);\n stage.setTitle(\"Button Graphics\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
HTML DOM Input Password required property
The HTML DOM input password required property is associated with the required attribute of an <input> element. The required property is used for setting and returning if it is necessary to fill some password field or not before the form is submitted to the server. This allows the form to not submit if a password field with required attribute is left empty by the user. Following is the syntax for − Setting the required property − textObject.required = true|false Here, true represents the text field must be filled while false represents its optional to fill the field before submitting the form. Let us look at an example for the input password required property − <!DOCTYPE html> <html> <body> <h1>Input password required property</h1> <p>Check if the above field is mandatory to be filled or not by clicking the below button</p> <form action="/Sample_page.php"> Password: <input type="password" id="PASS1" name=”passW” required> <input type="submit"> </form> <br> <button onclick="checkReq()">CHECK</button> <p id="Sample"></p> <script> function checkReq() { var Req=document.getElementById("PASS1").required; if(Req==true) document.getElementById("Sample").innerHTML="The password field must be filled before submitting"; else document.getElementById("Sample").innerHTML="The password field is optional and can be left blank by the user"; } </script> </body> </html> This will produce the following output − On clicking the CHECK button − If the required property is set true and you click submit − In the above example − We have first created an input password field with id “PASS1”, name “passW” and required attribute set to true.The password field is contained inside a form with action=”Sample_page.php” which specifies where to submit the form data when clicked on the submit button. <form action="/Sample_page.php"> Password: <input type="password" id="PASS1" name=”passW” required> <input type="submit"> </form> We have then created a button CHECK that will execute the checkReq() method when clicked by the user − <button onclick="checkReq()">CHECK</button> The checkReq() uses the getElementById() method to get the input element with type password and get its required property which in our case returns true. The returned boolean value is assigned to a variable Req and based on whether the returned value is true or false we display appropriate message in the paragraph with id “Sample” using its innerHTML property − function checkReq() { var Req=document.getElementById("PASS1").required; if(Req==true) document.getElementById("Sample").innerHTML="The password field must be filled before submitting"; else document.getElementById("Sample").innerHTML="The password field is optional and can be left blank by theuser"; }
[ { "code": null, "e": 1433, "s": 1062, "text": "The HTML DOM input password required property is associated with the required attribute of an <input> element. The required property is used for setting and returning if it is necessary to fill some password field or not before the form is submitted to the server. This allows the form to not submit if a password field with required attribute is left empty by the user." }, { "code": null, "e": 1463, "s": 1433, "text": "Following is the syntax for −" }, { "code": null, "e": 1495, "s": 1463, "text": "Setting the required property −" }, { "code": null, "e": 1528, "s": 1495, "text": "textObject.required = true|false" }, { "code": null, "e": 1662, "s": 1528, "text": "Here, true represents the text field must be filled while false represents its optional to fill the field before submitting the form." }, { "code": null, "e": 1731, "s": 1662, "text": "Let us look at an example for the input password required property −" }, { "code": null, "e": 2478, "s": 1731, "text": "<!DOCTYPE html>\n<html>\n<body>\n<h1>Input password required property</h1>\n<p>Check if the above field is mandatory to be filled or not by clicking the below button</p>\n<form action=\"/Sample_page.php\">\nPassword: <input type=\"password\" id=\"PASS1\" name=”passW” required>\n<input type=\"submit\">\n</form>\n<br>\n<button onclick=\"checkReq()\">CHECK</button>\n<p id=\"Sample\"></p>\n<script>\n function checkReq() {\n var Req=document.getElementById(\"PASS1\").required;\n if(Req==true)\n document.getElementById(\"Sample\").innerHTML=\"The password field must be filled before submitting\";\n else\n document.getElementById(\"Sample\").innerHTML=\"The password field is optional and can be left blank by the user\";\n }\n</script>\n</body>\n</html>" }, { "code": null, "e": 2519, "s": 2478, "text": "This will produce the following output −" }, { "code": null, "e": 2550, "s": 2519, "text": "On clicking the CHECK button −" }, { "code": null, "e": 2610, "s": 2550, "text": "If the required property is set true and you click submit −" }, { "code": null, "e": 2633, "s": 2610, "text": "In the above example −" }, { "code": null, "e": 2901, "s": 2633, "text": "We have first created an input password field with id “PASS1”, name “passW” and required attribute set to true.The password field is contained inside a form with action=”Sample_page.php” which specifies where to submit the form data when clicked on the submit button." }, { "code": null, "e": 3031, "s": 2901, "text": "<form action=\"/Sample_page.php\">\nPassword: <input type=\"password\" id=\"PASS1\" name=”passW” required>\n<input type=\"submit\">\n</form>" }, { "code": null, "e": 3134, "s": 3031, "text": "We have then created a button CHECK that will execute the checkReq() method when clicked by the user −" }, { "code": null, "e": 3178, "s": 3134, "text": "<button onclick=\"checkReq()\">CHECK</button>" }, { "code": null, "e": 3542, "s": 3178, "text": "The checkReq() uses the getElementById() method to get the input element with type password and get its required property which in our case returns true. The returned boolean value is assigned to a variable Req and based on whether the returned value is true or false we display appropriate message in the paragraph with id “Sample” using its innerHTML property −" }, { "code": null, "e": 3867, "s": 3542, "text": "function checkReq() {\n var Req=document.getElementById(\"PASS1\").required;\n if(Req==true)\n document.getElementById(\"Sample\").innerHTML=\"The password field must be filled before submitting\";\n else\n document.getElementById(\"Sample\").innerHTML=\"The password field is optional and can be left blank by theuser\";\n}" } ]
Find a string in lexicographic order which is in between given two strings - GeeksforGeeks
09 Sep, 2021 Given two strings S and T, find a string of the same length which is lexicographically greater than S and smaller than T. Print “-1” if no such string is formed.(S > T) Note: string S = s1s2... sn is said to be lexicographically smaller than string T = t1t2... tn, if there exists an i, such that s1 = t1, s2 = t2, ... si – 1 = ti – 1, si < ti. Examples: Input : S = "aaa", T = "ccc" Output : aab Explanation: Here, 'b' is greater than any letter in S[]('a') and smaller than any letter in T[]('c'). Input : S = "abcde", T = "abcdf" Output : -1 Explanation: There is no other string between S and T. Approach: Find a string which is lexicographically greater than string S and check if it is smaller than string T, if yes print the string next else print “-1”. To find string, iterate the string S in the reverse order, if the last letter is not ‘z’, increase the letter by one (to move to next letter). If it is ‘z’, change it to ‘a’ and move to the second last character. Compare the resultant string with string T, if both strings are equal print ‘-1’, else print the resultant string. Below is the implementation of above approach: C++ Java Python3 C# Javascript // CPP program to find the string// in lexicographic order which is// in between given two strings#include <bits/stdc++.h>using namespace std; // Function to find the lexicographically // next stringstring lexNext(string s, int n){ // Iterate from last character for (int i = n - 1; i >= 0; i--) { // If not 'z', increase by one if (s[i] != 'z') { s[i]++; return s; } // if 'z', change it to 'a' s[i] = 'a'; }} // Driver Codeint main(){ string S = "abcdeg", T = "abcfgh"; int n = S.length(); string res = lexNext(S, n); // If not equal, print the // resultant string if (res != T) cout << res << endl; else cout << "-1" << endl; return 0;} //Java program to find the string// in lexicographic order which is// in between given two strings class GFG { // Function to find the lexicographically // next string static String lexNext(String str, int n) { char[] s = str.toCharArray(); // Iterate from last character for (int i = n - 1; i >= 0; i--) { // If not 'z', increase by one if (s[i] != 'z') { s[i]++; return String.valueOf(s); } // if 'z', change it to 'a' s[i] = 'a'; } return null; } // Driver Code static public void main(String[] args) { String S = "abcdeg", T = "abcfgh"; int n = S.length(); String res = lexNext(S, n); // If not equal, print the // resultant string if (res != T) { System.out.println(res); } else { System.out.println("-1"); } }} // This code is contributed by 29AjayKumar # Python3 program to find the string# in lexicographic order which is# in between given two strings # Function to find the lexicographically# next stringdef lexNext(s, n): # Iterate from last character for i in range(n - 1, -1, -1): # If not 'z', increase by one if s[i] != 'z': k = ord(s[i]) s[i] = chr(k + 1) return ''.join(s) # if 'z', change it to 'a' s[i] = 'a' # Driver Codeif __name__ == "__main__": S = "abcdeg" T = "abcfgh" n = len(S) S = list(S) res = lexNext(S, n) # If not equal, print the # resultant string if res != T: print(res) else: print(-1) # This code is contributed by# sanjeev2552 //C# program to find the string// in lexicographic order which is// in between given two stringsusing System; public class GFG { // Function to find the lexicographically // next string static String lexNext(String str, int n) { char[] s = str.ToCharArray(); // Iterate from last character for (int i = n - 1; i >= 0; i--) { // If not 'z', increase by one if (s[i] != 'z') { s[i]++; return new String(s); } // if 'z', change it to 'a' s[i] = 'a'; } return null; } // Driver Code static public void Main() { String S = "abcdeg", T = "abcfgh"; int n = S.Length; String res = lexNext(S, n); // If not equal, print the // resultant string if (res != T) { Console.Write(res); } else { Console.Write("-1"); } }} // This code is contributed by 29AjayKumar <script> // JavaScript program to find the string// in lexicographic order which is// in between given two strings // Function to find the lexicographically // next stringfunction lexNext( s, n){ // Iterate from last character for (let i = n - 1; i >= 0; i--) { // If not 'z', increase by one if (s[i] != 'z') { let code = s.charCodeAt(i)+1; let str = String.fromCharCode(code); return s.substr(0,i)+str+s.substr(i+1); } // if 'z', change it to 'a' s[i] = 'a'; } } // Driver Codelet S = "abcdeg";let T = "abcfgh";let n = S.length;let res = lexNext(S, n); // If not equal, print the// resultant stringif (res != T) document.write( res,'<br>'); else document.write("-1 <br>" ); </script> Output: abcdeh YouTubeGeeksforGeeks501K subscribersFind a string in lexicographic order which is in between two given string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:00•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=XVDyj0eYQKU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> 29AjayKumar sanjeev2552 rohitsingh07052 simmytarika5 lexicographic-ordering Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Convert string to char array in C++ Longest Palindromic Substring | Set 1 Array of Strings in C++ (5 Different Ways to Create) Caesar Cipher in Cryptography Reverse words in a given string Length of the longest substring without repeating characters Check whether two strings are anagram of each other Top 50 String Coding Problems for Interviews
[ { "code": null, "e": 24948, "s": 24920, "text": "\n09 Sep, 2021" }, { "code": null, "e": 25118, "s": 24948, "text": "Given two strings S and T, find a string of the same length which is lexicographically greater than S and smaller than T. Print “-1” if no such string is formed.(S > T) " }, { "code": null, "e": 25294, "s": 25118, "text": "Note: string S = s1s2... sn is said to be lexicographically smaller than string T = t1t2... tn, if there exists an i, such that s1 = t1, s2 = t2, ... si – 1 = ti – 1, si < ti." }, { "code": null, "e": 25305, "s": 25294, "text": "Examples: " }, { "code": null, "e": 25569, "s": 25305, "text": "Input : S = \"aaa\", T = \"ccc\"\nOutput : aab\nExplanation: \nHere, 'b' is greater than any \nletter in S[]('a') and smaller \nthan any letter in T[]('c').\n\nInput : S = \"abcde\", T = \"abcdf\"\nOutput : -1\nExplanation: \nThere is no other string between\nS and T. " }, { "code": null, "e": 26058, "s": 25569, "text": "Approach: Find a string which is lexicographically greater than string S and check if it is smaller than string T, if yes print the string next else print “-1”. To find string, iterate the string S in the reverse order, if the last letter is not ‘z’, increase the letter by one (to move to next letter). If it is ‘z’, change it to ‘a’ and move to the second last character. Compare the resultant string with string T, if both strings are equal print ‘-1’, else print the resultant string." }, { "code": null, "e": 26107, "s": 26058, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 26111, "s": 26107, "text": "C++" }, { "code": null, "e": 26116, "s": 26111, "text": "Java" }, { "code": null, "e": 26124, "s": 26116, "text": "Python3" }, { "code": null, "e": 26127, "s": 26124, "text": "C#" }, { "code": null, "e": 26138, "s": 26127, "text": "Javascript" }, { "code": "// CPP program to find the string// in lexicographic order which is// in between given two strings#include <bits/stdc++.h>using namespace std; // Function to find the lexicographically // next stringstring lexNext(string s, int n){ // Iterate from last character for (int i = n - 1; i >= 0; i--) { // If not 'z', increase by one if (s[i] != 'z') { s[i]++; return s; } // if 'z', change it to 'a' s[i] = 'a'; }} // Driver Codeint main(){ string S = \"abcdeg\", T = \"abcfgh\"; int n = S.length(); string res = lexNext(S, n); // If not equal, print the // resultant string if (res != T) cout << res << endl; else cout << \"-1\" << endl; return 0;}", "e": 26909, "s": 26138, "text": null }, { "code": "//Java program to find the string// in lexicographic order which is// in between given two strings class GFG { // Function to find the lexicographically // next string static String lexNext(String str, int n) { char[] s = str.toCharArray(); // Iterate from last character for (int i = n - 1; i >= 0; i--) { // If not 'z', increase by one if (s[i] != 'z') { s[i]++; return String.valueOf(s); } // if 'z', change it to 'a' s[i] = 'a'; } return null; } // Driver Code static public void main(String[] args) { String S = \"abcdeg\", T = \"abcfgh\"; int n = S.length(); String res = lexNext(S, n); // If not equal, print the // resultant string if (res != T) { System.out.println(res); } else { System.out.println(\"-1\"); } }} // This code is contributed by 29AjayKumar", "e": 27881, "s": 26909, "text": null }, { "code": "# Python3 program to find the string# in lexicographic order which is# in between given two strings # Function to find the lexicographically# next stringdef lexNext(s, n): # Iterate from last character for i in range(n - 1, -1, -1): # If not 'z', increase by one if s[i] != 'z': k = ord(s[i]) s[i] = chr(k + 1) return ''.join(s) # if 'z', change it to 'a' s[i] = 'a' # Driver Codeif __name__ == \"__main__\": S = \"abcdeg\" T = \"abcfgh\" n = len(S) S = list(S) res = lexNext(S, n) # If not equal, print the # resultant string if res != T: print(res) else: print(-1) # This code is contributed by# sanjeev2552", "e": 28598, "s": 27881, "text": null }, { "code": "//C# program to find the string// in lexicographic order which is// in between given two stringsusing System; public class GFG { // Function to find the lexicographically // next string static String lexNext(String str, int n) { char[] s = str.ToCharArray(); // Iterate from last character for (int i = n - 1; i >= 0; i--) { // If not 'z', increase by one if (s[i] != 'z') { s[i]++; return new String(s); } // if 'z', change it to 'a' s[i] = 'a'; } return null; } // Driver Code static public void Main() { String S = \"abcdeg\", T = \"abcfgh\"; int n = S.Length; String res = lexNext(S, n); // If not equal, print the // resultant string if (res != T) { Console.Write(res); } else { Console.Write(\"-1\"); } }} // This code is contributed by 29AjayKumar", "e": 29564, "s": 28598, "text": null }, { "code": "<script> // JavaScript program to find the string// in lexicographic order which is// in between given two strings // Function to find the lexicographically // next stringfunction lexNext( s, n){ // Iterate from last character for (let i = n - 1; i >= 0; i--) { // If not 'z', increase by one if (s[i] != 'z') { let code = s.charCodeAt(i)+1; let str = String.fromCharCode(code); return s.substr(0,i)+str+s.substr(i+1); } // if 'z', change it to 'a' s[i] = 'a'; } } // Driver Codelet S = \"abcdeg\";let T = \"abcfgh\";let n = S.length;let res = lexNext(S, n); // If not equal, print the// resultant stringif (res != T) document.write( res,'<br>'); else document.write(\"-1 <br>\" ); </script>", "e": 30370, "s": 29564, "text": null }, { "code": null, "e": 30380, "s": 30370, "text": "Output: " }, { "code": null, "e": 30389, "s": 30380, "text": "abcdeh\n " }, { "code": null, "e": 31261, "s": 30389, "text": "YouTubeGeeksforGeeks501K subscribersFind a string in lexicographic order which is in between two given string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:00•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=XVDyj0eYQKU\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 31275, "s": 31263, "text": "29AjayKumar" }, { "code": null, "e": 31287, "s": 31275, "text": "sanjeev2552" }, { "code": null, "e": 31303, "s": 31287, "text": "rohitsingh07052" }, { "code": null, "e": 31316, "s": 31303, "text": "simmytarika5" }, { "code": null, "e": 31339, "s": 31316, "text": "lexicographic-ordering" }, { "code": null, "e": 31347, "s": 31339, "text": "Strings" }, { "code": null, "e": 31355, "s": 31347, "text": "Strings" }, { "code": null, "e": 31453, "s": 31355, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31462, "s": 31453, "text": "Comments" }, { "code": null, "e": 31475, "s": 31462, "text": "Old Comments" }, { "code": null, "e": 31532, "s": 31475, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 31568, "s": 31532, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 31604, "s": 31568, "text": "Convert string to char array in C++" }, { "code": null, "e": 31642, "s": 31604, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 31695, "s": 31642, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 31725, "s": 31695, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 31757, "s": 31725, "text": "Reverse words in a given string" }, { "code": null, "e": 31818, "s": 31757, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 31870, "s": 31818, "text": "Check whether two strings are anagram of each other" } ]
MySQL Query to change lower case to upper case?
You can use in-built function UPPER() from MySQL to change a lower case to upper case. The syntax is as follows with select statement. SELECT UPPER(‘yourStringValue’); The following is an example showing string in lower case − mysql> select upper('john'); Here is the output displaying string in upper case − +---------------+ | upper('john') | +---------------+ | JOHN | +---------------+ 1 row in set (0.00 sec) If you already have a table with a lower case value, then you can use the UPPER() function with update command. The syntax is as follows − UPDATE yourTableName set yourColumnName = UPPER(yourColumnName); To understand the above concept, let us first create a table and insert string values in lowercase. The following is the query to create a table − mysql> create table UpperTableDemo −> ( −> BookName longtext −> ); Query OK, 0 rows affected (0.70 sec) Insert some records in the table using INSERT command. The query is as follows − mysql> insert into UpperTableDemo values('introduction to c'); Query OK, 1 row affected (0.13 sec) mysql> insert into UpperTableDemo values('introduction to java'); Query OK, 1 row affected (0.18 sec) mysql> insert into UpperTableDemo values('introduction to python'); Query OK, 1 row affected (0.11 sec) mysql> insert into UpperTableDemo values('introduction to c#'); Query OK, 1 row affected (0.17 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from UpperTableDemo; The following is the output − +------------------------+ | BookName | +------------------------+ | introduction to c | | introduction to java | | introduction to python | | introduction to c# | +------------------------+ 4 rows in set (0.00 sec) The following is the query to change the lower case to upper case − mysql> update UpperTableDemo set BookName = upper(BookName); Query OK, 4 rows affected (0.16 sec) Rows matched: 4 Changed: 4 Warnings: 0 Display all records again with updated value. The query is as follows − mysql> select *from UpperTableDemo; The following is the output − +------------------------+ | BookName | +------------------------+ | INTRODUCTION TO C | | INTRODUCTION TO JAVA | | INTRODUCTION TO PYTHON | | INTRODUCTION TO C# | +------------------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1197, "s": 1062, "text": "You can use in-built function UPPER() from MySQL to change a lower case to upper case. The syntax is as follows with select statement." }, { "code": null, "e": 1230, "s": 1197, "text": "SELECT UPPER(‘yourStringValue’);" }, { "code": null, "e": 1289, "s": 1230, "text": "The following is an example showing string in lower case −" }, { "code": null, "e": 1318, "s": 1289, "text": "mysql> select upper('john');" }, { "code": null, "e": 1371, "s": 1318, "text": "Here is the output displaying string in upper case −" }, { "code": null, "e": 1485, "s": 1371, "text": "+---------------+\n| upper('john') |\n+---------------+\n| JOHN |\n+---------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1624, "s": 1485, "text": "If you already have a table with a lower case value, then you can use the UPPER() function with update command. The syntax is as follows −" }, { "code": null, "e": 1689, "s": 1624, "text": "UPDATE yourTableName set yourColumnName = UPPER(yourColumnName);" }, { "code": null, "e": 1836, "s": 1689, "text": "To understand the above concept, let us first create a table and insert string values in lowercase. The following is the query to create a table −" }, { "code": null, "e": 1949, "s": 1836, "text": "mysql> create table UpperTableDemo\n −> (\n −> BookName longtext\n −> );\nQuery OK, 0 rows affected (0.70 sec)" }, { "code": null, "e": 2030, "s": 1949, "text": "Insert some records in the table using INSERT command. The query is as follows −" }, { "code": null, "e": 2438, "s": 2030, "text": "mysql> insert into UpperTableDemo values('introduction to c');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into UpperTableDemo values('introduction to java');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into UpperTableDemo values('introduction to python');\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into UpperTableDemo values('introduction to c#');\nQuery OK, 1 row affected (0.17 sec)" }, { "code": null, "e": 2523, "s": 2438, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2559, "s": 2523, "text": "mysql> select *from UpperTableDemo;" }, { "code": null, "e": 2589, "s": 2559, "text": "The following is the output −" }, { "code": null, "e": 2830, "s": 2589, "text": "+------------------------+\n| BookName |\n+------------------------+\n| introduction to c |\n| introduction to java |\n| introduction to python |\n| introduction to c# |\n+------------------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2898, "s": 2830, "text": "The following is the query to change the lower case to upper case −" }, { "code": null, "e": 3035, "s": 2898, "text": "mysql> update UpperTableDemo set BookName = upper(BookName);\nQuery OK, 4 rows affected (0.16 sec)\nRows matched: 4 Changed: 4 Warnings: 0" }, { "code": null, "e": 3107, "s": 3035, "text": "Display all records again with updated value. The query is as follows −" }, { "code": null, "e": 3143, "s": 3107, "text": "mysql> select *from UpperTableDemo;" }, { "code": null, "e": 3173, "s": 3143, "text": "The following is the output −" }, { "code": null, "e": 3414, "s": 3173, "text": "+------------------------+\n| BookName |\n+------------------------+\n| INTRODUCTION TO C |\n| INTRODUCTION TO JAVA |\n| INTRODUCTION TO PYTHON |\n| INTRODUCTION TO C# |\n+------------------------+\n4 rows in set (0.00 sec)" } ]
How to use enums in Python classes?
There is a module name "enum" in python with the hep of which enum is used in python. #import enum import enum # use enum in class class Car(enum.Enum): suzuki = 1 Hyundai = 2 Dezire = 3 print ("All the enum values are : ") for c in (Car): print(c)
[ { "code": null, "e": 1148, "s": 1062, "text": "There is a module name \"enum\" in python with the hep of which enum is used in python." }, { "code": null, "e": 1323, "s": 1148, "text": "#import enum\nimport enum\n# use enum in class\nclass Car(enum.Enum):\n suzuki = 1\n Hyundai = 2\n Dezire = 3\nprint (\"All the enum values are : \")\nfor c in (Car):\n print(c)" } ]
How to convert an Image to blob using JavaScript?
Following is the code to convert an image to blob using JavaScript − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 18px; font-weight: 500; color: rebeccapurple; } </style> </head> <body> <h1>Convert an Image to blob using JavaScript</h1> <div class="sample"> <img src="https://picsum.photos/id/222/300/300.jpg" /> </div> <button class="Btn">Convert</button> <div class="result"></div> <h3>Click on the above button to convert the above image to blob</h3> <script> let BtnEle = document.querySelector(".Btn"); let resEle = gdocument.querySelector(".result"); BtnEle.addEventListener("click", () => { fetch("https://i.picsum.photos/id/222/300/300.jpg") .then(function (response) { return response.blob(); }) .then(function (blob) { resEle.innerHTML = "blob.size = " + blob.size + "<br>"; resEle.innerHTML += "blob.type = " + blob.type + "<br>"; }); }); </script> </body> </html> The above code will produce the following output − On clicking the ‘Convert’ button −
[ { "code": null, "e": 1131, "s": 1062, "text": "Following is the code to convert an image to blob using JavaScript −" }, { "code": null, "e": 1142, "s": 1131, "text": " Live Demo" }, { "code": null, "e": 2271, "s": 1142, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 18px;\n font-weight: 500;\n color: rebeccapurple;\n }\n</style>\n</head>\n<body>\n<h1>Convert an Image to blob using JavaScript</h1>\n<div class=\"sample\">\n<img src=\"https://picsum.photos/id/222/300/300.jpg\" />\n</div>\n<button class=\"Btn\">Convert</button>\n<div class=\"result\"></div>\n<h3>Click on the above button to convert the above image to blob</h3>\n<script>\n let BtnEle = document.querySelector(\".Btn\");\n let resEle = gdocument.querySelector(\".result\");\n BtnEle.addEventListener(\"click\", () => {\n fetch(\"https://i.picsum.photos/id/222/300/300.jpg\")\n .then(function (response) {\n return response.blob();\n })\n .then(function (blob) {\n resEle.innerHTML = \"blob.size = \" + blob.size + \"<br>\";\n resEle.innerHTML += \"blob.type = \" + blob.type + \"<br>\";\n });\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2322, "s": 2271, "text": "The above code will produce the following output −" }, { "code": null, "e": 2357, "s": 2322, "text": "On clicking the ‘Convert’ button −" } ]
314e IT Solutions Interview Experience for Software Engineer Role | On-Campus 2021 - GeeksforGeeks
26 Feb, 2021 Online Test: 10 Quantitative Aptitude Questions: Medium level 3 Coding questions: 2 Medium, 1 Hard Given an equation with a digit represented by x, find the value of x that satisfies the equation.Ex. “1x0 + 5 = 105”, Output: 0 Ex. “75 / x5 = 3”, Output: 2Determine whether a given password satisfies all the requirements:Must contain a Capital Letter.Must contain a number.Must contain a punctuation symbol or a math symbol.Must not contain the word “password” in any form.Should be of less than 7 characters and less than 31 characters.Switch Sort: Last question on this page under Sorting Hard Tag.http://wiki.alexjslessor.com/en/codebyte-answersOne SQL query: Medium difficulty involving join, count(), group by, and order by.Note: Candidates who did 2 coding questions fully and a hard one partially and sql query completely were shortlisted for the next round.Technical Discussion Round 1:Discussed all the codes from the online round.Switch sort question had a corner case for [3,4,1,2] for which my code won’t work. Made me correct my previous code for 1.5 hours till it was fully correct.Taking Command line arguments in Python.File handling in python – opening the file, file modes, writing a file, detecting the end of the file.Technical Discussion Round 2: This round was with the CTO of the company.Started by asking which language I was comfortable with, I said Python.Started with the same command-line arguments and file handling in detail.How to write the main function.How to declare class, how to declare objects?What is the init function? Its function in any development, that is role of init.py? What is your final year project? Explained, no counter questions.Have you done any projects on databases? Explained using python Tkinter library and sqlite3.Have you done any projects on web development? Explained internship project using Angular, typescript, APIs, no counter questions.What OS are you comfortable with? I said Windows, with not much experience with Linux, he said not an issue.How fluent are you in SQL? I said intermediate, asked a query between two tables, gave the logic, satisfied.Special thanks to GeeksforGeeks for the preparation resources. All the very best My Personal Notes arrow_drop_upSave Given an equation with a digit represented by x, find the value of x that satisfies the equation.Ex. “1x0 + 5 = 105”, Output: 0 Ex. “75 / x5 = 3”, Output: 2 Ex. “1x0 + 5 = 105”, Output: 0 Ex. “75 / x5 = 3”, Output: 2 Determine whether a given password satisfies all the requirements:Must contain a Capital Letter.Must contain a number.Must contain a punctuation symbol or a math symbol.Must not contain the word “password” in any form.Should be of less than 7 characters and less than 31 characters. Must contain a Capital Letter. Must contain a number. Must contain a punctuation symbol or a math symbol. Must not contain the word “password” in any form. Should be of less than 7 characters and less than 31 characters. Switch Sort: Last question on this page under Sorting Hard Tag.http://wiki.alexjslessor.com/en/codebyte-answersOne SQL query: Medium difficulty involving join, count(), group by, and order by.Note: Candidates who did 2 coding questions fully and a hard one partially and sql query completely were shortlisted for the next round.Technical Discussion Round 1:Discussed all the codes from the online round.Switch sort question had a corner case for [3,4,1,2] for which my code won’t work. Made me correct my previous code for 1.5 hours till it was fully correct.Taking Command line arguments in Python.File handling in python – opening the file, file modes, writing a file, detecting the end of the file.Technical Discussion Round 2: This round was with the CTO of the company.Started by asking which language I was comfortable with, I said Python.Started with the same command-line arguments and file handling in detail.How to write the main function.How to declare class, how to declare objects?What is the init function? Its function in any development, that is role of init.py? What is your final year project? Explained, no counter questions.Have you done any projects on databases? Explained using python Tkinter library and sqlite3.Have you done any projects on web development? Explained internship project using Angular, typescript, APIs, no counter questions.What OS are you comfortable with? I said Windows, with not much experience with Linux, he said not an issue.How fluent are you in SQL? I said intermediate, asked a query between two tables, gave the logic, satisfied.Special thanks to GeeksforGeeks for the preparation resources. All the very best My Personal Notes arrow_drop_upSave http://wiki.alexjslessor.com/en/codebyte-answers One SQL query: Medium difficulty involving join, count(), group by, and order by. Note: Candidates who did 2 coding questions fully and a hard one partially and sql query completely were shortlisted for the next round. Technical Discussion Round 1: Discussed all the codes from the online round.Switch sort question had a corner case for [3,4,1,2] for which my code won’t work. Made me correct my previous code for 1.5 hours till it was fully correct.Taking Command line arguments in Python.File handling in python – opening the file, file modes, writing a file, detecting the end of the file. Discussed all the codes from the online round. Switch sort question had a corner case for [3,4,1,2] for which my code won’t work. Made me correct my previous code for 1.5 hours till it was fully correct. Taking Command line arguments in Python. File handling in python – opening the file, file modes, writing a file, detecting the end of the file. Technical Discussion Round 2: This round was with the CTO of the company. Started by asking which language I was comfortable with, I said Python.Started with the same command-line arguments and file handling in detail.How to write the main function.How to declare class, how to declare objects?What is the init function? Its function in any development, that is role of init.py? What is your final year project? Explained, no counter questions.Have you done any projects on databases? Explained using python Tkinter library and sqlite3.Have you done any projects on web development? Explained internship project using Angular, typescript, APIs, no counter questions.What OS are you comfortable with? I said Windows, with not much experience with Linux, he said not an issue.How fluent are you in SQL? I said intermediate, asked a query between two tables, gave the logic, satisfied. Started by asking which language I was comfortable with, I said Python. Started with the same command-line arguments and file handling in detail. How to write the main function. How to declare class, how to declare objects? What is the init function? Its function in any development, that is role of init.py? What is your final year project? Explained, no counter questions. Have you done any projects on databases? Explained using python Tkinter library and sqlite3. Have you done any projects on web development? Explained internship project using Angular, typescript, APIs, no counter questions. What OS are you comfortable with? I said Windows, with not much experience with Linux, he said not an issue. How fluent are you in SQL? I said intermediate, asked a query between two tables, gave the logic, satisfied. Special thanks to GeeksforGeeks for the preparation resources. All the very best 314e Marketing On-Campus Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Amazon Interview Experience for SDE-1 (On-Campus) Microsoft Interview Experience for Internship (Via Engage) Amazon Interview Experience for SDE-1 Amazon Interview Experience for SDE-1 Amazon Interview Experience for SDE1 (8 Months Experienced) 2022 Amazon Interview Experience (Off-Campus) 2022 Amazon Interview Experience for SDE-1(Off-Campus) Microsoft Interview Experience for SDE-1 (Hyderabad) Google Interview Experience for IT Support Engineer Zoho Interview | Set 2 (On-Campus)
[ { "code": null, "e": 25054, "s": 25026, "text": "\n26 Feb, 2021" }, { "code": null, "e": 25067, "s": 25054, "text": "Online Test:" }, { "code": null, "e": 25116, "s": 25067, "text": "10 Quantitative Aptitude Questions: Medium level" }, { "code": null, "e": 25153, "s": 25116, "text": "3 Coding questions: 2 Medium, 1 Hard" }, { "code": null, "e": 27290, "s": 25153, "text": "Given an equation with a digit represented by x, find the value of x that satisfies the equation.Ex. “1x0 + 5 = 105”, Output: 0\nEx. “75 / x5 = 3”, Output: 2Determine whether a given password satisfies all the requirements:Must contain a Capital Letter.Must contain a number.Must contain a punctuation symbol or a math symbol.Must not contain the word “password” in any form.Should be of less than 7 characters and less than 31 characters.Switch Sort: Last question on this page under Sorting Hard Tag.http://wiki.alexjslessor.com/en/codebyte-answersOne SQL query: Medium difficulty involving join, count(), group by, and order by.Note: Candidates who did 2 coding questions fully and a hard one partially and sql query completely were shortlisted for the next round.Technical Discussion Round 1:Discussed all the codes from the online round.Switch sort question had a corner case for [3,4,1,2] for which my code won’t work. Made me correct my previous code for 1.5 hours till it was fully correct.Taking Command line arguments in Python.File handling in python – opening the file, file modes, writing a file, detecting the end of the file.Technical Discussion Round 2: This round was with the CTO of the company.Started by asking which language I was comfortable with, I said Python.Started with the same command-line arguments and file handling in detail.How to write the main function.How to declare class, how to declare objects?What is the init function? Its function in any development, that is role of init.py? What is your final year project? Explained, no counter questions.Have you done any projects on databases? Explained using python Tkinter library and sqlite3.Have you done any projects on web development? Explained internship project using Angular, typescript, APIs, no counter questions.What OS are you comfortable with? I said Windows, with not much experience with Linux, he said not an issue.How fluent are you in SQL? I said intermediate, asked a query between two tables, gave the logic, satisfied.Special thanks to GeeksforGeeks for the preparation resources. All the very best My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 27447, "s": 27290, "text": "Given an equation with a digit represented by x, find the value of x that satisfies the equation.Ex. “1x0 + 5 = 105”, Output: 0\nEx. “75 / x5 = 3”, Output: 2" }, { "code": null, "e": 27507, "s": 27447, "text": "Ex. “1x0 + 5 = 105”, Output: 0\nEx. “75 / x5 = 3”, Output: 2" }, { "code": null, "e": 27790, "s": 27507, "text": "Determine whether a given password satisfies all the requirements:Must contain a Capital Letter.Must contain a number.Must contain a punctuation symbol or a math symbol.Must not contain the word “password” in any form.Should be of less than 7 characters and less than 31 characters." }, { "code": null, "e": 27821, "s": 27790, "text": "Must contain a Capital Letter." }, { "code": null, "e": 27844, "s": 27821, "text": "Must contain a number." }, { "code": null, "e": 27896, "s": 27844, "text": "Must contain a punctuation symbol or a math symbol." }, { "code": null, "e": 27946, "s": 27896, "text": "Must not contain the word “password” in any form." }, { "code": null, "e": 28011, "s": 27946, "text": "Should be of less than 7 characters and less than 31 characters." }, { "code": null, "e": 29710, "s": 28011, "text": "Switch Sort: Last question on this page under Sorting Hard Tag.http://wiki.alexjslessor.com/en/codebyte-answersOne SQL query: Medium difficulty involving join, count(), group by, and order by.Note: Candidates who did 2 coding questions fully and a hard one partially and sql query completely were shortlisted for the next round.Technical Discussion Round 1:Discussed all the codes from the online round.Switch sort question had a corner case for [3,4,1,2] for which my code won’t work. Made me correct my previous code for 1.5 hours till it was fully correct.Taking Command line arguments in Python.File handling in python – opening the file, file modes, writing a file, detecting the end of the file.Technical Discussion Round 2: This round was with the CTO of the company.Started by asking which language I was comfortable with, I said Python.Started with the same command-line arguments and file handling in detail.How to write the main function.How to declare class, how to declare objects?What is the init function? Its function in any development, that is role of init.py? What is your final year project? Explained, no counter questions.Have you done any projects on databases? Explained using python Tkinter library and sqlite3.Have you done any projects on web development? Explained internship project using Angular, typescript, APIs, no counter questions.What OS are you comfortable with? I said Windows, with not much experience with Linux, he said not an issue.How fluent are you in SQL? I said intermediate, asked a query between two tables, gave the logic, satisfied.Special thanks to GeeksforGeeks for the preparation resources. All the very best My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 29759, "s": 29710, "text": "http://wiki.alexjslessor.com/en/codebyte-answers" }, { "code": null, "e": 29841, "s": 29759, "text": "One SQL query: Medium difficulty involving join, count(), group by, and order by." }, { "code": null, "e": 29978, "s": 29841, "text": "Note: Candidates who did 2 coding questions fully and a hard one partially and sql query completely were shortlisted for the next round." }, { "code": null, "e": 30008, "s": 29978, "text": "Technical Discussion Round 1:" }, { "code": null, "e": 30353, "s": 30008, "text": "Discussed all the codes from the online round.Switch sort question had a corner case for [3,4,1,2] for which my code won’t work. Made me correct my previous code for 1.5 hours till it was fully correct.Taking Command line arguments in Python.File handling in python – opening the file, file modes, writing a file, detecting the end of the file." }, { "code": null, "e": 30400, "s": 30353, "text": "Discussed all the codes from the online round." }, { "code": null, "e": 30557, "s": 30400, "text": "Switch sort question had a corner case for [3,4,1,2] for which my code won’t work. Made me correct my previous code for 1.5 hours till it was fully correct." }, { "code": null, "e": 30598, "s": 30557, "text": "Taking Command line arguments in Python." }, { "code": null, "e": 30701, "s": 30598, "text": "File handling in python – opening the file, file modes, writing a file, detecting the end of the file." }, { "code": null, "e": 30775, "s": 30701, "text": "Technical Discussion Round 2: This round was with the CTO of the company." }, { "code": null, "e": 31584, "s": 30775, "text": "Started by asking which language I was comfortable with, I said Python.Started with the same command-line arguments and file handling in detail.How to write the main function.How to declare class, how to declare objects?What is the init function? Its function in any development, that is role of init.py? What is your final year project? Explained, no counter questions.Have you done any projects on databases? Explained using python Tkinter library and sqlite3.Have you done any projects on web development? Explained internship project using Angular, typescript, APIs, no counter questions.What OS are you comfortable with? I said Windows, with not much experience with Linux, he said not an issue.How fluent are you in SQL? I said intermediate, asked a query between two tables, gave the logic, satisfied." }, { "code": null, "e": 31656, "s": 31584, "text": "Started by asking which language I was comfortable with, I said Python." }, { "code": null, "e": 31730, "s": 31656, "text": "Started with the same command-line arguments and file handling in detail." }, { "code": null, "e": 31762, "s": 31730, "text": "How to write the main function." }, { "code": null, "e": 31808, "s": 31762, "text": "How to declare class, how to declare objects?" }, { "code": null, "e": 31894, "s": 31808, "text": "What is the init function? Its function in any development, that is role of init.py? " }, { "code": null, "e": 31960, "s": 31894, "text": "What is your final year project? Explained, no counter questions." }, { "code": null, "e": 32053, "s": 31960, "text": "Have you done any projects on databases? Explained using python Tkinter library and sqlite3." }, { "code": null, "e": 32184, "s": 32053, "text": "Have you done any projects on web development? Explained internship project using Angular, typescript, APIs, no counter questions." }, { "code": null, "e": 32293, "s": 32184, "text": "What OS are you comfortable with? I said Windows, with not much experience with Linux, he said not an issue." }, { "code": null, "e": 32402, "s": 32293, "text": "How fluent are you in SQL? I said intermediate, asked a query between two tables, gave the logic, satisfied." }, { "code": null, "e": 32484, "s": 32402, "text": "Special thanks to GeeksforGeeks for the preparation resources. All the very best " }, { "code": null, "e": 32489, "s": 32484, "text": "314e" }, { "code": null, "e": 32499, "s": 32489, "text": "Marketing" }, { "code": null, "e": 32509, "s": 32499, "text": "On-Campus" }, { "code": null, "e": 32531, "s": 32509, "text": "Interview Experiences" }, { "code": null, "e": 32629, "s": 32531, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32638, "s": 32629, "text": "Comments" }, { "code": null, "e": 32651, "s": 32638, "text": "Old Comments" }, { "code": null, "e": 32701, "s": 32651, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 32760, "s": 32701, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 32798, "s": 32760, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 32836, "s": 32798, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 32901, "s": 32836, "text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022" }, { "code": null, "e": 32947, "s": 32901, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 32997, "s": 32947, "text": "Amazon Interview Experience for SDE-1(Off-Campus)" }, { "code": null, "e": 33050, "s": 32997, "text": "Microsoft Interview Experience for SDE-1 (Hyderabad)" }, { "code": null, "e": 33102, "s": 33050, "text": "Google Interview Experience for IT Support Engineer" } ]
XHTML - Syntax
XHTML syntax is very similar to HTML syntax and almost all the valid HTML elements are valid in XHTML as well. But when you write an XHTML document, you need to pay a bit extra attention to make your HTML document compliant to XHTML. Here are the important points to remember while writing a new XHTML document or converting existing HTML document into XHTML document − Write a DOCTYPE declaration at the start of the XHTML document. Write a DOCTYPE declaration at the start of the XHTML document. Write all XHTML tags and attributes in lower case only. Write all XHTML tags and attributes in lower case only. Close all XHTML tags properly. Close all XHTML tags properly. Nest all the tags properly. Nest all the tags properly. Quote all the attribute values. Quote all the attribute values. Forbid Attribute minimization. Forbid Attribute minimization. Replace the name attribute with the id attribute. Replace the name attribute with the id attribute. Deprecate the language attribute of the script tag. Deprecate the language attribute of the script tag. Here is the detail explanation of the above XHTML rules − All XHTML documents must have a DOCTYPE declaration at the start. There are three types of DOCTYPE declarations, which are discussed in detail in XHTML Doctypes chapter. Here is an example of using DOCTYPE − <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> XHTML is case sensitive markup language. All the XHTML tags and attributes need to be written in lower case only. <!-- This is invalid in XHTML --> <A Href="/xhtml/xhtml_tutorial.html">XHTML Tutorial</A> <!-- Correct XHTML way of writing this is as follows --> <a href="/xhtml/xhtml_tutorial.html">XHTML Tutorial</a> In the example, Href and anchor tag A are not in lower case, so it is incorrect. Each and every XHTML tag should have an equivalent closing tag, even empty elements should also have closing tags. Here is an example showing valid and invalid ways of using tags − <!-- This is invalid in XHTML --> <p>This paragraph is not written according to XHTML syntax. <!-- This is also invalid in XHTML --> <img src="/images/xhtml.gif" > The following syntax shows the correct way of writing above tags in XHTML. Difference is that, here we have closed both the tags properly. <!-- This is valid in XHTML --> <p>This paragraph is not written according to XHTML syntax.</p> <!-- This is also valid now --> <img src="/images/xhtml.gif" /> All the values of XHTML attributes must be quoted. Otherwise, your XHTML document is assumed as an invalid document. Here is the example showing syntax − <!-- This is invalid in XHTML --> <img src="/images/xhtml.gif" width=250 height=50 /> <!-- Correct XHTML way of writing this is as follows --> <img src="/images/xhtml.gif" width="250" height="50" /> XHTML does not allow attribute minimization. It means you need to explicitly state the attribute and its value. The following example shows the difference − <!-- This is invalid in XHTML --> <option selected> <!-- Correct XHTML way of writing this is as follows --> <option selected="selected"> Here is a list of the minimized attributes in HTML and the way you need to write them in XHTML − The id attribute replaces the name attribute. Instead of using name = "name", XHTML prefers to use id = "id". The following example shows how − <!-- This is invalid in XHTML --> <img src="/images/xhtml.gif" name="xhtml_logo" /> <!-- Correct XHTML way of writing this is as follows --> <img src="/images/xhtml.gif" id="xhtml_logo" /> The language attribute of the script tag is deprecated. The following example shows this difference − <!-- This is invalid in XHTML --> <script language="JavaScript" type="text/JavaScript"> document.write("Hello XHTML!"); </script> <!-- Correct XHTML way of writing this is as follows --> <script type="text/JavaScript"> document.write("Hello XHTML!"); </script> You must nest all the XHTML tags properly. Otherwise your document is assumed as an incorrect XHTML document. The following example shows the syntax − <!-- This is invalid in XHTML --> <b><i> This text is bold and italic</b></i> <!-- Correct XHTML way of writing this is as follows --> <b><i> This text is bold and italic</i></b> The following elements are not allowed to have any other element inside them. This prohibition applies to all depths of nesting. Means, it includes all the descending elements. The following example shows you a minimum content of an XHTML 1.0 document − <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/TR/xhtml1" xml:lang="en" lang="en"> <head> <title>Every document must have a title</title> </head> <body> ...your content goes here... </body> </html> Print Add Notes Bookmark this page
[ { "code": null, "e": 1983, "s": 1749, "text": "XHTML syntax is very similar to HTML syntax and almost all the valid HTML elements are valid in XHTML as well. But when you write an XHTML document, you need to pay a bit extra attention to make your HTML document compliant to XHTML." }, { "code": null, "e": 2119, "s": 1983, "text": "Here are the important points to remember while writing a new XHTML document or converting existing HTML document into XHTML document −" }, { "code": null, "e": 2183, "s": 2119, "text": "Write a DOCTYPE declaration at the start of the XHTML document." }, { "code": null, "e": 2247, "s": 2183, "text": "Write a DOCTYPE declaration at the start of the XHTML document." }, { "code": null, "e": 2303, "s": 2247, "text": "Write all XHTML tags and attributes in lower case only." }, { "code": null, "e": 2359, "s": 2303, "text": "Write all XHTML tags and attributes in lower case only." }, { "code": null, "e": 2390, "s": 2359, "text": "Close all XHTML tags properly." }, { "code": null, "e": 2421, "s": 2390, "text": "Close all XHTML tags properly." }, { "code": null, "e": 2449, "s": 2421, "text": "Nest all the tags properly." }, { "code": null, "e": 2477, "s": 2449, "text": "Nest all the tags properly." }, { "code": null, "e": 2509, "s": 2477, "text": "Quote all the attribute values." }, { "code": null, "e": 2541, "s": 2509, "text": "Quote all the attribute values." }, { "code": null, "e": 2572, "s": 2541, "text": "Forbid Attribute minimization." }, { "code": null, "e": 2603, "s": 2572, "text": "Forbid Attribute minimization." }, { "code": null, "e": 2653, "s": 2603, "text": "Replace the name attribute with the id attribute." }, { "code": null, "e": 2703, "s": 2653, "text": "Replace the name attribute with the id attribute." }, { "code": null, "e": 2755, "s": 2703, "text": "Deprecate the language attribute of the script tag." }, { "code": null, "e": 2807, "s": 2755, "text": "Deprecate the language attribute of the script tag." }, { "code": null, "e": 2865, "s": 2807, "text": "Here is the detail explanation of the above XHTML rules −" }, { "code": null, "e": 3073, "s": 2865, "text": "All XHTML documents must have a DOCTYPE declaration at the start. There are three types of DOCTYPE declarations, which are discussed in detail in XHTML Doctypes chapter. Here is an example of using DOCTYPE −" }, { "code": null, "e": 3196, "s": 3073, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" }, { "code": null, "e": 3310, "s": 3196, "text": "XHTML is case sensitive markup language. All the XHTML tags and attributes need to be written in lower case only." }, { "code": null, "e": 3514, "s": 3310, "text": "<!-- This is invalid in XHTML -->\n<A Href=\"/xhtml/xhtml_tutorial.html\">XHTML Tutorial</A>\n\n<!-- Correct XHTML way of writing this is as follows -->\n<a href=\"/xhtml/xhtml_tutorial.html\">XHTML Tutorial</a>" }, { "code": null, "e": 3595, "s": 3514, "text": "In the example, Href and anchor tag A are not in lower case, so it is incorrect." }, { "code": null, "e": 3776, "s": 3595, "text": "Each and every XHTML tag should have an equivalent closing tag, even empty elements should also have closing tags. Here is an example showing valid and invalid ways of using tags −" }, { "code": null, "e": 3941, "s": 3776, "text": "<!-- This is invalid in XHTML -->\n<p>This paragraph is not written according to XHTML syntax.\n\n<!-- This is also invalid in XHTML -->\n<img src=\"/images/xhtml.gif\" >" }, { "code": null, "e": 4080, "s": 3941, "text": "The following syntax shows the correct way of writing above tags in XHTML. Difference is that, here we have closed both the tags properly." }, { "code": null, "e": 4241, "s": 4080, "text": "<!-- This is valid in XHTML -->\n<p>This paragraph is not written according to XHTML syntax.</p>\n\n<!-- This is also valid now -->\n<img src=\"/images/xhtml.gif\" />" }, { "code": null, "e": 4395, "s": 4241, "text": "All the values of XHTML attributes must be quoted. Otherwise, your XHTML document is assumed as an invalid document. Here is the example showing syntax −" }, { "code": null, "e": 4595, "s": 4395, "text": "<!-- This is invalid in XHTML -->\n<img src=\"/images/xhtml.gif\" width=250 height=50 />\n\n<!-- Correct XHTML way of writing this is as follows -->\n<img src=\"/images/xhtml.gif\" width=\"250\" height=\"50\" />" }, { "code": null, "e": 4752, "s": 4595, "text": "XHTML does not allow attribute minimization. It means you need to explicitly state the attribute and its value. The following example shows the difference −" }, { "code": null, "e": 4891, "s": 4752, "text": "<!-- This is invalid in XHTML -->\n<option selected>\n\n<!-- Correct XHTML way of writing this is as follows -->\n<option selected=\"selected\">" }, { "code": null, "e": 4988, "s": 4891, "text": "Here is a list of the minimized attributes in HTML and the way you need to write them in XHTML −" }, { "code": null, "e": 5132, "s": 4988, "text": "The id attribute replaces the name attribute. Instead of using name = \"name\", XHTML prefers to use id = \"id\". The following example shows how −" }, { "code": null, "e": 5322, "s": 5132, "text": "<!-- This is invalid in XHTML -->\n<img src=\"/images/xhtml.gif\" name=\"xhtml_logo\" />\n\n<!-- Correct XHTML way of writing this is as follows -->\n<img src=\"/images/xhtml.gif\" id=\"xhtml_logo\" />" }, { "code": null, "e": 5424, "s": 5322, "text": "The language attribute of the script tag is deprecated. The following example shows this difference −" }, { "code": null, "e": 5694, "s": 5424, "text": "<!-- This is invalid in XHTML -->\n\n<script language=\"JavaScript\" type=\"text/JavaScript\">\n document.write(\"Hello XHTML!\");\n</script>\n\n<!-- Correct XHTML way of writing this is as follows -->\n\n<script type=\"text/JavaScript\">\n document.write(\"Hello XHTML!\");\n</script>" }, { "code": null, "e": 5845, "s": 5694, "text": "You must nest all the XHTML tags properly. Otherwise your document is assumed as an incorrect XHTML document. The following example shows the syntax −" }, { "code": null, "e": 6025, "s": 5845, "text": "<!-- This is invalid in XHTML -->\n<b><i> This text is bold and italic</b></i>\n\n<!-- Correct XHTML way of writing this is as follows -->\n<b><i> This text is bold and italic</i></b>" }, { "code": null, "e": 6202, "s": 6025, "text": "The following elements are not allowed to have any other element inside them. This prohibition applies to all depths of nesting. Means, it includes all the descending elements." }, { "code": null, "e": 6279, "s": 6202, "text": "The following example shows you a minimum content of an XHTML 1.0 document −" }, { "code": null, "e": 6650, "s": 6279, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns=\"http://www.w3.org/TR/xhtml1\" xml:lang=\"en\" lang=\"en\">\n <head>\n <title>Every document must have a title</title>\n </head>\n\t\n <body>\n ...your content goes here...\n </body>\n</html>" }, { "code": null, "e": 6657, "s": 6650, "text": " Print" }, { "code": null, "e": 6668, "s": 6657, "text": " Add Notes" } ]
LSTM for predictive maintenance of turbofan engines | by Koen Peters | Towards Data Science
<disclaimer I aim to showcase the effect of different methods and choices made during model development. These effects are often shown using the test set, something which is considered (very) bad practice but helps for educational purposes.> In the last post we developed an MLP with lagged variables for FD002, a dataset in which the engines run on six different operating conditions. Today we’ll wrap-up the series and develop a LSTM for dataset FD004, in which the engines can develop two different faults in addition to running on multiple operating conditions. It’s the biggest challenge within NASA’s turbofan dataset yet, but we can use a lot of the building blocks from last time. Let’s get started! First, we’ll import the required libraries and set the random seeds, such that results will be reproducible. I’ve taken more precautions to create reproducible results, which you can read about here. We’ll load the data next and inspect the first few rows. Looking good. As usual, we compute the Remaining Useful Life (RUL) of the training set. As in the last post, these engines are running on multiple operating conditions. Plotting won’t do us much good without some pre-processing. So, let’s create the baseline model before continuing our analysis. For the baseline model we’ll train a linear regression on the available sensors and engine settings. We’ll set the upper limit of the computed RUL to 125, as it better reflects what we know about the engines RUL [1]. # returns# train set RMSE:21.437942286411495, R2:0.7220738975061722# test set RMSE:34.59373591137396, R2:0.5974472412018376 Our baseline model has a training RMSE of 21.43 and a test RMSE of 34.59, which will be the score to beat. Let’s move on to plotting to select our features. To make sense of the sensor values, we’ll apply the same operating condition-based standardization as last time. This form of standardization essentially applies a standard scaler to each group of datapoints which are running on the same operating condition, centralizing their means and ‘stitching’ the signal together. This form of standardization works for this dataset because the different operating conditions shift the mean of the signal (but doesn’t seem to affect the signal or breakdown in any other way). We’ll first concatenate the values of the settings to get a single variable which indicates the operating condition. Then, we’ll iterate over the groups of operating conditions to fit the standard scaler on the train set and transform both the train and test set. We can now look at some plots. Like last time, sensors 1, 5, 16 and 19 look similar but don’t seem very useful. Sensor 2, 3, 4, 11, and 17 show a similar upward trend and should be included for further model development. Sensors 6, 10 and 16 don’t reveal much trend, we’ll leave those out. Sensor 7, 12, 15, 20 and 21 clearly show the distinction between the two faults being developed. Sensor 8, 9, 13, 14 show similar patterns but with the addition of a fault condition, these signals might do more harm than good for model performance. As the signals don’t seem to distinguish between faults very well. Trying a model with and without these sensors will have to show whether these features should be included. Sensor 18 doesn’t seem to hold any information after condition-based standardization. Time to start preparing for our LSTM. Explaining how an LSTM works is a bit out of scope for this blogpost, you can find excellent resources on the internet if you wish to read-up on the technique [2]. I will focus mostly on how to apply the algorithm. I’ve mainly chosen the LSTM for its capability to work with sequences, which is a useful way of arranging your data while working with timeseries. I’ll explain how to create sequences further down below. We can re-use some of the functions from last time, like exponential smoothing and train-validation split. Exponential smoothing is a simple yet powerful smoothing algorithm. See the simplified formula below [3]. ~Xt = a*Xt + (1 - a)*~Xt-1 Where ~Xt is the filtered value of Xt and α the strength of the filter. Alpha can hold a value between 0–1. When alpha = 0.8, the filtered datapoint will be comprised of 80% of the value at Xt and 20% of the (already filtered) value at Xt-1. Values of alpha closer to 0 result in a more prominent smoothing effect. It’s important for model validation that records of a single engine don’t get divided between train and validation sets. The LSTM may be able to predict correctly on the validation set by interpolation, which provides a false sense of the prediction error. When the model is fed truly unseen data it will perform much worse as it can no longer predict the RUL by interpolation. The train_val_group_split splits the data in such a way that all records of a single engine are assigned to either the training or validation set. Next, we’ll discuss generating the sequences used by LSTM models. Ideally, you’d use something like TimeseriesGenerator from tensorflow to create your sequences, but there’s a few reasons why I opt to use custom code. First, we need to account for unit_nrs. Sequences should only have data of a single unit_nr to prevent mixing records where failure is imminent with records of the next engine in the train set which is still running fine. Second, timeseries usually use X timepoints to predict Yt+1, whereas I want to predict Yt. Predicting Yt instead of Yt+1 achieves two things: (I) First and foremost, it’s in line with all previous data framings we’ve used throughout this short series and (II) it allows us to feed a tiny bit more data to the algorithm. Where you’d naturally use your second to last record to predict the last target, we can now use the last record to predict the last target (see figure 1 below). Although, it’s only 1 additional record per engine, it can make a difference for very small subsets. For example, some engines in the test set only consist of a couple of records. I have been inspired by code on Microsoft Azure’s github page to create the sequences [4] but have made some considerable changes. The code has been updated to implement the sequence generation on the right (see figure 1) and to include padding sequences of the test set (which I’ll explain further down below). The example dataframe from figure 1 is used to showcase the effects of the sequence generating code. The function gen_train_data was designed to receive a dataframe containing records of a single engine. When creating sequences of length=4, it is able to return 2 arrays (or sequences). One from index 0 up to and including index 3, and the other from index 1 up to and including index 4. The values of the returned sequences should make it easy to check them against the example dataframe (figure 1) and understanding what is happening. Next, we’ll write a wrapper function to generate these sequences for multiple engines. We’ll do something similar for the labels to predict. Notice that the 3rd and 4th index values are returned, matching the sequences above. Again, the wrapper is able to generate the labels for multiple engines. Generating the test data is a bit trickier. The original code would discard engines from the test set if they had less records than the desired sequence length [4]. Because models generally can’t cope with sequences which vary in length. By introducing padding, we can keep all the engines in the test set. Let’s say we want to create a sequence of length=5, but we only have 2 rows available. We can prefix (or pad) the missing 3 rows with some dummy values so our model will receive sequences of the desired length. Later on we can program our model to ignore the dummy values, but let’s first implement a padding function for our example dataframe. The example dataframe has 5 rows per engine, in the code above we want to create a sequence of length=6. As in the padding example, the available rows are returned as a sequence with dummy values prefixed, or padded, to get the desired sequence length. Note, I’ve put the mask value as a float to be in line with the other values in the dataframe. We now have all the building blocks to train the first LSTM. First, we combine all the preprocessing steps to prepare our data for modelling. The initial model is defined with a single LSTM layer. The masking layer allows us to pass the padded dummy values without the model interpreting them. Next, we’ll compile the model and save its weights. The model is recompiled, and its weights reloaded before training to ensure reproducibility [5]. Notice the training times are about 5 times higher compared to the MLP from last time. At this stage I would normally start looking into cloud computing (especially for hyperparameter tuning further down below), but for this series we’ll keep everything on a commodity laptop. Looking at the train and validation loss everything seems to be fine. Let’s evaluate model performance. # returns:# train set RMSE:16.55081558227539, R2:0.8388066627963793# test set RMSE:29.043230109223934, R2:0.7162618665206494 With an RMSE of 29.043 the current LSTM is already a 16.04% improvement over the baseline model. There are two more things to check before hyperparameter tuning;- (I) model performance without sensors 8, 9, 13 and 14 and- (II) validation loss behavior when running more epochs To test the model performance without sensors 8, 9, 13 and 14 we have to update our remaining_sensors variable Because we remove a few sensors from the model inputs, we also have to re-instantiate our model to accommodate for the change in data shape. Re-instantiating our model means a new set of random weights will be initialized, making it more difficult to judge whether changes in model performance are due to the change in features or the random weights. No other changes have to be made so let’s re-run everything and check the results to see if we can draw any conclusions. # returns:# train set RMSE:17.098350524902344, R2:0.8279650412665183# test set RMSE:29.36311002353286, R2:0.709977307051393 Both training and validation loss have increased a bit and the test RMSE has also increased by .3. It may be difficult to fully account this change to the removal of the sensors compared to the re-initialized model weights. To be sure we’ll include both sets of sensors in the hyperparameter tuning approach. Like last time, let’s train once more with considerably increased epochs to view how the validation loss behaves # returns:# train set RMSE:15.545417785644531, R2:0.857795579414809# test set RMSE:29.32099593032191, R2:0.7108086415870063 The validation loss seems quite stable, however, the models starts to overfit slightly after 15 epochs. We can play around with different epochs but shouldn’t push it too far. We’ll use a similar hyperparameter tuning setup as last time. Parameters to tune are:- alpha, filter strength- sequence_length- epochs- number of layers- nodes per layer- dropout- optimizer (I choose to not tune this parameter)- learning rate (I choose to not tune this parameter)- activation function- batch size- included sensors Let’s define the possible values for the parameters. With over 100k unique hyperparameter combinations, testing all of them would take ages. I’m opting for a random gridsearch as it’s much less time consuming with only a minor setback in overall performance [6]. Next, we’ll define the functions to prepare our data and create the model. Finally, we define the number of iterations and the main code for running the hyperparameter tuning. Note, for the GroupShuffleSplit the number of splits has been set to 3, meaning we’ll train and crossvalidate each unique combination of hyperparameters 3 times. The mean and standard deviation of the validation loss are saved alongside the hyperparameters for that specific iteration. I’ve run the random gridsearch multiple times with different variations (e.g. with early stopping and different ranges for the parameters). The last tuning job was halted after 55 iterations as my laptop slowed to a crawl, however the best result seemed to be rather consistent, with a validation loss slightly above 200 MSE. Let’s have a look at the result. As you can see, iterations without sensors 8, 9, 13 and 14 didn’t make it to the top 5, giving stronger evidence that it is better to keep those sensors included. Let’s retrain our model with the best performing hyperparameters and check the result. # returns:# train set RMSE:12.35975170135498, R2:0.9112171726749143# test set RMSE:25.35340838205415, R2:0.7837776516770107 The final test RMSE is 25.353, which is a 26.71% improvement over our baseline model. When compared to the literature (see overviews in [3] and [8]), results seem to be on par with those from 2017/2018 state of the art approaches. Which I think is quite neat given the solution isn’t overly complex. Running more iterations and also tuning the optimizer and learning rate could probably push this a little further. Looking back at this short series, I had a lot of fun analysing the datasets and developing the models. It was really interesting for me to see how the change in problem framing, by clipping the linearly computed RUL to an upper limit, arguably resulted in the largest improvement in model accuracy. Showcasing the importance of framing your problem correctly. In addition, it was a personal win to learn and apply survival analysis to a predictive maintenance dataset, as I had not encountered a good and clear example of that technique for predictive maintenance. I hope this series gave you a good introduction into (some) predictive maintenance methods. The write-up, examples and explanations would have definitely helped me when starting out. If you want to improve further, I’d suggest reading a few papers on more complex preprocessing and neural network architectures, as well as changing the error measure from RMSE to one which penalizes late predictions (see [3] for an example on a different error measure). Another interesting approach would be to calculate/predict the asset health index [8–10]. The idea is to have a single, abstract, KPI informing on the overall health of the equipment, you could break this down further by specifying each sensor’s contribution to the overall score. Last but not least, incorporating domain knowledge greatly improves your ability to come up with a fitting solution. Try to understand the mechanics at play and talk to experts to get pointers you may have overlooked or couldn’t understand based on the data alone. You can find the full code on my github page here. I would like to give a big shout-out to Maikel Grobbe, for having numerous discussions with me and reviewing all my articles. In addition, I’d like to thank you for reading and as always, if you have any questions or remarks, please leave them in the comments below! References[1] F. O. Heimes, “Recurrent neural networks for remaining useful life estimation,” 2008 International Conference on Prognostics and Health Management, Denver, CO, 2008, pp. 1–6, doi: 10.1109/PHM.2008.4711422.[2] http://colah.github.io/posts/2015-08-Understanding-LSTMs/[3] Duarte Pasa, G., Paixão de Medeiros, I., & Yoneyama, T. (2019). Operating Condition-Invariant Neural Network-based Prognostics Methods applied on Turbofan Aircraft Engines. Annual Conference of the PHM Society, 11(1). https://doi.org/10.36001/phmconf.2019.v11i1.786[4] https://github.com/Azure/lstms_for_predictive_maintenance[5] Primer on developing reproducible Neural Networks in Jupyter Notebook[6] Zheng, Alice. Evaluating Machine Learning Models. O’Reilly Media, Inc. 2015[7] J. Li, X. Li and D. He, “A Directed Acyclic Graph Network Combined With CNN and LSTM for Remaining Useful Life Prediction,” in IEEE Access, vol. 7, pp. 75464–75475, 2019, doi: 10.1109/ACCESS.2019.2919566.[8] https://www.researchgate.net/profile/Jianjun_Shi/publication/260662503_A_Data-Level_Fusion_Model_for_Developing_Composite_Health_Indices_for_Degradation_Modeling_and_Prognostic_Analysis/links/553e47d80cf20184050e16ea.pdf[9] http://www.pubmanitoba.ca/v1/exhibits/mh_gra_2015/coalition-10-3.pdf[10] https://www.wapa.gov/About/the-source/Documents/AMtoolkitTSSymposium0818.pdf
[ { "code": null, "e": 289, "s": 47, "text": "<disclaimer I aim to showcase the effect of different methods and choices made during model development. These effects are often shown using the test set, something which is considered (very) bad practice but helps for educational purposes.>" }, { "code": null, "e": 755, "s": 289, "text": "In the last post we developed an MLP with lagged variables for FD002, a dataset in which the engines run on six different operating conditions. Today we’ll wrap-up the series and develop a LSTM for dataset FD004, in which the engines can develop two different faults in addition to running on multiple operating conditions. It’s the biggest challenge within NASA’s turbofan dataset yet, but we can use a lot of the building blocks from last time. Let’s get started!" }, { "code": null, "e": 955, "s": 755, "text": "First, we’ll import the required libraries and set the random seeds, such that results will be reproducible. I’ve taken more precautions to create reproducible results, which you can read about here." }, { "code": null, "e": 1012, "s": 955, "text": "We’ll load the data next and inspect the first few rows." }, { "code": null, "e": 1100, "s": 1012, "text": "Looking good. As usual, we compute the Remaining Useful Life (RUL) of the training set." }, { "code": null, "e": 1309, "s": 1100, "text": "As in the last post, these engines are running on multiple operating conditions. Plotting won’t do us much good without some pre-processing. So, let’s create the baseline model before continuing our analysis." }, { "code": null, "e": 1526, "s": 1309, "text": "For the baseline model we’ll train a linear regression on the available sensors and engine settings. We’ll set the upper limit of the computed RUL to 125, as it better reflects what we know about the engines RUL [1]." }, { "code": null, "e": 1650, "s": 1526, "text": "# returns# train set RMSE:21.437942286411495, R2:0.7220738975061722# test set RMSE:34.59373591137396, R2:0.5974472412018376" }, { "code": null, "e": 1807, "s": 1650, "text": "Our baseline model has a training RMSE of 21.43 and a test RMSE of 34.59, which will be the score to beat. Let’s move on to plotting to select our features." }, { "code": null, "e": 2323, "s": 1807, "text": "To make sense of the sensor values, we’ll apply the same operating condition-based standardization as last time. This form of standardization essentially applies a standard scaler to each group of datapoints which are running on the same operating condition, centralizing their means and ‘stitching’ the signal together. This form of standardization works for this dataset because the different operating conditions shift the mean of the signal (but doesn’t seem to affect the signal or breakdown in any other way)." }, { "code": null, "e": 2618, "s": 2323, "text": "We’ll first concatenate the values of the settings to get a single variable which indicates the operating condition. Then, we’ll iterate over the groups of operating conditions to fit the standard scaler on the train set and transform both the train and test set. We can now look at some plots." }, { "code": null, "e": 2699, "s": 2618, "text": "Like last time, sensors 1, 5, 16 and 19 look similar but don’t seem very useful." }, { "code": null, "e": 2808, "s": 2699, "text": "Sensor 2, 3, 4, 11, and 17 show a similar upward trend and should be included for further model development." }, { "code": null, "e": 2877, "s": 2808, "text": "Sensors 6, 10 and 16 don’t reveal much trend, we’ll leave those out." }, { "code": null, "e": 2974, "s": 2877, "text": "Sensor 7, 12, 15, 20 and 21 clearly show the distinction between the two faults being developed." }, { "code": null, "e": 3300, "s": 2974, "text": "Sensor 8, 9, 13, 14 show similar patterns but with the addition of a fault condition, these signals might do more harm than good for model performance. As the signals don’t seem to distinguish between faults very well. Trying a model with and without these sensors will have to show whether these features should be included." }, { "code": null, "e": 3424, "s": 3300, "text": "Sensor 18 doesn’t seem to hold any information after condition-based standardization. Time to start preparing for our LSTM." }, { "code": null, "e": 3843, "s": 3424, "text": "Explaining how an LSTM works is a bit out of scope for this blogpost, you can find excellent resources on the internet if you wish to read-up on the technique [2]. I will focus mostly on how to apply the algorithm. I’ve mainly chosen the LSTM for its capability to work with sequences, which is a useful way of arranging your data while working with timeseries. I’ll explain how to create sequences further down below." }, { "code": null, "e": 3950, "s": 3843, "text": "We can re-use some of the functions from last time, like exponential smoothing and train-validation split." }, { "code": null, "e": 4056, "s": 3950, "text": "Exponential smoothing is a simple yet powerful smoothing algorithm. See the simplified formula below [3]." }, { "code": null, "e": 4083, "s": 4056, "text": "~Xt = a*Xt + (1 - a)*~Xt-1" }, { "code": null, "e": 4398, "s": 4083, "text": "Where ~Xt is the filtered value of Xt and α the strength of the filter. Alpha can hold a value between 0–1. When alpha = 0.8, the filtered datapoint will be comprised of 80% of the value at Xt and 20% of the (already filtered) value at Xt-1. Values of alpha closer to 0 result in a more prominent smoothing effect." }, { "code": null, "e": 4923, "s": 4398, "text": "It’s important for model validation that records of a single engine don’t get divided between train and validation sets. The LSTM may be able to predict correctly on the validation set by interpolation, which provides a false sense of the prediction error. When the model is fed truly unseen data it will perform much worse as it can no longer predict the RUL by interpolation. The train_val_group_split splits the data in such a way that all records of a single engine are assigned to either the training or validation set." }, { "code": null, "e": 4989, "s": 4923, "text": "Next, we’ll discuss generating the sequences used by LSTM models." }, { "code": null, "e": 5141, "s": 4989, "text": "Ideally, you’d use something like TimeseriesGenerator from tensorflow to create your sequences, but there’s a few reasons why I opt to use custom code." }, { "code": null, "e": 5363, "s": 5141, "text": "First, we need to account for unit_nrs. Sequences should only have data of a single unit_nr to prevent mixing records where failure is imminent with records of the next engine in the train set which is still running fine." }, { "code": null, "e": 5505, "s": 5363, "text": "Second, timeseries usually use X timepoints to predict Yt+1, whereas I want to predict Yt. Predicting Yt instead of Yt+1 achieves two things:" }, { "code": null, "e": 5618, "s": 5505, "text": "(I) First and foremost, it’s in line with all previous data framings we’ve used throughout this short series and" }, { "code": null, "e": 6024, "s": 5618, "text": "(II) it allows us to feed a tiny bit more data to the algorithm. Where you’d naturally use your second to last record to predict the last target, we can now use the last record to predict the last target (see figure 1 below). Although, it’s only 1 additional record per engine, it can make a difference for very small subsets. For example, some engines in the test set only consist of a couple of records." }, { "code": null, "e": 6336, "s": 6024, "text": "I have been inspired by code on Microsoft Azure’s github page to create the sequences [4] but have made some considerable changes. The code has been updated to implement the sequence generation on the right (see figure 1) and to include padding sequences of the test set (which I’ll explain further down below)." }, { "code": null, "e": 6437, "s": 6336, "text": "The example dataframe from figure 1 is used to showcase the effects of the sequence generating code." }, { "code": null, "e": 6874, "s": 6437, "text": "The function gen_train_data was designed to receive a dataframe containing records of a single engine. When creating sequences of length=4, it is able to return 2 arrays (or sequences). One from index 0 up to and including index 3, and the other from index 1 up to and including index 4. The values of the returned sequences should make it easy to check them against the example dataframe (figure 1) and understanding what is happening." }, { "code": null, "e": 6961, "s": 6874, "text": "Next, we’ll write a wrapper function to generate these sequences for multiple engines." }, { "code": null, "e": 7015, "s": 6961, "text": "We’ll do something similar for the labels to predict." }, { "code": null, "e": 7172, "s": 7015, "text": "Notice that the 3rd and 4th index values are returned, matching the sequences above. Again, the wrapper is able to generate the labels for multiple engines." }, { "code": null, "e": 7690, "s": 7172, "text": "Generating the test data is a bit trickier. The original code would discard engines from the test set if they had less records than the desired sequence length [4]. Because models generally can’t cope with sequences which vary in length. By introducing padding, we can keep all the engines in the test set. Let’s say we want to create a sequence of length=5, but we only have 2 rows available. We can prefix (or pad) the missing 3 rows with some dummy values so our model will receive sequences of the desired length." }, { "code": null, "e": 7824, "s": 7690, "text": "Later on we can program our model to ignore the dummy values, but let’s first implement a padding function for our example dataframe." }, { "code": null, "e": 8172, "s": 7824, "text": "The example dataframe has 5 rows per engine, in the code above we want to create a sequence of length=6. As in the padding example, the available rows are returned as a sequence with dummy values prefixed, or padded, to get the desired sequence length. Note, I’ve put the mask value as a float to be in line with the other values in the dataframe." }, { "code": null, "e": 8233, "s": 8172, "text": "We now have all the building blocks to train the first LSTM." }, { "code": null, "e": 8314, "s": 8233, "text": "First, we combine all the preprocessing steps to prepare our data for modelling." }, { "code": null, "e": 8518, "s": 8314, "text": "The initial model is defined with a single LSTM layer. The masking layer allows us to pass the padded dummy values without the model interpreting them. Next, we’ll compile the model and save its weights." }, { "code": null, "e": 8615, "s": 8518, "text": "The model is recompiled, and its weights reloaded before training to ensure reproducibility [5]." }, { "code": null, "e": 8892, "s": 8615, "text": "Notice the training times are about 5 times higher compared to the MLP from last time. At this stage I would normally start looking into cloud computing (especially for hyperparameter tuning further down below), but for this series we’ll keep everything on a commodity laptop." }, { "code": null, "e": 8996, "s": 8892, "text": "Looking at the train and validation loss everything seems to be fine. Let’s evaluate model performance." }, { "code": null, "e": 9121, "s": 8996, "text": "# returns:# train set RMSE:16.55081558227539, R2:0.8388066627963793# test set RMSE:29.043230109223934, R2:0.7162618665206494" }, { "code": null, "e": 9218, "s": 9121, "text": "With an RMSE of 29.043 the current LSTM is already a 16.04% improvement over the baseline model." }, { "code": null, "e": 9398, "s": 9218, "text": "There are two more things to check before hyperparameter tuning;- (I) model performance without sensors 8, 9, 13 and 14 and- (II) validation loss behavior when running more epochs" }, { "code": null, "e": 9509, "s": 9398, "text": "To test the model performance without sensors 8, 9, 13 and 14 we have to update our remaining_sensors variable" }, { "code": null, "e": 9981, "s": 9509, "text": "Because we remove a few sensors from the model inputs, we also have to re-instantiate our model to accommodate for the change in data shape. Re-instantiating our model means a new set of random weights will be initialized, making it more difficult to judge whether changes in model performance are due to the change in features or the random weights. No other changes have to be made so let’s re-run everything and check the results to see if we can draw any conclusions." }, { "code": null, "e": 10105, "s": 9981, "text": "# returns:# train set RMSE:17.098350524902344, R2:0.8279650412665183# test set RMSE:29.36311002353286, R2:0.709977307051393" }, { "code": null, "e": 10414, "s": 10105, "text": "Both training and validation loss have increased a bit and the test RMSE has also increased by .3. It may be difficult to fully account this change to the removal of the sensors compared to the re-initialized model weights. To be sure we’ll include both sets of sensors in the hyperparameter tuning approach." }, { "code": null, "e": 10527, "s": 10414, "text": "Like last time, let’s train once more with considerably increased epochs to view how the validation loss behaves" }, { "code": null, "e": 10651, "s": 10527, "text": "# returns:# train set RMSE:15.545417785644531, R2:0.857795579414809# test set RMSE:29.32099593032191, R2:0.7108086415870063" }, { "code": null, "e": 10827, "s": 10651, "text": "The validation loss seems quite stable, however, the models starts to overfit slightly after 15 epochs. We can play around with different epochs but shouldn’t push it too far." }, { "code": null, "e": 10889, "s": 10827, "text": "We’ll use a similar hyperparameter tuning setup as last time." }, { "code": null, "e": 11159, "s": 10889, "text": "Parameters to tune are:- alpha, filter strength- sequence_length- epochs- number of layers- nodes per layer- dropout- optimizer (I choose to not tune this parameter)- learning rate (I choose to not tune this parameter)- activation function- batch size- included sensors" }, { "code": null, "e": 11212, "s": 11159, "text": "Let’s define the possible values for the parameters." }, { "code": null, "e": 11422, "s": 11212, "text": "With over 100k unique hyperparameter combinations, testing all of them would take ages. I’m opting for a random gridsearch as it’s much less time consuming with only a minor setback in overall performance [6]." }, { "code": null, "e": 11497, "s": 11422, "text": "Next, we’ll define the functions to prepare our data and create the model." }, { "code": null, "e": 11598, "s": 11497, "text": "Finally, we define the number of iterations and the main code for running the hyperparameter tuning." }, { "code": null, "e": 11884, "s": 11598, "text": "Note, for the GroupShuffleSplit the number of splits has been set to 3, meaning we’ll train and crossvalidate each unique combination of hyperparameters 3 times. The mean and standard deviation of the validation loss are saved alongside the hyperparameters for that specific iteration." }, { "code": null, "e": 12243, "s": 11884, "text": "I’ve run the random gridsearch multiple times with different variations (e.g. with early stopping and different ranges for the parameters). The last tuning job was halted after 55 iterations as my laptop slowed to a crawl, however the best result seemed to be rather consistent, with a validation loss slightly above 200 MSE. Let’s have a look at the result." }, { "code": null, "e": 12493, "s": 12243, "text": "As you can see, iterations without sensors 8, 9, 13 and 14 didn’t make it to the top 5, giving stronger evidence that it is better to keep those sensors included. Let’s retrain our model with the best performing hyperparameters and check the result." }, { "code": null, "e": 12617, "s": 12493, "text": "# returns:# train set RMSE:12.35975170135498, R2:0.9112171726749143# test set RMSE:25.35340838205415, R2:0.7837776516770107" }, { "code": null, "e": 13032, "s": 12617, "text": "The final test RMSE is 25.353, which is a 26.71% improvement over our baseline model. When compared to the literature (see overviews in [3] and [8]), results seem to be on par with those from 2017/2018 state of the art approaches. Which I think is quite neat given the solution isn’t overly complex. Running more iterations and also tuning the optimizer and learning rate could probably push this a little further." }, { "code": null, "e": 13598, "s": 13032, "text": "Looking back at this short series, I had a lot of fun analysing the datasets and developing the models. It was really interesting for me to see how the change in problem framing, by clipping the linearly computed RUL to an upper limit, arguably resulted in the largest improvement in model accuracy. Showcasing the importance of framing your problem correctly. In addition, it was a personal win to learn and apply survival analysis to a predictive maintenance dataset, as I had not encountered a good and clear example of that technique for predictive maintenance." }, { "code": null, "e": 14334, "s": 13598, "text": "I hope this series gave you a good introduction into (some) predictive maintenance methods. The write-up, examples and explanations would have definitely helped me when starting out. If you want to improve further, I’d suggest reading a few papers on more complex preprocessing and neural network architectures, as well as changing the error measure from RMSE to one which penalizes late predictions (see [3] for an example on a different error measure). Another interesting approach would be to calculate/predict the asset health index [8–10]. The idea is to have a single, abstract, KPI informing on the overall health of the equipment, you could break this down further by specifying each sensor’s contribution to the overall score." }, { "code": null, "e": 14599, "s": 14334, "text": "Last but not least, incorporating domain knowledge greatly improves your ability to come up with a fitting solution. Try to understand the mechanics at play and talk to experts to get pointers you may have overlooked or couldn’t understand based on the data alone." }, { "code": null, "e": 14917, "s": 14599, "text": "You can find the full code on my github page here. I would like to give a big shout-out to Maikel Grobbe, for having numerous discussions with me and reviewing all my articles. In addition, I’d like to thank you for reading and as always, if you have any questions or remarks, please leave them in the comments below!" } ]
How do I write a function that takes an array of values and returns an object JavaScript?
Let’s say, we are required to write a function classifyArray() that takes in an array which contains mixed data types and returns a Map() with the elements grouped by their data types. For example − // if the input array is: const arr = ['class', 2, [7, 8, 9], {"name": "Michael"}, Symbol('foo'), true, false, 'name', 6]; // then the output Map should be: Map(5) { 'string' => [ 'class', 'name' ], 'number' => [ 2, 6 ], 'object' => [ [ 7, 8, 9 ], { name: 'Michael' } ], 'symbol' => [ Symbol(foo) ], 'boolean' => [ true, false ] } Now let’s write the code for this function − const arr = ['class', 2, [7, 8, 9], {"name": "Michael"}, Symbol('foo'), true, false, 'name', 6]; const classifyArray = arr => { return arr.reduce((acc, val) => { const previousData = acc.get(typeof val); if(previousData){ acc.set(typeof val, [...previousData, val]); }else{ acc.set(typeof val, [val]); }; return acc; }, new Map()); }; console.log(classifyArray(arr)); The output in the console will be − Map(5) { 'string' => [ 'class', 'name' ], 'number' => [ 2, 6 ], 'object' => [ [ 7, 8, 9 ], { name: 'Michael' } ], 'symbol' => [ Symbol(foo) ], 'boolean' => [ true, false ] }
[ { "code": null, "e": 1247, "s": 1062, "text": "Let’s say, we are required to write a function classifyArray() that takes in an array which\ncontains mixed data types and returns a Map() with the elements grouped by their data types." }, { "code": null, "e": 1261, "s": 1247, "text": "For example −" }, { "code": null, "e": 1607, "s": 1261, "text": "// if the input array is:\nconst arr = ['class', 2, [7, 8, 9], {\"name\": \"Michael\"}, Symbol('foo'),\ntrue, false, 'name', 6];\n// then the output Map should be:\nMap(5) {\n 'string' => [ 'class', 'name' ],\n 'number' => [ 2, 6 ],\n 'object' => [ [ 7, 8, 9 ], { name: 'Michael' } ],\n 'symbol' => [ Symbol(foo) ],\n 'boolean' => [ true, false ]\n}" }, { "code": null, "e": 1652, "s": 1607, "text": "Now let’s write the code for this function −" }, { "code": null, "e": 2074, "s": 1652, "text": "const arr = ['class', 2, [7, 8, 9], {\"name\": \"Michael\"}, Symbol('foo'),\ntrue, false, 'name', 6];\nconst classifyArray = arr => {\n return arr.reduce((acc, val) => {\n const previousData = acc.get(typeof val);\n if(previousData){\n acc.set(typeof val, [...previousData, val]);\n }else{\n acc.set(typeof val, [val]);\n };\n return acc;\n }, new Map());\n};\nconsole.log(classifyArray(arr));" }, { "code": null, "e": 2110, "s": 2074, "text": "The output in the console will be −" }, { "code": null, "e": 2299, "s": 2110, "text": "Map(5) {\n 'string' => [ 'class', 'name' ],\n 'number' => [ 2, 6 ],\n 'object' => [ [ 7, 8, 9 ], { name: 'Michael' } ],\n 'symbol' => [ Symbol(foo) ],\n 'boolean' => [ true, false ]\n}" } ]
What is run time polymorphism in C#?
Runtime polymorphism has method overriding that is also known as dynamic binding or late binding. It is implemented by abstract classes and virtual functions. Abstract classes contain abstract methods, which are implemented by the derived class. Let us see an example of abstract classes that implements run time polymorphism − Live Demo using System; namespace PolymorphismApplication { abstract class Shape { public abstract int area(); } class Rectangle: Shape { private int length; private int width; public Rectangle( int a = 0, int b = 0) { length = a; width = b; } public override int area () { Console.WriteLine("Rectangle class area :"); return (width * length); } } class RectangleTester { static void Main(string[] args) { Rectangle r = new Rectangle(10, 7); double a = r.area(); Console.WriteLine("Area: {0}",a); Console.ReadKey(); } } } Rectangle class area : Area: 70 When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime.
[ { "code": null, "e": 1221, "s": 1062, "text": "Runtime polymorphism has method overriding that is also known as dynamic binding or late binding. It is implemented by abstract classes and virtual functions." }, { "code": null, "e": 1308, "s": 1221, "text": "Abstract classes contain abstract methods, which are implemented by the derived class." }, { "code": null, "e": 1390, "s": 1308, "text": "Let us see an example of abstract classes that implements run time polymorphism −" }, { "code": null, "e": 1401, "s": 1390, "text": " Live Demo" }, { "code": null, "e": 2065, "s": 1401, "text": "using System;\n\nnamespace PolymorphismApplication {\n abstract class Shape {\n public abstract int area();\n }\n\n class Rectangle: Shape {\n private int length;\n private int width;\n\n public Rectangle( int a = 0, int b = 0) {\n length = a;\n width = b;\n }\n\n public override int area () {\n Console.WriteLine(\"Rectangle class area :\");\n return (width * length);\n }\n }\n\n class RectangleTester {\n static void Main(string[] args) {\n Rectangle r = new Rectangle(10, 7);\n double a = r.area();\n Console.WriteLine(\"Area: {0}\",a);\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 2097, "s": 2065, "text": "Rectangle class area :\nArea: 70" }, { "code": null, "e": 2371, "s": 2097, "text": "When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime." } ]
SAS - Concatenate Data Sets
Multiple SAS data sets can be concatenated to give a single data set using the SET statement. The total number of observations in the concatenated data set is the sum of the number of observations in the original data sets. The order of observations is sequential. All observations from the first data set are followed by all observations from the second data set, and so on. Ideally all the combining data sets have same variables, but in case they have different number of variables, then in the result all the variables appear, with missing values for the smaller data set. The basic syntax for SET statement in SAS is − SET data-set 1 data-set 2 data-set 3.....; Following is the description of the parameters used − data-set1,data-set2 are dataset names written one after another. data-set1,data-set2 are dataset names written one after another. Consider the employee data of an organization which is available in two different data sets, one for the IT department and another for Non-It department. To get the complete details of all the employees we concatenate both the data sets using the SET statement shown as below. DATA ITDEPT; INPUT empid name $ salary ; DATALINES; 1 Rick 623.3 3 Mike 611.5 6 Tusar 578.6 ; RUN; DATA NON_ITDEPT; INPUT empid name $ salary ; DATALINES; 2 Dan 515.2 4 Ryan 729.1 5 Gary 843.25 7 Pranab 632.8 8 Rasmi 722.5 RUN; DATA All_Dept; SET ITDEPT NON_ITDEPT; RUN; PROC PRINT DATA = All_Dept; RUN; When the above code is executed, we get the following output. When we have many variations in the data sets for concatenation, the result of variables can differ but the total number of observations in the concatenated data set is always the sum of the observations in each data set. We will consider below many scenarios on this variation. If one of the original data set has more number of variables then another, then the data sets still get combined but in the smaller data set those variables appear as missing. In below example the first data set has an extra variable named DOJ. In the result the value of DOJ for second data set will appear as missing. DATA ITDEPT; INPUT empid name $ salary DOJ date9. ; DATALINES; 1 Rick 623.3 02APR2001 3 Mike 611.5 21OCT2000 6 Tusar 578.6 01MAR2009 ; RUN; DATA NON_ITDEPT; INPUT empid name $ salary ; DATALINES; 2 Dan 515.2 4 Ryan 729.1 5 Gary 843.25 7 Pranab 632.8 8 Rasmi 722.5 RUN; DATA All_Dept; SET ITDEPT NON_ITDEPT; RUN; PROC PRINT DATA = All_Dept; RUN; When the above code is executed, we get the following output. In this scenario the data sets have same number of variables but a variable name differs between them. In that case a normal concatenation will produce all the variables in the result set and giving missing results for the two variables which differ. While we may not change the variable name in the original data sets we can apply the RENAME function in the concatenated data set we create. That will produce the same result as a normal concatenation but of course with one new variable name in place of two different variable names present in the original data set. In the below example data set ITDEPT has the variable name ename whereas the data set NON_ITDEPT has the variable name empname. But both of these variables represent the same type(character). We apply the RENAME function in the SET statement as shown below. DATA ITDEPT; INPUT empid ename $ salary ; DATALINES; 1 Rick 623.3 3 Mike 611.5 6 Tusar 578.6 ; RUN; DATA NON_ITDEPT; INPUT empid empname $ salary ; DATALINES; 2 Dan 515.2 4 Ryan 729.1 5 Gary 843.25 7 Pranab 632.8 8 Rasmi 722.5 RUN; DATA All_Dept; SET ITDEPT(RENAME =(ename = Employee) ) NON_ITDEPT(RENAME =(empname = Employee) ); RUN; PROC PRINT DATA = All_Dept; RUN; When the above code is executed, we get the following output. If the variable lengths in the two data sets is different than the concatenated data set will have values in which some data is truncated for the variable with smaller length. It happens if the first data set has a smaller length. To solve this we apply the higher length to both the data set as shown below. In the below example the variable ename is of length 5 in the first data set and 7 in the second. When concatenating we apply the LENGTH statement in the concatenated data set to set the ename length to 7. DATA ITDEPT; INPUT empid 1-2 ename $ 3-7 salary 8-14 ; DATALINES; 1 Rick 623.3 3 Mike 611.5 6 Tusar 578.6 ; RUN; DATA NON_ITDEPT; INPUT empid 1-2 ename $ 3-9 salary 10-16 ; DATALINES; 2 Dan 515.2 4 Ryan 729.1 5 Gary 843.25 7 Pranab 632.8 8 Rasmi 722.5 RUN; DATA All_Dept; LENGTH ename $ 7 ; SET ITDEPT NON_ITDEPT ; RUN; PROC PRINT DATA = All_Dept; RUN; When the above code is executed, we get the following output. 50 Lectures 5.5 hours Code And Create 124 Lectures 30 hours Juan Galvan 162 Lectures 31.5 hours Yossef Ayman Zedan 35 Lectures 2.5 hours Ermin Dedic 167 Lectures 45.5 hours Muslim Helalee Print Add Notes Bookmark this page
[ { "code": null, "e": 2960, "s": 2583, "text": "Multiple SAS data sets can be concatenated to give a single data set using the SET statement. The total number of observations in the concatenated data set is the sum of the number of observations in the original data sets. The order of observations is sequential. All observations from the first data set are followed by all observations from the second data set, and so on." }, { "code": null, "e": 3161, "s": 2960, "text": "Ideally all the combining data sets have same variables, but in case they have different number of variables, then in the result all the variables appear, with missing values for the smaller data set." }, { "code": null, "e": 3208, "s": 3161, "text": "The basic syntax for SET statement in SAS is −" }, { "code": null, "e": 3252, "s": 3208, "text": "SET data-set 1 data-set 2 data-set 3.....;\n" }, { "code": null, "e": 3306, "s": 3252, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 3371, "s": 3306, "text": "data-set1,data-set2 are dataset names written one after another." }, { "code": null, "e": 3436, "s": 3371, "text": "data-set1,data-set2 are dataset names written one after another." }, { "code": null, "e": 3713, "s": 3436, "text": "Consider the employee data of an organization which is available in two different data sets, one for the IT department and another for Non-It department. To get the complete details of all the employees we concatenate both the data sets using the SET statement shown as below." }, { "code": null, "e": 4052, "s": 3713, "text": "DATA ITDEPT; \n INPUT empid name $ salary ; \nDATALINES; \n1 Rick 623.3 \n3 Mike 611.5 \n6 Tusar 578.6 \n; \nRUN; \nDATA NON_ITDEPT; \n INPUT empid name $ salary ; \nDATALINES; \n2 Dan 515.2 \n4 Ryan 729.1 \n5 Gary 843.25 \n7 Pranab 632.8 \n8 Rasmi 722.5 \nRUN; \nDATA All_Dept; \n SET ITDEPT NON_ITDEPT; \nRUN; \nPROC PRINT DATA = All_Dept; \nRUN; \n" }, { "code": null, "e": 4114, "s": 4052, "text": "When the above code is executed, we get the following output." }, { "code": null, "e": 4393, "s": 4114, "text": "When we have many variations in the data sets for concatenation, the result of variables can differ but the total number of observations in the concatenated data set is always the sum of the observations in each data set. We will consider below many scenarios on this variation." }, { "code": null, "e": 4569, "s": 4393, "text": "If one of the original data set has more number of variables then another, then the data sets still get combined but in the smaller data set those variables appear as missing." }, { "code": null, "e": 4713, "s": 4569, "text": "In below example the first data set has an extra variable named DOJ. In the result the value of DOJ for second data set will appear as missing." }, { "code": null, "e": 5092, "s": 4713, "text": "DATA ITDEPT; \n INPUT empid name $ salary DOJ date9. ; \nDATALINES; \n1 Rick 623.3 02APR2001\n3 Mike 611.5 21OCT2000\n6 Tusar 578.6 01MAR2009 \n; \nRUN; \nDATA NON_ITDEPT; \n INPUT empid name $ salary ; \nDATALINES; \n2 Dan 515.2 \n4 Ryan 729.1 \n5 Gary 843.25 \n7 Pranab 632.8 \n8 Rasmi 722.5 \nRUN; \nDATA All_Dept; \n SET ITDEPT NON_ITDEPT; \nRUN; \nPROC PRINT DATA = All_Dept; \nRUN; \n" }, { "code": null, "e": 5154, "s": 5092, "text": "When the above code is executed, we get the following output." }, { "code": null, "e": 5722, "s": 5154, "text": "In this scenario the data sets have same number of variables but a variable name differs between them. In that case a normal concatenation will produce all the variables\nin the result set and giving missing results for the two variables which differ. While we may not change the variable name in the original data sets we can apply the RENAME function in the concatenated data set we create. That will produce the same result as a normal concatenation but of course with one new variable name in place of two different variable names present in the original data set." }, { "code": null, "e": 5981, "s": 5722, "text": " In the below example data set ITDEPT has the variable name ename whereas the data set NON_ITDEPT has the variable name empname. But both of these variables represent the same type(character). We apply the RENAME function in the SET statement as shown below." }, { "code": null, "e": 6384, "s": 5981, "text": "DATA ITDEPT; \n INPUT empid ename $ salary ; \nDATALINES; \n1 Rick 623.3 \n3 Mike 611.5 \n6 Tusar 578.6 \n; \nRUN; \nDATA NON_ITDEPT; \n INPUT empid empname $ salary ; \nDATALINES; \n2 Dan 515.2 \n4 Ryan 729.1 \n5 Gary 843.25 \n7 Pranab 632.8 \n8 Rasmi 722.5 \nRUN; \nDATA All_Dept; \n SET ITDEPT(RENAME =(ename = Employee) ) NON_ITDEPT(RENAME =(empname = Employee) ); \nRUN; \nPROC PRINT DATA = All_Dept; \nRUN; \n" }, { "code": null, "e": 6446, "s": 6384, "text": "When the above code is executed, we get the following output." }, { "code": null, "e": 6755, "s": 6446, "text": "If the variable lengths in the two data sets is different than the concatenated data set will have values in which some data is truncated for the variable with smaller length. It happens if the first data set has a smaller length. To solve this we apply the higher length to both the data set as shown below." }, { "code": null, "e": 6961, "s": 6755, "text": "In the below example the variable ename is of length 5 in the first data set and 7 in the second. When concatenating we apply the LENGTH statement in the concatenated data set to set the ename length to 7." }, { "code": null, "e": 7365, "s": 6961, "text": "DATA ITDEPT; \n INPUT empid 1-2 ename $ 3-7 salary 8-14 ; \nDATALINES; \n1 Rick 623.3 \n3 Mike 611.5 \n6 Tusar 578.6 \n; \nRUN;\nDATA NON_ITDEPT; \n INPUT empid 1-2 ename $ 3-9 salary 10-16 ; \nDATALINES; \n2 Dan 515.2 \n4 Ryan 729.1 \n5 Gary 843.25\n7 Pranab 632.8 \n8 Rasmi 722.5 \nRUN; \nDATA All_Dept; \n LENGTH ename $ 7 ;\n SET ITDEPT NON_ITDEPT ; \nRUN; \nPROC PRINT DATA = All_Dept; \nRUN; \n" }, { "code": null, "e": 7427, "s": 7365, "text": "When the above code is executed, we get the following output." }, { "code": null, "e": 7462, "s": 7427, "text": "\n 50 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7479, "s": 7462, "text": " Code And Create" }, { "code": null, "e": 7514, "s": 7479, "text": "\n 124 Lectures \n 30 hours \n" }, { "code": null, "e": 7527, "s": 7514, "text": " Juan Galvan" }, { "code": null, "e": 7564, "s": 7527, "text": "\n 162 Lectures \n 31.5 hours \n" }, { "code": null, "e": 7584, "s": 7564, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 7619, "s": 7584, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7632, "s": 7619, "text": " Ermin Dedic" }, { "code": null, "e": 7669, "s": 7632, "text": "\n 167 Lectures \n 45.5 hours \n" }, { "code": null, "e": 7685, "s": 7669, "text": " Muslim Helalee" }, { "code": null, "e": 7692, "s": 7685, "text": " Print" }, { "code": null, "e": 7703, "s": 7692, "text": " Add Notes" } ]
Visualizing Convolution Neural Networks using Pytorch | by Niranjan Kumar | Towards Data Science
Convolution Neural Network (CNN) is another type of neural network that can be used to enable machines to visualize things and perform tasks such as image classification, image recognition, object detection, instance segmentation etc...But the neural network models are often termed as ‘black box’ models because it is quite difficult to understand how the model is learning the complex dependencies present in the input. Also, it is difficult to analyze why a given prediction is made during inference. In this article, we will look at two different types of visualization techniques such as : Visualizing learned filter weights.Performing occlusion experiments on the image. Visualizing learned filter weights. Performing occlusion experiments on the image. These methods help us to understand what does filter learn? what kind of images cause certain neurons to fire? and how good are the hidden representations of the input image?. Citation Note: The content and the structure of this article is based on the deep learning lectures from One-Fourth Labs — PadhAI. If you are interested checkout there course. Before we go ahead and visualize the working of Convolution Neural Network, we will discuss the receptive field of filters present in the CNN’s. Consider that we have a two-layered Convolution Neural Network and we are using 3x3 filters through the network. The centered pixel marked in the yellow present in Layer 2 is actually the result of applying convolution operation on the center pixel present in Layer 1 (by using 3x3 kernels and stride = 1). Similarly, the center pixel present in Layer 3 is a result of applying convolution operation on the center pixel present in Layer 2. The receptive field of a neuron is defined as the region in the input image that can influence the neuron in a convolution layer i.e...how many pixels in the original image are influencing the neuron present in a convolution layer. It is clear that the central pixel in Layer 3 depends on the 3x3 neighborhood of the previous layer (Layer 2). The 9 successive pixels (marked in pink) present in Layer 2 including the central pixel corresponds to the 5x5 region in Layer 1. As we go deeper and deeper in the network the pixels at the deeper layers will have a high receptive field i.e... the region of interest with respect to the original image would be larger. From the above image, we can observe that the highlighted pixel present in the second convolution layer has a high receptive field with respect to the original input image. To visualize the working of CNN, we will explore two commonly used methods to understand how the neural network learns the complex relationships. Filter visualization with a pre-trained model.Occlusion analysis with a pre-trained model. Filter visualization with a pre-trained model. Occlusion analysis with a pre-trained model. All the code discussed in the article is present on my GitHub. You can open the code notebook with any setup by directly opening my Jupyter Notebook on Github with Colab which runs on Google’s Virtual Machine. Click here, if you just want to quickly open the notebook and follow along with this tutorial. Don’t forget to upload the input images folder (can be downloaded from the Github Repo) onto Google Colab before executing the code in Colab. github.com In this article, we will use a small subset of the ImageNet dataset with 1000 categories to visualize the filters of the model. The dataset can be downloaded from my GitHub repo. To visualize the data set we will implement the custom function imshow. The function imshow takes two arguments — image in tensor and the title of the image. First, we will perform the inverse normalization of the image with respect to the ImageNet mean and standard deviation values. After that, we will use matplotlib to display the image. By visualizing the filters of the trained model, we can understand how CNN learns the complex Spatial and Temporal pixel dependencies present in the image. What does a filter capture? Consider that we have 2D input of size 4x4 and we are applying a filter of 2x2 (marked in red) on the image starting from the top left corner of the image. As we slide the kernel over the image from left to right and top to bottom to perform a convolution operation we would get an output that is smaller than the size of the input. The output at each convolution operation (like h14) is equal to the dot product of the input vector and a weight vector. We know that the dot product between the two vectors is proportional to the cosine of the angle between vectors. During convolution operation, certain parts of the input image like the portion of the image containing the face of a dog might give high value when we apply a filter on top of it. In the above example, let’s discuss in what kind of scenarios our output h14 will be high?. The output h14 would be high if the cosine value between the vectors is high i.e... cosine value should be equal to 1. If the cosine angle is equal to 1 then we know the angle between the vectors is equal to 00. That means both input vector (portion of the image) X and the weight vector W are in the same direction the neuron is going to fire maximally. The neuron h14 will fire maximally when the input X (a portion of the image for convolution) is equal to the unit vector or a multiple of the unit vector in the direction of the filter vector W. In other words, we can think of a filter as an image. As we slide the filter over the input from left to right and top to bottom whenever the filter coincides with a similar portion of the input, the neuron will fire. For all other parts of the input image that doesn’t align with the filter, the output will be low. This is the reason we call the kernel or weight matrix as a filter because it filters out portions of the input image that doesn’t align with the filter. To understand what kind of patters does the filter learns, we can just plot the filter i.e... weights associated with the filter. For filter visualization, we will use Alexnet pre-trained with the ImageNet data set. #alexnet pretrained with imagenet data#import model zoo in torchvisionimport torchvision.models as modelsalexnet = models.alexnet(pretrained=True) Alexnet contains 5 convolutional layers and 3 fully connected layers. ReLU is applied after every convolution operation. Remember that in convolution operation for 3D (RGB) images, there is no movement of kernel along with the depth since both kernel and image are of the same depth. We will visualize these filters (kernel) in two ways. Visualizing each filter by combing three channels as an RGB image.Visualizing each channel in a filter independently using a heatmap. Visualizing each filter by combing three channels as an RGB image. Visualizing each channel in a filter independently using a heatmap. The main function to plot the weights is plot_weights. The function takes 4 parameters, model — Alexnet model or any trained model layer_num — Convolution Layer number to visualize the weights single_channel — Visualization mode collated — Applicable for single-channel visualization only. In the plot_weights function, we take our trained model and read the layer present at that layer number. In Alexnet (Pytorch model zoo) first convolution layer is represented with a layer index of zero. Once we extract the layer associated with that index, we will check whether the layer is the convolution layer or not. Since we can only visualize layers which are convolutional. After validating the layer index, we will extract the learned weight data present in that layer. #getting the weight tensor dataweight_tensor = model.features[layer_num].weight.data Depending on the input argument single_channel we can plot the weight data as single-channel or multi-channel images. Alexnet’s first convolution layer has 64 filters of size 11x11. We will plot these filters in two different ways and understand what kind of patterns filters learn. In the case of single_channel = False we have 64 filters of depth 3 (RGB). we will combine each filter RGB channels into one RGB image of size 11x11x3. As a result, we would get 64 RGB images as the output. #visualize weights for alexnet — first conv layerplot_weights(alexnet, 0, single_channel = False) From the images, we can interpret that the kernels seem to learn blurry edges, contours, boundaries. For example, figure 4 in the above image indicates that the filter is trying to learn the boundary. Similarly, figure 37 indicates the filter has learned about contours that could help in the problem of image classification. By settingsingle_channel = True we are interpreting each channel present in the filters as a separate image. For each filter we will get 3 separate images representing each channel since the depth of the filter is 3 for first convolution operation. In total, we will have 64*3 images as the output for visualization. From the above figure, we can see that each filter channel out of a total of 64 filters (0–63) is visualized separately. For eg. figure 0,0 indicate that the image represents the zeroth filter corresponding to the zeroth channel. Similarly, figure 0,1 indicates that the image represents the zeroth filter corresponding to the first channel and so on. Visualizing the filter channels individually gives more intuition about what different filters are trying to learn based on the input data. By looking closely at the filter visualizations, it is clear that the patterns found in some of the channels from the same filter are different. That means not all channels present in a filter are trying to learn the same information from the input image. As we move deeper into the network the filter patterns more complex, they tend to capture high-level information like the face of a dog or cat. As we go deeper and deeper into the network number of filters used for convolution increases. It is not possible for us to visualize all these filter channels individually either as a single image or each channel separately because of the large number of such filters. The second convolution layer of Alexnet (indexed as layer 3 in Pytorch sequential model structure) has 192 filters, so we would get 192*64 = 12,288 individual filter channel plots for visualization. Another way to plot these filters is to concatenate all these images into a single heatmap with a greyscale. #plotting single channel imagesplot_weights(alexnet, 0, single_channel = True, collated = True) #plotting single channel images - second convolution layerplot_weights(alexnet, 3, single_channel = True, collated = True) #plotting single channel images - third convolution layerplot_weights(alexnet, 6, single_channel = True, collated = True) As you can see there are some interpretable features like edges, angles, and boundaries in the images from the first convolution layer. But as we go deeper into the network it becomes harder to interpret the filters. Occlusion experiments are performed to determine which patches of the image contribute maximally to the output of a neural network. In a problem of image classification, how would we know that the model is actually picking up an object of interest (eg. car wheel) as opposed to the surrounding background image?. In occlusion experiments, we iterate over all the regions of the image systematically by occluding a part of the image with a grey patch set to be zero and monitoring the probability of the classifier. For example, we start the occlusion experiment by greying out the top left corner of the image and compute the probability of a particular class by passing the modified image through the network. Similarly, we will iterate over all regions of the image and look at the probability of the classifier for each experiment. The heatmap in the above figure clearly shows that the probability of true class drops significantly if we occlude our object of interest like a car wheel or the face of a dog (the dark blue region). The occlusion experiments tell us that our convolution neural network is actually learning some meaning patterns like detecting the face of a dog from the input. That means that the model is truly picking up the location of a dog instead of identifying based on the surrounding context like a sofa or a couch. To understand this concept clearly, let’s take an image from our data set and perform occlusion experiments on it. For occlusion experiments, we will use VGG-16 pre-trained on ImageNet data. #for visualization we will use vgg16 pretrained on imagenet datamodel = models.vgg16(pretrained=True) To perform the experiments, we need to write a custom function to conduct occlusion on the input image. The function occlusion takes 6 arguments — model, an input image, an input image label, and occlusion hyperparameters. The occlusion hyperparameters include the size of the occlusion patch, occlusion stride, and occlusion pixel value. In the function first, we are getting the width and height of the input image. After that, we will compute the output image width and height based on the input image dimensions and occlusion patch dimension. Then we will initialize the heatmap tensor based on the output height and width. Now we would iterate through each of the pixels present in the heatmap. In each iteration, we will compute the dimensions of the occlusion patch to be replaced in the original image. We then replace all the pixel information in the image with occlusion patch in the specified location i.e... modifying the input image by replacing a certain area with a grey patch. Once we have the modified input we will pass it through the model for inference and compute the probability of a true class. Then we are updating the heatmap at the corresponding location with the probability value. Once we obtain the heatmap, we are displaying the heatmap using a seaborn plotter and also set the maximum value of gradient to probability. From the heatmap, the darker color represents the smaller probability, meaning that the occlusion in that area is very effective. If we occlude or cover the area with a darker color in the original image then the probability of classifying the image falls significantly (less than 0.15). github.com If you want to learn more about Artificial Neural Networks using Keras & Tensorflow 2.0 (Python or R). Check out the Artificial Neural Networks by Abhishek and Pukhraj from Starttechacademy. They explain the fundamentals of deep learning in a simplistic manner. In this article, we have discussed the receptive field of a neural network. After that, we have discussed two different methods to visualize a CNN model along with Pytorch implementation. Visualizing the neural network models gives us a better intuition of how to improve the performance of the model for a wide range of applications. Recommended Reading towardsdatascience.com www.marktechpost.com Feel free to reach out to me via LinkedIn or twitter if you face any problems while implementing the code present in my GitHub repository. Until next time Peace :) NK. Disclaimer — There might be some affiliate links in this post to relevant resources. You can purchase the bundle at the lowest price possible. I will receive a small commission if you purchase the course.
[ { "code": null, "e": 676, "s": 172, "text": "Convolution Neural Network (CNN) is another type of neural network that can be used to enable machines to visualize things and perform tasks such as image classification, image recognition, object detection, instance segmentation etc...But the neural network models are often termed as ‘black box’ models because it is quite difficult to understand how the model is learning the complex dependencies present in the input. Also, it is difficult to analyze why a given prediction is made during inference." }, { "code": null, "e": 767, "s": 676, "text": "In this article, we will look at two different types of visualization techniques such as :" }, { "code": null, "e": 849, "s": 767, "text": "Visualizing learned filter weights.Performing occlusion experiments on the image." }, { "code": null, "e": 885, "s": 849, "text": "Visualizing learned filter weights." }, { "code": null, "e": 932, "s": 885, "text": "Performing occlusion experiments on the image." }, { "code": null, "e": 1108, "s": 932, "text": "These methods help us to understand what does filter learn? what kind of images cause certain neurons to fire? and how good are the hidden representations of the input image?." }, { "code": null, "e": 1284, "s": 1108, "text": "Citation Note: The content and the structure of this article is based on the deep learning lectures from One-Fourth Labs — PadhAI. If you are interested checkout there course." }, { "code": null, "e": 1429, "s": 1284, "text": "Before we go ahead and visualize the working of Convolution Neural Network, we will discuss the receptive field of filters present in the CNN’s." }, { "code": null, "e": 1869, "s": 1429, "text": "Consider that we have a two-layered Convolution Neural Network and we are using 3x3 filters through the network. The centered pixel marked in the yellow present in Layer 2 is actually the result of applying convolution operation on the center pixel present in Layer 1 (by using 3x3 kernels and stride = 1). Similarly, the center pixel present in Layer 3 is a result of applying convolution operation on the center pixel present in Layer 2." }, { "code": null, "e": 2101, "s": 1869, "text": "The receptive field of a neuron is defined as the region in the input image that can influence the neuron in a convolution layer i.e...how many pixels in the original image are influencing the neuron present in a convolution layer." }, { "code": null, "e": 2531, "s": 2101, "text": "It is clear that the central pixel in Layer 3 depends on the 3x3 neighborhood of the previous layer (Layer 2). The 9 successive pixels (marked in pink) present in Layer 2 including the central pixel corresponds to the 5x5 region in Layer 1. As we go deeper and deeper in the network the pixels at the deeper layers will have a high receptive field i.e... the region of interest with respect to the original image would be larger." }, { "code": null, "e": 2704, "s": 2531, "text": "From the above image, we can observe that the highlighted pixel present in the second convolution layer has a high receptive field with respect to the original input image." }, { "code": null, "e": 2850, "s": 2704, "text": "To visualize the working of CNN, we will explore two commonly used methods to understand how the neural network learns the complex relationships." }, { "code": null, "e": 2941, "s": 2850, "text": "Filter visualization with a pre-trained model.Occlusion analysis with a pre-trained model." }, { "code": null, "e": 2988, "s": 2941, "text": "Filter visualization with a pre-trained model." }, { "code": null, "e": 3033, "s": 2988, "text": "Occlusion analysis with a pre-trained model." }, { "code": null, "e": 3338, "s": 3033, "text": "All the code discussed in the article is present on my GitHub. You can open the code notebook with any setup by directly opening my Jupyter Notebook on Github with Colab which runs on Google’s Virtual Machine. Click here, if you just want to quickly open the notebook and follow along with this tutorial." }, { "code": null, "e": 3480, "s": 3338, "text": "Don’t forget to upload the input images folder (can be downloaded from the Github Repo) onto Google Colab before executing the code in Colab." }, { "code": null, "e": 3491, "s": 3480, "text": "github.com" }, { "code": null, "e": 3670, "s": 3491, "text": "In this article, we will use a small subset of the ImageNet dataset with 1000 categories to visualize the filters of the model. The dataset can be downloaded from my GitHub repo." }, { "code": null, "e": 3742, "s": 3670, "text": "To visualize the data set we will implement the custom function imshow." }, { "code": null, "e": 4012, "s": 3742, "text": "The function imshow takes two arguments — image in tensor and the title of the image. First, we will perform the inverse normalization of the image with respect to the ImageNet mean and standard deviation values. After that, we will use matplotlib to display the image." }, { "code": null, "e": 4168, "s": 4012, "text": "By visualizing the filters of the trained model, we can understand how CNN learns the complex Spatial and Temporal pixel dependencies present in the image." }, { "code": null, "e": 4196, "s": 4168, "text": "What does a filter capture?" }, { "code": null, "e": 4529, "s": 4196, "text": "Consider that we have 2D input of size 4x4 and we are applying a filter of 2x2 (marked in red) on the image starting from the top left corner of the image. As we slide the kernel over the image from left to right and top to bottom to perform a convolution operation we would get an output that is smaller than the size of the input." }, { "code": null, "e": 4763, "s": 4529, "text": "The output at each convolution operation (like h14) is equal to the dot product of the input vector and a weight vector. We know that the dot product between the two vectors is proportional to the cosine of the angle between vectors." }, { "code": null, "e": 5036, "s": 4763, "text": "During convolution operation, certain parts of the input image like the portion of the image containing the face of a dog might give high value when we apply a filter on top of it. In the above example, let’s discuss in what kind of scenarios our output h14 will be high?." }, { "code": null, "e": 5391, "s": 5036, "text": "The output h14 would be high if the cosine value between the vectors is high i.e... cosine value should be equal to 1. If the cosine angle is equal to 1 then we know the angle between the vectors is equal to 00. That means both input vector (portion of the image) X and the weight vector W are in the same direction the neuron is going to fire maximally." }, { "code": null, "e": 5586, "s": 5391, "text": "The neuron h14 will fire maximally when the input X (a portion of the image for convolution) is equal to the unit vector or a multiple of the unit vector in the direction of the filter vector W." }, { "code": null, "e": 6057, "s": 5586, "text": "In other words, we can think of a filter as an image. As we slide the filter over the input from left to right and top to bottom whenever the filter coincides with a similar portion of the input, the neuron will fire. For all other parts of the input image that doesn’t align with the filter, the output will be low. This is the reason we call the kernel or weight matrix as a filter because it filters out portions of the input image that doesn’t align with the filter." }, { "code": null, "e": 6273, "s": 6057, "text": "To understand what kind of patters does the filter learns, we can just plot the filter i.e... weights associated with the filter. For filter visualization, we will use Alexnet pre-trained with the ImageNet data set." }, { "code": null, "e": 6420, "s": 6273, "text": "#alexnet pretrained with imagenet data#import model zoo in torchvisionimport torchvision.models as modelsalexnet = models.alexnet(pretrained=True)" }, { "code": null, "e": 6758, "s": 6420, "text": "Alexnet contains 5 convolutional layers and 3 fully connected layers. ReLU is applied after every convolution operation. Remember that in convolution operation for 3D (RGB) images, there is no movement of kernel along with the depth since both kernel and image are of the same depth. We will visualize these filters (kernel) in two ways." }, { "code": null, "e": 6892, "s": 6758, "text": "Visualizing each filter by combing three channels as an RGB image.Visualizing each channel in a filter independently using a heatmap." }, { "code": null, "e": 6959, "s": 6892, "text": "Visualizing each filter by combing three channels as an RGB image." }, { "code": null, "e": 7027, "s": 6959, "text": "Visualizing each channel in a filter independently using a heatmap." }, { "code": null, "e": 7115, "s": 7027, "text": "The main function to plot the weights is plot_weights. The function takes 4 parameters," }, { "code": null, "e": 7158, "s": 7115, "text": "model — Alexnet model or any trained model" }, { "code": null, "e": 7220, "s": 7158, "text": "layer_num — Convolution Layer number to visualize the weights" }, { "code": null, "e": 7256, "s": 7220, "text": "single_channel — Visualization mode" }, { "code": null, "e": 7317, "s": 7256, "text": "collated — Applicable for single-channel visualization only." }, { "code": null, "e": 7796, "s": 7317, "text": "In the plot_weights function, we take our trained model and read the layer present at that layer number. In Alexnet (Pytorch model zoo) first convolution layer is represented with a layer index of zero. Once we extract the layer associated with that index, we will check whether the layer is the convolution layer or not. Since we can only visualize layers which are convolutional. After validating the layer index, we will extract the learned weight data present in that layer." }, { "code": null, "e": 7881, "s": 7796, "text": "#getting the weight tensor dataweight_tensor = model.features[layer_num].weight.data" }, { "code": null, "e": 8164, "s": 7881, "text": "Depending on the input argument single_channel we can plot the weight data as single-channel or multi-channel images. Alexnet’s first convolution layer has 64 filters of size 11x11. We will plot these filters in two different ways and understand what kind of patterns filters learn." }, { "code": null, "e": 8371, "s": 8164, "text": "In the case of single_channel = False we have 64 filters of depth 3 (RGB). we will combine each filter RGB channels into one RGB image of size 11x11x3. As a result, we would get 64 RGB images as the output." }, { "code": null, "e": 8469, "s": 8371, "text": "#visualize weights for alexnet — first conv layerplot_weights(alexnet, 0, single_channel = False)" }, { "code": null, "e": 8795, "s": 8469, "text": "From the images, we can interpret that the kernels seem to learn blurry edges, contours, boundaries. For example, figure 4 in the above image indicates that the filter is trying to learn the boundary. Similarly, figure 37 indicates the filter has learned about contours that could help in the problem of image classification." }, { "code": null, "e": 9112, "s": 8795, "text": "By settingsingle_channel = True we are interpreting each channel present in the filters as a separate image. For each filter we will get 3 separate images representing each channel since the depth of the filter is 3 for first convolution operation. In total, we will have 64*3 images as the output for visualization." }, { "code": null, "e": 9464, "s": 9112, "text": "From the above figure, we can see that each filter channel out of a total of 64 filters (0–63) is visualized separately. For eg. figure 0,0 indicate that the image represents the zeroth filter corresponding to the zeroth channel. Similarly, figure 0,1 indicates that the image represents the zeroth filter corresponding to the first channel and so on." }, { "code": null, "e": 10004, "s": 9464, "text": "Visualizing the filter channels individually gives more intuition about what different filters are trying to learn based on the input data. By looking closely at the filter visualizations, it is clear that the patterns found in some of the channels from the same filter are different. That means not all channels present in a filter are trying to learn the same information from the input image. As we move deeper into the network the filter patterns more complex, they tend to capture high-level information like the face of a dog or cat." }, { "code": null, "e": 10581, "s": 10004, "text": "As we go deeper and deeper into the network number of filters used for convolution increases. It is not possible for us to visualize all these filter channels individually either as a single image or each channel separately because of the large number of such filters. The second convolution layer of Alexnet (indexed as layer 3 in Pytorch sequential model structure) has 192 filters, so we would get 192*64 = 12,288 individual filter channel plots for visualization. Another way to plot these filters is to concatenate all these images into a single heatmap with a greyscale." }, { "code": null, "e": 10677, "s": 10581, "text": "#plotting single channel imagesplot_weights(alexnet, 0, single_channel = True, collated = True)" }, { "code": null, "e": 10800, "s": 10677, "text": "#plotting single channel images - second convolution layerplot_weights(alexnet, 3, single_channel = True, collated = True)" }, { "code": null, "e": 10922, "s": 10800, "text": "#plotting single channel images - third convolution layerplot_weights(alexnet, 6, single_channel = True, collated = True)" }, { "code": null, "e": 11139, "s": 10922, "text": "As you can see there are some interpretable features like edges, angles, and boundaries in the images from the first convolution layer. But as we go deeper into the network it becomes harder to interpret the filters." }, { "code": null, "e": 11271, "s": 11139, "text": "Occlusion experiments are performed to determine which patches of the image contribute maximally to the output of a neural network." }, { "code": null, "e": 11452, "s": 11271, "text": "In a problem of image classification, how would we know that the model is actually picking up an object of interest (eg. car wheel) as opposed to the surrounding background image?." }, { "code": null, "e": 11654, "s": 11452, "text": "In occlusion experiments, we iterate over all the regions of the image systematically by occluding a part of the image with a grey patch set to be zero and monitoring the probability of the classifier." }, { "code": null, "e": 12174, "s": 11654, "text": "For example, we start the occlusion experiment by greying out the top left corner of the image and compute the probability of a particular class by passing the modified image through the network. Similarly, we will iterate over all regions of the image and look at the probability of the classifier for each experiment. The heatmap in the above figure clearly shows that the probability of true class drops significantly if we occlude our object of interest like a car wheel or the face of a dog (the dark blue region)." }, { "code": null, "e": 12484, "s": 12174, "text": "The occlusion experiments tell us that our convolution neural network is actually learning some meaning patterns like detecting the face of a dog from the input. That means that the model is truly picking up the location of a dog instead of identifying based on the surrounding context like a sofa or a couch." }, { "code": null, "e": 12599, "s": 12484, "text": "To understand this concept clearly, let’s take an image from our data set and perform occlusion experiments on it." }, { "code": null, "e": 12675, "s": 12599, "text": "For occlusion experiments, we will use VGG-16 pre-trained on ImageNet data." }, { "code": null, "e": 12777, "s": 12675, "text": "#for visualization we will use vgg16 pretrained on imagenet datamodel = models.vgg16(pretrained=True)" }, { "code": null, "e": 13116, "s": 12777, "text": "To perform the experiments, we need to write a custom function to conduct occlusion on the input image. The function occlusion takes 6 arguments — model, an input image, an input image label, and occlusion hyperparameters. The occlusion hyperparameters include the size of the occlusion patch, occlusion stride, and occlusion pixel value." }, { "code": null, "e": 13405, "s": 13116, "text": "In the function first, we are getting the width and height of the input image. After that, we will compute the output image width and height based on the input image dimensions and occlusion patch dimension. Then we will initialize the heatmap tensor based on the output height and width." }, { "code": null, "e": 13986, "s": 13405, "text": "Now we would iterate through each of the pixels present in the heatmap. In each iteration, we will compute the dimensions of the occlusion patch to be replaced in the original image. We then replace all the pixel information in the image with occlusion patch in the specified location i.e... modifying the input image by replacing a certain area with a grey patch. Once we have the modified input we will pass it through the model for inference and compute the probability of a true class. Then we are updating the heatmap at the corresponding location with the probability value." }, { "code": null, "e": 14127, "s": 13986, "text": "Once we obtain the heatmap, we are displaying the heatmap using a seaborn plotter and also set the maximum value of gradient to probability." }, { "code": null, "e": 14415, "s": 14127, "text": "From the heatmap, the darker color represents the smaller probability, meaning that the occlusion in that area is very effective. If we occlude or cover the area with a darker color in the original image then the probability of classifying the image falls significantly (less than 0.15)." }, { "code": null, "e": 14426, "s": 14415, "text": "github.com" }, { "code": null, "e": 14688, "s": 14426, "text": "If you want to learn more about Artificial Neural Networks using Keras & Tensorflow 2.0 (Python or R). Check out the Artificial Neural Networks by Abhishek and Pukhraj from Starttechacademy. They explain the fundamentals of deep learning in a simplistic manner." }, { "code": null, "e": 15023, "s": 14688, "text": "In this article, we have discussed the receptive field of a neural network. After that, we have discussed two different methods to visualize a CNN model along with Pytorch implementation. Visualizing the neural network models gives us a better intuition of how to improve the performance of the model for a wide range of applications." }, { "code": null, "e": 15043, "s": 15023, "text": "Recommended Reading" }, { "code": null, "e": 15066, "s": 15043, "text": "towardsdatascience.com" }, { "code": null, "e": 15087, "s": 15066, "text": "www.marktechpost.com" }, { "code": null, "e": 15226, "s": 15087, "text": "Feel free to reach out to me via LinkedIn or twitter if you face any problems while implementing the code present in my GitHub repository." }, { "code": null, "e": 15251, "s": 15226, "text": "Until next time Peace :)" }, { "code": null, "e": 15255, "s": 15251, "text": "NK." } ]
Perl int Function
This function returns the integer element of EXPR, or $_ if omitted. The int function does not do rounding. If you need to round a value up to an integer, you should use sprintf. Following is the simple syntax for this function − int EXPR int This function returns the integer part of EXPR. Following is the example code showing its basic usage − #!/usr/bin/perl $int_val = int( 6.23930 ); print"Integer value is $int_val\n"; $int_val = int( -6.23930 ); print"Integer value is $int_val\n"; $int_val = int( 10 / 3 ); print"Integer value is $int_val\n"; When above code is executed, it produces the following result − Integer value is 6 Integer value is -6 Integer value is 3 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2399, "s": 2220, "text": "This function returns the integer element of EXPR, or $_ if omitted. The int function does not do rounding. If you need to round a value up to an integer, you should use sprintf." }, { "code": null, "e": 2450, "s": 2399, "text": "Following is the simple syntax for this function −" }, { "code": null, "e": 2465, "s": 2450, "text": "int EXPR\n\nint\n" }, { "code": null, "e": 2513, "s": 2465, "text": "This function returns the integer part of EXPR." }, { "code": null, "e": 2569, "s": 2513, "text": "Following is the example code showing its basic usage −" }, { "code": null, "e": 2777, "s": 2569, "text": "#!/usr/bin/perl\n\n$int_val = int( 6.23930 );\nprint\"Integer value is $int_val\\n\";\n\n$int_val = int( -6.23930 );\nprint\"Integer value is $int_val\\n\";\n\n$int_val = int( 10 / 3 );\nprint\"Integer value is $int_val\\n\";" }, { "code": null, "e": 2841, "s": 2777, "text": "When above code is executed, it produces the following result −" }, { "code": null, "e": 2900, "s": 2841, "text": "Integer value is 6\nInteger value is -6\nInteger value is 3\n" }, { "code": null, "e": 2935, "s": 2900, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 2949, "s": 2935, "text": " Devi Killada" }, { "code": null, "e": 2984, "s": 2949, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3004, "s": 2984, "text": " Harshit Srivastava" }, { "code": null, "e": 3037, "s": 3004, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 3053, "s": 3037, "text": " TELCOMA Global" }, { "code": null, "e": 3086, "s": 3053, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3103, "s": 3086, "text": " Mohammad Nauman" }, { "code": null, "e": 3136, "s": 3103, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 3159, "s": 3136, "text": " Stone River ELearning" }, { "code": null, "e": 3194, "s": 3159, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3217, "s": 3194, "text": " Stone River ELearning" }, { "code": null, "e": 3224, "s": 3217, "text": " Print" }, { "code": null, "e": 3235, "s": 3224, "text": " Add Notes" } ]
Angular PrimeNG TieredMenu Component - GeeksforGeeks
08 Sep, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the TieredMenu component in Angular PrimeNG. We will also learn about the properties, methods, styling along with their syntaxes that will be used in the code. TieredMenu component: It allows a user to make the menu in the form of tiers. Properties: model: It is an array of menu items. It is of array data type & the default value is null. popup: It defines if the menu would be displayed as a popup. It is of the boolean data type & the default value is false. appendTo: It specifies the target element to attach the overlay & the valid values are “body” or a local ng-template variable of another element. It is of array data type & the default value is null. style: It sets an inline style of the component. It is of string data type & the default value is null. styleClass: It sets the style class of the component. It accepts the string data type & the default value is null. baseZIndex: It is a base zIndex value to use in layering. It accepts the number as input data type & the default value is 0. autoZIndex: It specifies whether to automatically manage the layering. It is of the boolean data type & the default value is true. autoDisplay: It specifies whether to show a root submenu on mouseover. It is of the boolean data type & the default value is false. showTransitionOptions: It shows transition options to show the animation. It accepts the string data type & the default value is .12s cubic-bezier(0, 0, 0.2, 1). hideTransitionOptions: It shows transition options to hide the animation. It accepts the string data type & the default value is .1s linear. Methods: toggle: It is used to toggles the visibility of the popup menu. show: It is used to displays the popup menu. hide: It is used to hides the popup menu. Styling: p-tieredmenu: It is a container element. p-menu-list: It is a list element. p-menuitem: It is a menuitem element. p-menuitem-text: It is a label of a menu item. p-menuitem-icon: It is an icon of a menu item. p-submenu-icon: It is the arrow icon of a submenu. Creating Angular application & module installation: Step 1: Create an Angular application using the following command: ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: After complete installation, it will look like the following: Example 1: This is the basic example that shows how to use the TieredMenu component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG TieredMenu Component</h5><p-tieredMenu [model]="gfg"></p-tieredMenu> app.component.ts import { Component } from "@angular/core";import { MenuItem } from "primeng/api"; @Component({ selector: "my-app", templateUrl: "./app.component.html",})export class AppComponent { gfg: MenuItem[]; ngOnInit() { this.gfg = [ { label: "JavaScript", items: [ { label: "JavaScript1", items: [ { label: "JavaScript1.1", }, { label: "JavaScript1.2", }, ], }, { label: "JavaScript2", }, { label: "JavaScript3", }, ], }, { label: "HTML", items: [ { label: "HTML 1", }, { label: "HTML 2", }, ], }, { label: "Angular", items: [ { label: "Angular 1", }, { label: "Angular 2", }, ], }, ]; }} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { TieredMenuModule } from "primeng/tieredmenu"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, TieredMenuModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {} Output: Example 2: In this example, we will make the tieredmenu component using popup. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG TieredMenu Component</h5><button #btn type="button" pButton label="Click Here" (click)="menu.toggle($event)"></button><p-tieredMenu #menu [model]="gfg" [popup]="true"></p-tieredMenu> app.component.ts import { Component } from '@angular/core';import { MenuItem } from 'primeng/api'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: MenuItem[]; ngOnInit() { this.gfg = [ { label: 'JavaScript', items: [ { label: 'JavaScript1', items: [ { label: 'JavaScript1.1' }, { label: 'JavaScript1.2' } ] }, { label: 'JavaScript2' }, { label: 'JavaScript3' } ] }, { label: 'HTML', items: [ { label: 'HTML 1' }, { label: 'HTML 2' } ] }, { label: 'Angular', items: [ { label: 'Angular 1' }, { label: 'Angular 2' } ] } ]; }} app.module.ts import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { TieredMenuModule } from 'primeng/tieredmenu';import { ButtonModule } from 'primeng/button'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, TieredMenuModule, ButtonModule ], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {} Output: Reference: https://primefaces.org/primeng/showcase/#/tieredmenu Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Angular PrimeNG Dropdown Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular 10 (blur) Event How to setup 404 page in angular routing ? How to create module with Routing in Angular 9 ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24718, "s": 24690, "text": "\n08 Sep, 2021" }, { "code": null, "e": 25119, "s": 24718, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the TieredMenu component in Angular PrimeNG. We will also learn about the properties, methods, styling along with their syntaxes that will be used in the code." }, { "code": null, "e": 25197, "s": 25119, "text": "TieredMenu component: It allows a user to make the menu in the form of tiers." }, { "code": null, "e": 25209, "s": 25197, "text": "Properties:" }, { "code": null, "e": 25300, "s": 25209, "text": "model: It is an array of menu items. It is of array data type & the default value is null." }, { "code": null, "e": 25422, "s": 25300, "text": "popup: It defines if the menu would be displayed as a popup. It is of the boolean data type & the default value is false." }, { "code": null, "e": 25622, "s": 25422, "text": "appendTo: It specifies the target element to attach the overlay & the valid values are “body” or a local ng-template variable of another element. It is of array data type & the default value is null." }, { "code": null, "e": 25726, "s": 25622, "text": "style: It sets an inline style of the component. It is of string data type & the default value is null." }, { "code": null, "e": 25841, "s": 25726, "text": "styleClass: It sets the style class of the component. It accepts the string data type & the default value is null." }, { "code": null, "e": 25966, "s": 25841, "text": "baseZIndex: It is a base zIndex value to use in layering. It accepts the number as input data type & the default value is 0." }, { "code": null, "e": 26097, "s": 25966, "text": "autoZIndex: It specifies whether to automatically manage the layering. It is of the boolean data type & the default value is true." }, { "code": null, "e": 26229, "s": 26097, "text": "autoDisplay: It specifies whether to show a root submenu on mouseover. It is of the boolean data type & the default value is false." }, { "code": null, "e": 26391, "s": 26229, "text": "showTransitionOptions: It shows transition options to show the animation. It accepts the string data type & the default value is .12s cubic-bezier(0, 0, 0.2, 1)." }, { "code": null, "e": 26532, "s": 26391, "text": "hideTransitionOptions: It shows transition options to hide the animation. It accepts the string data type & the default value is .1s linear." }, { "code": null, "e": 26541, "s": 26532, "text": "Methods:" }, { "code": null, "e": 26605, "s": 26541, "text": "toggle: It is used to toggles the visibility of the popup menu." }, { "code": null, "e": 26650, "s": 26605, "text": "show: It is used to displays the popup menu." }, { "code": null, "e": 26692, "s": 26650, "text": "hide: It is used to hides the popup menu." }, { "code": null, "e": 26703, "s": 26694, "text": "Styling:" }, { "code": null, "e": 26744, "s": 26703, "text": "p-tieredmenu: It is a container element." }, { "code": null, "e": 26779, "s": 26744, "text": "p-menu-list: It is a list element." }, { "code": null, "e": 26817, "s": 26779, "text": "p-menuitem: It is a menuitem element." }, { "code": null, "e": 26864, "s": 26817, "text": "p-menuitem-text: It is a label of a menu item." }, { "code": null, "e": 26911, "s": 26864, "text": "p-menuitem-icon: It is an icon of a menu item." }, { "code": null, "e": 26962, "s": 26911, "text": "p-submenu-icon: It is the arrow icon of a submenu." }, { "code": null, "e": 27014, "s": 26962, "text": "Creating Angular application & module installation:" }, { "code": null, "e": 27081, "s": 27014, "text": "Step 1: Create an Angular application using the following command:" }, { "code": null, "e": 27096, "s": 27081, "text": "ng new appname" }, { "code": null, "e": 27193, "s": 27096, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 27204, "s": 27193, "text": "cd appname" }, { "code": null, "e": 27253, "s": 27204, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 27310, "s": 27253, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 27391, "s": 27310, "text": "Project Structure: After complete installation, it will look like the following:" }, { "code": null, "e": 27478, "s": 27393, "text": "Example 1: This is the basic example that shows how to use the TieredMenu component." }, { "code": null, "e": 27497, "s": 27478, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG TieredMenu Component</h5><p-tieredMenu [model]=\"gfg\"></p-tieredMenu>", "e": 27600, "s": 27497, "text": null }, { "code": null, "e": 27617, "s": 27600, "text": "app.component.ts" }, { "code": "import { Component } from \"@angular/core\";import { MenuItem } from \"primeng/api\"; @Component({ selector: \"my-app\", templateUrl: \"./app.component.html\",})export class AppComponent { gfg: MenuItem[]; ngOnInit() { this.gfg = [ { label: \"JavaScript\", items: [ { label: \"JavaScript1\", items: [ { label: \"JavaScript1.1\", }, { label: \"JavaScript1.2\", }, ], }, { label: \"JavaScript2\", }, { label: \"JavaScript3\", }, ], }, { label: \"HTML\", items: [ { label: \"HTML 1\", }, { label: \"HTML 2\", }, ], }, { label: \"Angular\", items: [ { label: \"Angular 1\", }, { label: \"Angular 2\", }, ], }, ]; }}", "e": 28613, "s": 27617, "text": null }, { "code": null, "e": 28627, "s": 28613, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { TieredMenuModule } from \"primeng/tieredmenu\"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, TieredMenuModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}", "e": 29114, "s": 28627, "text": null }, { "code": null, "e": 29122, "s": 29114, "text": "Output:" }, { "code": null, "e": 29201, "s": 29122, "text": "Example 2: In this example, we will make the tieredmenu component using popup." }, { "code": null, "e": 29220, "s": 29201, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG TieredMenu Component</h5><button #btn type=\"button\" pButton label=\"Click Here\" (click)=\"menu.toggle($event)\"></button><p-tieredMenu #menu [model]=\"gfg\" [popup]=\"true\"></p-tieredMenu>", "e": 29444, "s": 29220, "text": null }, { "code": null, "e": 29461, "s": 29444, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core';import { MenuItem } from 'primeng/api'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: MenuItem[]; ngOnInit() { this.gfg = [ { label: 'JavaScript', items: [ { label: 'JavaScript1', items: [ { label: 'JavaScript1.1' }, { label: 'JavaScript1.2' } ] }, { label: 'JavaScript2' }, { label: 'JavaScript3' } ] }, { label: 'HTML', items: [ { label: 'HTML 1' }, { label: 'HTML 2' } ] }, { label: 'Angular', items: [ { label: 'Angular 1' }, { label: 'Angular 2' } ] } ]; }}", "e": 30439, "s": 29461, "text": null }, { "code": null, "e": 30453, "s": 30439, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { TieredMenuModule } from 'primeng/tieredmenu';import { ButtonModule } from 'primeng/button'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, TieredMenuModule, ButtonModule ], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}", "e": 30978, "s": 30453, "text": null }, { "code": null, "e": 30986, "s": 30978, "text": "Output:" }, { "code": null, "e": 31050, "s": 30986, "text": "Reference: https://primefaces.org/primeng/showcase/#/tieredmenu" }, { "code": null, "e": 31066, "s": 31050, "text": "Angular-PrimeNG" }, { "code": null, "e": 31076, "s": 31066, "text": "AngularJS" }, { "code": null, "e": 31093, "s": 31076, "text": "Web Technologies" }, { "code": null, "e": 31191, "s": 31093, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31200, "s": 31191, "text": "Comments" }, { "code": null, "e": 31213, "s": 31200, "text": "Old Comments" }, { "code": null, "e": 31248, "s": 31213, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 31301, "s": 31248, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 31325, "s": 31301, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 31368, "s": 31325, "text": "How to setup 404 page in angular routing ?" }, { "code": null, "e": 31417, "s": 31368, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 31473, "s": 31417, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 31506, "s": 31473, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31568, "s": 31506, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31611, "s": 31568, "text": "How to fetch data from an API in ReactJS ?" } ]
Menu Driven Program to implement all the operations of Doubly Circular Linked List - GeeksforGeeks
09 Dec, 2021 Circular Doubly Linked List has properties of both Doubly Linked List and Circular Linked List in which two consecutive elements are linked or connected by previous and next pointer and the last node points to the first node by next pointer and also the first node points to the last node by the previous pointer. The program implements all the functions and operations that are possible on a doubly circular list following functions in a menu-driven program. Approach: Each function (except display) takes the address of the pointer to the head i.e. the first element of the list. This allows us to change the address of the head pointer. The idea is the use only one pointer, which is of type node, to perform all the operations. node is the class that contains three data members. One member is of type int which stores data of the node and two members of type node*, one store’s address of next element and other stores address of the previous element. This way it is possible to traverse the list in either direction. It is possible to modify, insert, delete search for the element using a single pointer. Functions Covered: void insert_front (node **head): This function allows the user to enter a new node at the front of the list. void insert_end (node **head): This function allows the user to enter a new node at the end of the list. void inser_after (node **head): This function allows the user to enter a new node after a node is entered by the user. void insert_before (node **head): This function allows the user to enter a new node before a node is entered by the user. void delete_front (node **head): This function allows the user to delete a node from the front of the list. void delete_end(node**head): This function allows the user to delete a node from the end of the list. void delete_mid( node **head): This function allows deletion of a node entered by the user. void search (node *head): Function to search for the location of the array entered by the user. void reverse (node **head): Function to reverse the list and make the last element of the list head. void display (node *head): Function to print the list. Below is the C++ program to implement the above approach: C++ // C++ program for the above approach #include <iostream> using namespace std; class node { public: node* next; node* prev; int data; }; // Function to add the node at the front // of the doubly circular LL void insert_front(node** head) { // Function to insert node // in front of list cout << "\nEnter Data for New Node:"; // Create a new node named // new_node node* new_node = new node; // Enter data for new_node cin >> new_node->data; if (*head == NULL) { // If there is no node in // the list, create a node // pointing to itself and // make it head new_node->next = new_node; new_node->prev = new_node; *head = new_node; } else { // If there already exists // elements in the list // Next of new_node will point // to head new_node->next = *head; // prev of new_node will point // to prev of head new_node->prev = (*head)->prev; // next of prev of head i.e. next // of last node will point to // new_node ((*head)->prev)->next = new_node; // prev of head will point // to new_node (*head)->prev = new_node; // new_node will become the // head of list *head = new_node; } } // Function to add the node at the end // of the doubly circular LL void insert_end(node** head) { // Function to insert node at // last of list cout << "\nEnter Data for New Node:"; // Create new node node* new_node = new node; cin >> new_node->data; if (*head == NULL) { // If there is no element in the // list create a node pointing // to itself and make it head new_node->next = new_node; new_node->prev = new_node; *head = new_node; } else { // If there are elements in the // list then create a temp node // pointing to current element node* curr = *head; while (curr->next != *head) // Traverse till the end of // list curr = curr->next; // next of new_node will point to // next of current node new_node->next = curr->next; // prev of new_node will // point to current element new_node->prev = curr; // prev of next of current node // i.e. prev of head will point to // new_node (curr->next)->prev = new_node; // next of current node will // point to new_node curr->next = new_node; } } // Function to add the node after the // given node of doubly circular LL void insert_after(node** head) { // Function to enter a node after // the element entered by user // Create new node node* new_node = new node; cout << "\nEnter Data for New Node:"; cin >> new_node->data; if (*head == NULL) { // If there is no element in // the list then create a node // pointing to itself and make // it head cout << "\nThere is No element in the List"; cout << "\nCreating a new node"; new_node->prev = new_node; new_node->next = new_node; *head = new_node; } else { int num; // Ask user after which node new // node is to be inserted cout << "Enter After Element:"; cin >> num; // temp node to traverse list // and point to current element node* curr = *head; while (curr->data != num) { curr = curr->next; // If current becomes equal // to head i.e. if entire list // has been traversed then // element entered is not found // in list if (curr == *head) { cout << "\nEntered Element" << " Not Found in " "List\n"; return; } } // Control will reach here only if // element is found in list // next of new node will point to // next of current node new_node->next = curr->next; // prev of new node will // point to current node new_node->prev = curr; // prev of next of current node // will point to new node (curr->next)->prev = new_node; // next of current node will // point to new node curr->next = new_node; } } // Function to add the node before the // given node of doubly circular LL void insert_before(node** head) { // Function to enter node before // a node entered by the user node* new_node = new node; if (*head == NULL) { // If there is no element in the // list create new node and make // it head cout << "List is Empty!! Creating New node..."; cout << "\nEnter Data for New Node:"; cin >> new_node->data; new_node->prev = new_node; new_node->next = new_node; *head = new_node; } else { int num; // Ask user before which node // new node is to be inserted cout << "\nEnter Before Element:"; cin >> num; // If user wants to enter new node // before the first node i.e. // before head then call insert_front // function if ((*head)->data == num) insert_front(head); else { // temp node current for traversing // the list and point to current // element we assign curr to // *head->next this time because // data of head has already been // checked in previous condition node* curr = (*head)->next; while (curr->data != num) { if (curr == *head) { // If current equal head then // entire list has been traversed // and the entered element is not // found in list cout << "\nEntered Element Not Found " "in List!!\n"; return; } curr = curr->next; } cout << "\nEnter Data For New Node:"; cin >> new_node->data; // Control will reaach here only // if entered node exists in list // and current has found the element // next of new node will point to // current node new_node->next = curr; // prev of new node will point // to prev of current node new_node->prev = curr->prev; // next of prev of current node // will point to new node (curr->prev)->next = new_node; // prev of current will // point to new node curr->prev = new_node; } } } // Function to delete the front node // of doubly circular LL void delete_front(node** head) { // Function to delete a node // from front of list if (*head == NULL) { // If list is already empty // print a message cout << "\nList in empty!!\n"; } else if ((*head)->next == *head) { // If head is the only element // in the list delete head and // assign it to NULL delete *head; *head = NULL; } else { node* curr = new node; // temp node to save address // of node next to head curr = (*head)->next; // prev of temp will // point to prev of head curr->prev = (*head)->prev; // next of prev of head i.e. // next of last node will point // to temp ((*head)->prev)->next = curr; // delete head delete *head; // assign head to temp *head = curr; } } // Function to delete the end node // of doubly circular LL void delete_end(node** head) { // Function to delete a node // from end of list if (*head == NULL) { // If list is already empty // print a message cout << "\nList is Empty!!\n"; } else if ((*head)->next == *head) { // If head is the only element // in the list delete head and // assign it to NULL delete *head; *head = NULL; } else { // Create temporary node curr // to traverse list and point // to current element node* curr = new node; // Assign curr to head curr = *head; while (curr->next != (*head)) { // Traverse till end of list curr = curr->next; } // next of prev of curr will point // to next of curr (curr->prev)->next = curr->next; // prev of next of curr will point // to prev of curr (curr->next)->prev = curr->prev; // delete curr delete curr; } } // Function to delete the middle node // of doubly circular LL void delete_mid(node** head) { // Function to delete a node // entered by user if (*head == NULL) { // If list is already empty // print a message cout << "\nList is Empty!!!"; } else { cout << "\nEnter Element to be deleted:"; int num; cin >> num; if ((*head)->data == num) { // If user wants to delete // the head node i.e front // node call delete_front(head) // function delete_front(head); } else { // temp node to traverse list // and point to current node node* curr = (*head)->next; while ((curr->data) != num) { if (curr == (*head)) { // If curr equals head then // entire list has been // traversed element to be // deleted is not found cout << "\nEntered Element Not Found " "in List!!\n"; return; } curr = curr->next; } // control will reach here only // if element is found in the list // next of prev of curr will // point to next of curr (curr->prev)->next = curr->next; // prev of next of curr will // point to prev of curr (curr->next)->prev = curr->prev; delete curr; } } } // Function to search any node in the // doubly circular LL void search(node* head) { if (head == NULL) { // If head is null list is empty cout << "List is empty!!"; return; } int item; cout << "Enter item to be searched:"; // Ask user to enter item to // be searched cin >> item; // curr pointer is used to // traverse list it will point // to the current element node* curr = head; int index = 0, count = 0; do { // If data in curr is equal to item // to be searched print its position // index+1 if (curr->data == item) { cout << "\nItem found at position:" << index + 1; // increment count count++; } // Index will increment by 1 in // each iteration index++; curr = curr->next; } while (curr != head); // If count is still 0 that means // item is not found if (count == 0) cout << "Item searched not found in list"; } // Function to reverse the doubly // circular Linked List void reverse(node** head) { if (*head == NULL) { // If head is null list is empty cout << "List is Empty !!"; return; } // curr is used to traverse list node* curr = *head; while (curr->next != *head) { // use a temp node to store // address of next of curr node* temp = curr->next; // make next of curr to point // its previous curr->next = curr->prev; // make previous of curr to // point its next curr->prev = temp; // After each iteration move // to element which was earlier // next of curr curr = temp; } // Update the last node separately node* temp = curr->next; curr->next = curr->prev; curr->prev = temp; // only change is this node will now // become head *head = curr; } // Function to display the doubly // circular linked list void display(node* head) { node* curr = head; if (curr == NULL) cout << "\n List is Empty!!"; else { do { cout << curr->data << "->"; curr = curr->next; } while (curr != head); } } void display_menu() { cout << "==============================================" "======================"; cout << "\nMenu:\n"; cout << "1. Insert At Front\n"; cout << "2. Insert At End\n"; cout << "3. Insert After Element\n"; cout << "4. Insert Before Element\n"; cout << "5. Delete From Front\n"; cout << "6. Delete From End\n"; cout << "7. Delete A Node\n"; cout << "8. Search for a element\n"; cout << "9. Reverse a the list\n"; cout << "==============================================" "======================"; } // Driver Code int main() { int choice; char repeat_menu = 'y'; // Declaration of head node node* head = NULL; display_menu(); do { cout << "\nEnter Your Choice:"; cin >> choice; switch (choice) { case 1: { insert_front(&head); display(head); break; } case 2: { insert_end(&head); display(head); break; } case 3: { insert_after(&head); display(head); break; } case 4: { insert_before(&head); display(head); break; } case 5: { delete_front(&head); display(head); break; } case 6: { delete_end(&head); display(head); break; } case 7: { delete_mid(&head); display(head); break; } case 8: { search(head); break; } case 9: { reverse(&head); display(head); break; } default: { cout << "\nWrong Choice!!!"; display_menu(); break; } } cout << "\nEnter More(Y/N)"; cin >> repeat_menu; } while (repeat_menu == 'y' || repeat_menu == 'Y'); return 0; } Output: 1. void insert_front (node **head): 2. void insert_end (node **head): 3. void insert_after (node **head): 4. void insert_before (node **head): 5. void delete_front (node **head): 6. void delete_end (node **head): 7. void delete_mid (node **head): 8. void search (node *head): 9. void reverse (node **head): simmytarika5 surindertarika1234 sweetyty circular linked list doubly linked list Linked Lists Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Circular Singly Linked List | Insertion Delete a node in a Doubly Linked List Swap nodes in a linked list without swapping data Given a linked list which is sorted, how will you insert in sorted way Circular Linked List | Set 2 (Traversal) Insert a node at a specific position in a linked list Program to implement Singly Linked List in C++ using class Priority Queue using Linked List Insertion Sort for Singly Linked List Real-time application of Data Structures
[ { "code": null, "e": 25008, "s": 24977, "text": " \n09 Dec, 2021\n" }, { "code": null, "e": 25468, "s": 25008, "text": "Circular Doubly Linked List has properties of both Doubly Linked List and Circular Linked List in which two consecutive elements are linked or connected by previous and next pointer and the last node points to the first node by next pointer and also the first node points to the last node by the previous pointer. The program implements all the functions and operations that are possible on a doubly circular list following functions in a menu-driven program." }, { "code": null, "e": 26119, "s": 25468, "text": "Approach: Each function (except display) takes the address of the pointer to the head i.e. the first element of the list. This allows us to change the address of the head pointer. The idea is the use only one pointer, which is of type node, to perform all the operations. node is the class that contains three data members. One member is of type int which stores data of the node and two members of type node*, one store’s address of next element and other stores address of the previous element. This way it is possible to traverse the list in either direction. It is possible to modify, insert, delete search for the element using a single pointer." }, { "code": null, "e": 26138, "s": 26119, "text": "Functions Covered:" }, { "code": null, "e": 26247, "s": 26138, "text": "void insert_front (node **head): This function allows the user to enter a new node at the front of the list." }, { "code": null, "e": 26352, "s": 26247, "text": "void insert_end (node **head): This function allows the user to enter a new node at the end of the list." }, { "code": null, "e": 26471, "s": 26352, "text": "void inser_after (node **head): This function allows the user to enter a new node after a node is entered by the user." }, { "code": null, "e": 26593, "s": 26471, "text": "void insert_before (node **head): This function allows the user to enter a new node before a node is entered by the user." }, { "code": null, "e": 26702, "s": 26593, "text": "void delete_front (node **head): This function allows the user to delete a node from the front of the list." }, { "code": null, "e": 26804, "s": 26702, "text": "void delete_end(node**head): This function allows the user to delete a node from the end of the list." }, { "code": null, "e": 26896, "s": 26804, "text": "void delete_mid( node **head): This function allows deletion of a node entered by the user." }, { "code": null, "e": 26992, "s": 26896, "text": "void search (node *head): Function to search for the location of the array entered by the user." }, { "code": null, "e": 27093, "s": 26992, "text": "void reverse (node **head): Function to reverse the list and make the last element of the list head." }, { "code": null, "e": 27148, "s": 27093, "text": "void display (node *head): Function to print the list." }, { "code": null, "e": 27206, "s": 27148, "text": "Below is the C++ program to implement the above approach:" }, { "code": null, "e": 27210, "s": 27206, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// C++ program for the above approach\n#include <iostream>\nusing namespace std;\n \nclass node {\npublic:\n node* next;\n node* prev;\n int data;\n};\n \n// Function to add the node at the front\n// of the doubly circular LL\nvoid insert_front(node** head)\n{\n // Function to insert node\n // in front of list\n cout << \"\\nEnter Data for New Node:\";\n \n // Create a new node named\n // new_node\n node* new_node = new node;\n \n // Enter data for new_node\n cin >> new_node->data;\n \n if (*head == NULL) {\n \n // If there is no node in\n // the list, create a node\n // pointing to itself and\n // make it head\n new_node->next = new_node;\n new_node->prev = new_node;\n *head = new_node;\n }\n \n else {\n \n // If there already exists\n // elements in the list\n \n // Next of new_node will point\n // to head\n new_node->next = *head;\n \n // prev of new_node will point\n // to prev of head\n new_node->prev = (*head)->prev;\n \n // next of prev of head i.e. next\n // of last node will point to\n // new_node\n ((*head)->prev)->next = new_node;\n \n // prev of head will point\n // to new_node\n (*head)->prev = new_node;\n \n // new_node will become the\n // head of list\n *head = new_node;\n }\n}\n \n// Function to add the node at the end\n// of the doubly circular LL\nvoid insert_end(node** head)\n{\n // Function to insert node at\n // last of list\n cout << \"\\nEnter Data for New Node:\";\n \n // Create new node\n node* new_node = new node;\n cin >> new_node->data;\n \n if (*head == NULL) {\n \n // If there is no element in the\n // list create a node pointing\n // to itself and make it head\n new_node->next = new_node;\n new_node->prev = new_node;\n *head = new_node;\n }\n else {\n \n // If there are elements in the\n // list then create a temp node\n // pointing to current element\n node* curr = *head;\n \n while (curr->next != *head)\n \n // Traverse till the end of\n // list\n curr = curr->next;\n \n // next of new_node will point to\n // next of current node\n new_node->next = curr->next;\n \n // prev of new_node will\n // point to current element\n new_node->prev = curr;\n \n // prev of next of current node\n // i.e. prev of head will point to\n // new_node\n (curr->next)->prev = new_node;\n \n // next of current node will\n // point to new_node\n curr->next = new_node;\n }\n}\n \n// Function to add the node after the\n// given node of doubly circular LL\nvoid insert_after(node** head)\n{\n // Function to enter a node after\n // the element entered by user\n \n // Create new node\n node* new_node = new node;\n cout << \"\\nEnter Data for New Node:\";\n cin >> new_node->data;\n \n if (*head == NULL) {\n \n // If there is no element in\n // the list then create a node\n // pointing to itself and make\n // it head\n cout << \"\\nThere is No element in the List\";\n cout << \"\\nCreating a new node\";\n new_node->prev = new_node;\n new_node->next = new_node;\n *head = new_node;\n }\n else {\n int num;\n \n // Ask user after which node new\n // node is to be inserted\n cout << \"Enter After Element:\";\n cin >> num;\n \n // temp node to traverse list\n // and point to current element\n node* curr = *head;\n \n while (curr->data != num) {\n curr = curr->next;\n \n // If current becomes equal\n // to head i.e. if entire list\n // has been traversed then\n // element entered is not found\n // in list\n if (curr == *head) {\n \n cout << \"\\nEntered Element\"\n << \" Not Found in \"\n \"List\\n\";\n return;\n }\n }\n \n // Control will reach here only if\n // element is found in list\n \n // next of new node will point to\n // next of current node\n new_node->next = curr->next;\n \n // prev of new node will\n // point to current node\n new_node->prev = curr;\n \n // prev of next of current node\n // will point to new node\n (curr->next)->prev = new_node;\n \n // next of current node will\n // point to new node\n curr->next = new_node;\n }\n}\n \n// Function to add the node before the\n// given node of doubly circular LL\nvoid insert_before(node** head)\n{\n // Function to enter node before\n // a node entered by the user\n node* new_node = new node;\n \n if (*head == NULL) {\n \n // If there is no element in the\n // list create new node and make\n // it head\n cout << \"List is Empty!! Creating New node...\";\n cout << \"\\nEnter Data for New Node:\";\n cin >> new_node->data;\n \n new_node->prev = new_node;\n new_node->next = new_node;\n *head = new_node;\n }\n \n else {\n int num;\n \n // Ask user before which node\n // new node is to be inserted\n cout << \"\\nEnter Before Element:\";\n cin >> num;\n \n // If user wants to enter new node\n // before the first node i.e.\n // before head then call insert_front\n // function\n if ((*head)->data == num)\n insert_front(head);\n \n else {\n \n // temp node current for traversing\n // the list and point to current\n // element we assign curr to\n // *head->next this time because\n // data of head has already been\n // checked in previous condition\n node* curr = (*head)->next;\n \n while (curr->data != num) {\n if (curr == *head) {\n \n // If current equal head then\n // entire list has been traversed\n // and the entered element is not\n // found in list\n cout << \"\\nEntered Element Not Found \"\n \"in List!!\\n\";\n return;\n }\n curr = curr->next;\n }\n \n cout << \"\\nEnter Data For New Node:\";\n cin >> new_node->data;\n \n // Control will reaach here only\n // if entered node exists in list\n // and current has found the element\n \n // next of new node will point to\n // current node\n new_node->next = curr;\n \n // prev of new node will point\n // to prev of current node\n new_node->prev = curr->prev;\n \n // next of prev of current node\n // will point to new node\n (curr->prev)->next = new_node;\n \n // prev of current will\n // point to new node\n curr->prev = new_node;\n }\n }\n}\n \n// Function to delete the front node\n// of doubly circular LL\nvoid delete_front(node** head)\n{\n // Function to delete a node\n // from front of list\n if (*head == NULL) {\n \n // If list is already empty\n // print a message\n cout << \"\\nList in empty!!\\n\";\n }\n else if ((*head)->next == *head) {\n \n // If head is the only element\n // in the list delete head and\n // assign it to NULL\n delete *head;\n *head = NULL;\n }\n else {\n node* curr = new node;\n \n // temp node to save address\n // of node next to head\n curr = (*head)->next;\n \n // prev of temp will\n // point to prev of head\n curr->prev = (*head)->prev;\n \n // next of prev of head i.e.\n // next of last node will point\n // to temp\n ((*head)->prev)->next = curr;\n \n // delete head\n delete *head;\n \n // assign head to temp\n *head = curr;\n }\n}\n \n// Function to delete the end node\n// of doubly circular LL\nvoid delete_end(node** head)\n{\n // Function to delete a node\n // from end of list\n if (*head == NULL) {\n \n // If list is already empty\n // print a message\n cout << \"\\nList is Empty!!\\n\";\n }\n else if ((*head)->next == *head) {\n \n // If head is the only element\n // in the list delete head and\n // assign it to NULL\n delete *head;\n *head = NULL;\n }\n else {\n \n // Create temporary node curr\n // to traverse list and point\n // to current element\n node* curr = new node;\n \n // Assign curr to head\n curr = *head;\n while (curr->next != (*head)) {\n \n // Traverse till end of list\n curr = curr->next;\n }\n \n // next of prev of curr will point\n // to next of curr\n (curr->prev)->next = curr->next;\n \n // prev of next of curr will point\n // to prev of curr\n (curr->next)->prev = curr->prev;\n \n // delete curr\n delete curr;\n }\n}\n \n// Function to delete the middle node\n// of doubly circular LL\nvoid delete_mid(node** head)\n{\n // Function to delete a node\n // entered by user\n if (*head == NULL) {\n \n // If list is already empty\n // print a message\n cout << \"\\nList is Empty!!!\";\n }\n \n else {\n cout << \"\\nEnter Element to be deleted:\";\n int num;\n cin >> num;\n \n if ((*head)->data == num) {\n \n // If user wants to delete\n // the head node i.e front\n // node call delete_front(head)\n // function\n delete_front(head);\n }\n \n else {\n \n // temp node to traverse list\n // and point to current node\n node* curr = (*head)->next;\n while ((curr->data) != num) {\n if (curr == (*head)) {\n \n // If curr equals head then\n // entire list has been\n // traversed element to be\n // deleted is not found\n cout << \"\\nEntered Element Not Found \"\n \"in List!!\\n\";\n return;\n }\n \n curr = curr->next;\n }\n \n // control will reach here only\n // if element is found in the list\n \n // next of prev of curr will\n // point to next of curr\n (curr->prev)->next = curr->next;\n \n // prev of next of curr will\n // point to prev of curr\n (curr->next)->prev = curr->prev;\n delete curr;\n }\n }\n}\n \n// Function to search any node in the\n// doubly circular LL\nvoid search(node* head)\n{\n if (head == NULL) {\n \n // If head is null list is empty\n cout << \"List is empty!!\";\n return;\n }\n \n int item;\n cout << \"Enter item to be searched:\";\n \n // Ask user to enter item to\n // be searched\n cin >> item;\n \n // curr pointer is used to\n // traverse list it will point\n // to the current element\n node* curr = head;\n \n int index = 0, count = 0;\n \n do {\n \n // If data in curr is equal to item\n // to be searched print its position\n // index+1\n if (curr->data == item) {\n cout << \"\\nItem found at position:\"\n << index + 1;\n \n // increment count\n count++;\n }\n \n // Index will increment by 1 in\n // each iteration\n index++;\n curr = curr->next;\n \n } while (curr != head);\n \n // If count is still 0 that means\n // item is not found\n if (count == 0)\n cout << \"Item searched not found in list\";\n}\n \n// Function to reverse the doubly\n// circular Linked List\nvoid reverse(node** head)\n{\n if (*head == NULL) {\n \n // If head is null list is empty\n cout << \"List is Empty !!\";\n return;\n }\n \n // curr is used to traverse list\n node* curr = *head;\n while (curr->next != *head) {\n \n // use a temp node to store\n // address of next of curr\n node* temp = curr->next;\n \n // make next of curr to point\n // its previous\n curr->next = curr->prev;\n \n // make previous of curr to\n // point its next\n curr->prev = temp;\n \n // After each iteration move\n // to element which was earlier\n // next of curr\n curr = temp;\n }\n \n // Update the last node separately\n node* temp = curr->next;\n curr->next = curr->prev;\n curr->prev = temp;\n \n // only change is this node will now\n // become head\n *head = curr;\n}\n \n// Function to display the doubly\n// circular linked list\nvoid display(node* head)\n{\n node* curr = head;\n if (curr == NULL)\n cout << \"\\n List is Empty!!\";\n else {\n do {\n cout << curr->data << \"->\";\n curr = curr->next;\n } while (curr != head);\n }\n}\n \nvoid display_menu()\n{\n cout << \"==============================================\"\n \"======================\";\n cout << \"\\nMenu:\\n\";\n cout << \"1. Insert At Front\\n\";\n cout << \"2. Insert At End\\n\";\n cout << \"3. Insert After Element\\n\";\n cout << \"4. Insert Before Element\\n\";\n cout << \"5. Delete From Front\\n\";\n cout << \"6. Delete From End\\n\";\n cout << \"7. Delete A Node\\n\";\n cout << \"8. Search for a element\\n\";\n cout << \"9. Reverse a the list\\n\";\n cout << \"==============================================\"\n \"======================\";\n}\n \n// Driver Code\nint main()\n{\n int choice;\n char repeat_menu = 'y';\n \n // Declaration of head node\n node* head = NULL;\n display_menu();\n do {\n cout << \"\\nEnter Your Choice:\";\n cin >> choice;\n switch (choice) {\n case 1: {\n insert_front(&head);\n display(head);\n break;\n }\n case 2: {\n insert_end(&head);\n display(head);\n break;\n }\n case 3: {\n insert_after(&head);\n display(head);\n break;\n }\n case 4: {\n insert_before(&head);\n display(head);\n break;\n }\n case 5: {\n delete_front(&head);\n display(head);\n break;\n }\n case 6: {\n delete_end(&head);\n display(head);\n break;\n }\n case 7: {\n delete_mid(&head);\n display(head);\n break;\n }\n case 8: {\n search(head);\n break;\n }\n case 9: {\n reverse(&head);\n display(head);\n break;\n }\n default: {\n cout << \"\\nWrong Choice!!!\";\n display_menu();\n break;\n }\n }\n cout << \"\\nEnter More(Y/N)\";\n cin >> repeat_menu;\n \n } while (repeat_menu == 'y' || repeat_menu == 'Y');\n return 0;\n}\n\n\n\n\n\n", "e": 42302, "s": 27220, "text": null }, { "code": null, "e": 42313, "s": 42305, "text": "Output:" }, { "code": null, "e": 42351, "s": 42315, "text": "1. void insert_front (node **head):" }, { "code": null, "e": 42389, "s": 42355, "text": "2. void insert_end (node **head):" }, { "code": null, "e": 42430, "s": 42393, "text": "3. void insert_after (node **head):" }, { "code": null, "e": 42472, "s": 42434, "text": "4. void insert_before (node **head):" }, { "code": null, "e": 42513, "s": 42476, "text": "5. void delete_front (node **head):" }, { "code": null, "e": 42552, "s": 42517, "text": "6. void delete_end (node **head):" }, { "code": null, "e": 42591, "s": 42556, "text": "7. void delete_mid (node **head):" }, { "code": null, "e": 42625, "s": 42595, "text": "8. void search (node *head):" }, { "code": null, "e": 42661, "s": 42629, "text": "9. void reverse (node **head):" }, { "code": null, "e": 42678, "s": 42665, "text": "simmytarika5" }, { "code": null, "e": 42697, "s": 42678, "text": "surindertarika1234" }, { "code": null, "e": 42706, "s": 42697, "text": "sweetyty" }, { "code": null, "e": 42729, "s": 42706, "text": "\ncircular linked list\n" }, { "code": null, "e": 42750, "s": 42729, "text": "\ndoubly linked list\n" }, { "code": null, "e": 42765, "s": 42750, "text": "\nLinked Lists\n" }, { "code": null, "e": 42779, "s": 42765, "text": "\nLinked List\n" }, { "code": null, "e": 42984, "s": 42779, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 43024, "s": 42984, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 43062, "s": 43024, "text": "Delete a node in a Doubly Linked List" }, { "code": null, "e": 43112, "s": 43062, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 43183, "s": 43112, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 43224, "s": 43183, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 43278, "s": 43224, "text": "Insert a node at a specific position in a linked list" }, { "code": null, "e": 43337, "s": 43278, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 43370, "s": 43337, "text": "Priority Queue using Linked List" }, { "code": null, "e": 43408, "s": 43370, "text": "Insertion Sort for Singly Linked List" } ]
Python - AnchorLayout in Kivy
Kivy is an open source Python library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps. It is used to develop the Android application, as well as Desktops applications. In this article we will see how to use the anchor layout positioning. Using AnchorLayouts we place the widgets at one of the borders. The class kivy.uix.anchorlayout.AnchorLayout implements the anchor layout. Both the anchor_x parameter and anchor_y parameter can be passed the values ‘left’, ‘right’ and ‘center’. In the below program we create two buttons, attach them to two anchors and keep them in a BoxLayout. from kivy.app import App from kivy.uix.anchorlayout import AnchorLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button class AnchorLayoutApp(App): def build(self): # Anchor Layout1 anchor1 = AnchorLayout(anchor_x='left', anchor_y='bottom') button1 = Button(text='Bottom-Left', size_hint=(0.3, 0.3),background_color=(1.0, 0.0, 0.0, 1.0)) anchor1.add_widget(button1) # Anchor Layout2 anchor2 = AnchorLayout(anchor_x='right', anchor_y='top') # Add anchor layouts to a box layout button2 = Button(text='Top-Right', size_hint=(0.3, 0.3),background_color=(1.0, 0.0, 0.0, 1.0)) anchor2.add_widget(button2) # Create a box layout BL = BoxLayout() # Add both the anchor layouts to the box layout BL.add_widget(anchor1) BL.add_widget(anchor2) # Return the boxlayout widget return BL # Run the Kivy app if __name__ == '__main__': AnchorLayoutApp().run() Running the above code gives us the following result −
[ { "code": null, "e": 1360, "s": 1062, "text": "Kivy is an open source Python library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps. It is used to develop the Android application, as well as Desktops applications. In this article we will see how to use the anchor layout positioning." }, { "code": null, "e": 1706, "s": 1360, "text": "Using AnchorLayouts we place the widgets at one of the borders. The class kivy.uix.anchorlayout.AnchorLayout implements the anchor layout. Both the anchor_x parameter and anchor_y parameter can be passed the values ‘left’, ‘right’ and ‘center’. In the below program we create two buttons, attach them to two anchors and keep them in a BoxLayout." }, { "code": null, "e": 2679, "s": 1706, "text": "from kivy.app import App\nfrom kivy.uix.anchorlayout import AnchorLayout\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.button import Button\nclass AnchorLayoutApp(App):\n def build(self):\n # Anchor Layout1\n anchor1 = AnchorLayout(anchor_x='left', anchor_y='bottom')\n button1 = Button(text='Bottom-Left', size_hint=(0.3, 0.3),background_color=(1.0, 0.0, 0.0, 1.0))\n anchor1.add_widget(button1)\n # Anchor Layout2\n anchor2 = AnchorLayout(anchor_x='right', anchor_y='top')\n # Add anchor layouts to a box layout\n button2 = Button(text='Top-Right', size_hint=(0.3, 0.3),background_color=(1.0, 0.0, 0.0, 1.0))\n anchor2.add_widget(button2)\n # Create a box layout\n BL = BoxLayout()\n # Add both the anchor layouts to the box layout\n BL.add_widget(anchor1)\n BL.add_widget(anchor2)\n # Return the boxlayout widget\n return BL\n# Run the Kivy app\nif __name__ == '__main__':\n AnchorLayoutApp().run()" }, { "code": null, "e": 2734, "s": 2679, "text": "Running the above code gives us the following result −" } ]
Local Function in C# - GeeksforGeeks
18 Jan, 2022 The local function feature is introduced in C# 7.0. It allows you to declare a method inside the body of an already defined method. Or in other words, we can say that a local function is a private function of a function whose scope is limited to that function in which it is created. The type of local function is similar to the type of function in which it is defined. You can only call the local function from their container members.Important Points: Local functions are declared inside methods, constructors, property accessors, event accessors, anonymous methods, lambda expressions, finalizers, and other local functions. You cannot declare a local function in the expression-bodied member. Local function makes your program more readable and also save you from mistakenly call method because you cannot call a local function directly. In local function, you are allowed to use async and unsafe modifiers. Local function can access the local variables that are defined inside the container method including method parameters. You are not allowed to use any member access modifiers in the local function definition, including private keyword because they are by default private and you are not allowed to make them public. You are also not allowed to use static keyword with local function. You are also not allowed to apply attributes to the local function, or to its parameters, or to its parameter type. Multiple local functions are allowed. Overloading is not allowed for local functions. Example 1: CSharp // C# program to illustrate local functionusing System; public class Program { // Main method public static void Main() { // Local Function void AddValue(int a, int b) { Console.WriteLine("Value of a is: " + a); Console.WriteLine("Value of b is: " + b); Console.WriteLine("Sum of a and b is: {0}", a + b); Console.WriteLine(); } // Calling Local function AddValue(20, 40); AddValue(40, 60); }} Output: Value of a is: 20 Value of b is: 40 Sum of a and b is: 60 Value of a is: 40 Value of b is: 60 Sum of a and b is: 100 Example 2: CSharp // C# program to illustrate local function// accessing the variable of the function// in which they presentusing System; public class Program { // Main method public static void Main() { // Variables of main method int x = 40; int y = 60; // Local Function void AddValue(int a, int b) { Console.WriteLine("Value of a is: " + a); Console.WriteLine("Value of b is: " + b); Console.WriteLine("Value of x is: " + x); Console.WriteLine("Value of y is: " + y); Console.WriteLine("Sum: {0}", a + b + x + y); Console.WriteLine(); } // Calling Local function AddValue(50, 80); AddValue(79, 70); }} Output: Value of a is: 50 Value of b is: 80 Value of x is: 40 Value of y is: 60 Sum: 230 Value of a is: 79 Value of b is: 70 Value of x is: 40 Value of y is: 60 Sum: 249 Advantages of local function: You are allowed to create local generic functions.Example: CSharp // C# program to illustrate how to// create local generic functionusing System; public class Program { // Main method public static void Main() { // Local Generic Function void MyMethod<MyValue>(MyValue value) { Console.WriteLine("Value is: " + value); } // Calling local generic function MyMethod<int>(123); MyMethod<string>("GeeksforGeeks"); MyMethod<char>('G'); MyMethod<double>(45453.5656); }} Output: Value is: 123 Value is: GeeksforGeeks Value is: G Value is: 45453.5656 You are allowed to pass out/ref parameters in local functions. Example: CSharp // C# program to illustrate how can we// out parameter in local functionusing System; public class Program { // Main method public static void Main() { // Local Function with out parameter void MyMethod(string str, out string s) { s = str + "for" + "Geeks"; } string a = null; // Calling Local function MyMethod("Geeks", out a); Console.WriteLine(a); }} Output: GeeksforGeeks You are allowed to use params in local functions.Example: CSharp // C# program to illustrate how can we// pass params in local functionusing System; public class Program { // Main method public static void Main() { // Local Function // Using params void MyMethod(params string[] data) { for (int x = 0; x < data.Length; x++) { Console.WriteLine(data[x]); } } // Calling Local function MyMethod("Geeks", "gfg", "GeeksforGeeks", "123geeks"); }} Output: Geeks gfg GeeksforGeeks 123geeks muaaznaeem sagar0719kumar CSharp-7.0 C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Constructors Introduction to .NET Framework Difference between Ref and Out keywords in C# C# | Class and Object Top 50 C# Interview Questions & Answers Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework C# | Encapsulation Lambda Expressions in C# HashSet in C# with Examples C# | Replace() Method
[ { "code": null, "e": 23553, "s": 23525, "text": "\n18 Jan, 2022" }, { "code": null, "e": 24009, "s": 23553, "text": "The local function feature is introduced in C# 7.0. It allows you to declare a method inside the body of an already defined method. Or in other words, we can say that a local function is a private function of a function whose scope is limited to that function in which it is created. The type of local function is similar to the type of function in which it is defined. You can only call the local function from their container members.Important Points: " }, { "code": null, "e": 24183, "s": 24009, "text": "Local functions are declared inside methods, constructors, property accessors, event accessors, anonymous methods, lambda expressions, finalizers, and other local functions." }, { "code": null, "e": 24252, "s": 24183, "text": "You cannot declare a local function in the expression-bodied member." }, { "code": null, "e": 24397, "s": 24252, "text": "Local function makes your program more readable and also save you from mistakenly call method because you cannot call a local function directly." }, { "code": null, "e": 24467, "s": 24397, "text": "In local function, you are allowed to use async and unsafe modifiers." }, { "code": null, "e": 24587, "s": 24467, "text": "Local function can access the local variables that are defined inside the container method including method parameters." }, { "code": null, "e": 24783, "s": 24587, "text": "You are not allowed to use any member access modifiers in the local function definition, including private keyword because they are by default private and you are not allowed to make them public." }, { "code": null, "e": 24851, "s": 24783, "text": "You are also not allowed to use static keyword with local function." }, { "code": null, "e": 24967, "s": 24851, "text": "You are also not allowed to apply attributes to the local function, or to its parameters, or to its parameter type." }, { "code": null, "e": 25005, "s": 24967, "text": "Multiple local functions are allowed." }, { "code": null, "e": 25053, "s": 25005, "text": "Overloading is not allowed for local functions." }, { "code": null, "e": 25065, "s": 25053, "text": "Example 1: " }, { "code": null, "e": 25072, "s": 25065, "text": "CSharp" }, { "code": "// C# program to illustrate local functionusing System; public class Program { // Main method public static void Main() { // Local Function void AddValue(int a, int b) { Console.WriteLine(\"Value of a is: \" + a); Console.WriteLine(\"Value of b is: \" + b); Console.WriteLine(\"Sum of a and b is: {0}\", a + b); Console.WriteLine(); } // Calling Local function AddValue(20, 40); AddValue(40, 60); }}", "e": 25573, "s": 25072, "text": null }, { "code": null, "e": 25583, "s": 25573, "text": "Output: " }, { "code": null, "e": 25701, "s": 25583, "text": "Value of a is: 20\nValue of b is: 40\nSum of a and b is: 60\n\nValue of a is: 40\nValue of b is: 60\nSum of a and b is: 100" }, { "code": null, "e": 25713, "s": 25701, "text": "Example 2: " }, { "code": null, "e": 25720, "s": 25713, "text": "CSharp" }, { "code": "// C# program to illustrate local function// accessing the variable of the function// in which they presentusing System; public class Program { // Main method public static void Main() { // Variables of main method int x = 40; int y = 60; // Local Function void AddValue(int a, int b) { Console.WriteLine(\"Value of a is: \" + a); Console.WriteLine(\"Value of b is: \" + b); Console.WriteLine(\"Value of x is: \" + x); Console.WriteLine(\"Value of y is: \" + y); Console.WriteLine(\"Sum: {0}\", a + b + x + y); Console.WriteLine(); } // Calling Local function AddValue(50, 80); AddValue(79, 70); }}", "e": 26460, "s": 25720, "text": null }, { "code": null, "e": 26469, "s": 26460, "text": "Output: " }, { "code": null, "e": 26632, "s": 26469, "text": "Value of a is: 50\nValue of b is: 80\nValue of x is: 40\nValue of y is: 60\nSum: 230\n\nValue of a is: 79\nValue of b is: 70\nValue of x is: 40\nValue of y is: 60\nSum: 249" }, { "code": null, "e": 26664, "s": 26632, "text": "Advantages of local function: " }, { "code": null, "e": 26724, "s": 26664, "text": "You are allowed to create local generic functions.Example: " }, { "code": null, "e": 26731, "s": 26724, "text": "CSharp" }, { "code": "// C# program to illustrate how to// create local generic functionusing System; public class Program { // Main method public static void Main() { // Local Generic Function void MyMethod<MyValue>(MyValue value) { Console.WriteLine(\"Value is: \" + value); } // Calling local generic function MyMethod<int>(123); MyMethod<string>(\"GeeksforGeeks\"); MyMethod<char>('G'); MyMethod<double>(45453.5656); }}", "e": 27218, "s": 26731, "text": null }, { "code": null, "e": 27228, "s": 27218, "text": "Output: " }, { "code": null, "e": 27299, "s": 27228, "text": "Value is: 123\nValue is: GeeksforGeeks\nValue is: G\nValue is: 45453.5656" }, { "code": null, "e": 27374, "s": 27301, "text": "You are allowed to pass out/ref parameters in local functions. Example: " }, { "code": null, "e": 27381, "s": 27374, "text": "CSharp" }, { "code": "// C# program to illustrate how can we// out parameter in local functionusing System; public class Program { // Main method public static void Main() { // Local Function with out parameter void MyMethod(string str, out string s) { s = str + \"for\" + \"Geeks\"; } string a = null; // Calling Local function MyMethod(\"Geeks\", out a); Console.WriteLine(a); }}", "e": 27832, "s": 27381, "text": null }, { "code": null, "e": 27842, "s": 27832, "text": "Output: " }, { "code": null, "e": 27856, "s": 27842, "text": "GeeksforGeeks" }, { "code": null, "e": 27917, "s": 27858, "text": "You are allowed to use params in local functions.Example: " }, { "code": null, "e": 27924, "s": 27917, "text": "CSharp" }, { "code": "// C# program to illustrate how can we// pass params in local functionusing System; public class Program { // Main method public static void Main() { // Local Function // Using params void MyMethod(params string[] data) { for (int x = 0; x < data.Length; x++) { Console.WriteLine(data[x]); } } // Calling Local function MyMethod(\"Geeks\", \"gfg\", \"GeeksforGeeks\", \"123geeks\"); }}", "e": 28413, "s": 27924, "text": null }, { "code": null, "e": 28423, "s": 28413, "text": "Output: " }, { "code": null, "e": 28456, "s": 28423, "text": "Geeks\ngfg\nGeeksforGeeks\n123geeks" }, { "code": null, "e": 28471, "s": 28460, "text": "muaaznaeem" }, { "code": null, "e": 28486, "s": 28471, "text": "sagar0719kumar" }, { "code": null, "e": 28497, "s": 28486, "text": "CSharp-7.0" }, { "code": null, "e": 28500, "s": 28497, "text": "C#" }, { "code": null, "e": 28598, "s": 28500, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28607, "s": 28598, "text": "Comments" }, { "code": null, "e": 28620, "s": 28607, "text": "Old Comments" }, { "code": null, "e": 28638, "s": 28620, "text": "C# | Constructors" }, { "code": null, "e": 28669, "s": 28638, "text": "Introduction to .NET Framework" }, { "code": null, "e": 28715, "s": 28669, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28737, "s": 28715, "text": "C# | Class and Object" }, { "code": null, "e": 28777, "s": 28737, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28864, "s": 28777, "text": "Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework" }, { "code": null, "e": 28883, "s": 28864, "text": "C# | Encapsulation" }, { "code": null, "e": 28908, "s": 28883, "text": "Lambda Expressions in C#" }, { "code": null, "e": 28936, "s": 28908, "text": "HashSet in C# with Examples" } ]
A Data Scientist’s Guide to Identify and Resolve Data Quality Issues | by Arunn Thevapalan | Towards Data Science
If you've worked in the AI industry with real-world data, you’d understand the pain. No matter how streamlined the data collection process is, the data we’re about to model is always messy. According to IBM, the 80/20 Rule holds for data science as well. 80% of a data scientist’s valuable time is spent simply finding, cleansing, and organizing data, leaving only 20% of the time actually performing analysis. Wrangling data isn’t fun. I know it’s crucial, “garbage in garbage out,” and all that, but I simply can’t seem to enjoy cleaning whitespaces, fixing regex expressions, and resolving unforeseen problems in data. According to Google Research: “Everyone wants to do the model work, but not the data work” — I’m guilty as charged. Further, the paper introduces a phenomenon called data cascades which are compounding events causing adverse, downstream effects that arise from underlying data issues. In reality, the problem so far is threefold: Most data scientists don’t enjoy cleaning and wrangling data Only 20% of the time is available to do meaningful analytics Data quality issues, if not treated early, will cascade and affect downstream The only solution to these problems is to ensure that cleaning data is easy, quick, and natural. We need tools and technologies that help us, the data scientists, quickly identify and resolve data quality issues to use our valuable time in analytics and AI — the work we truly enjoy. In this article, I’d present one such open-source tool that helps identify data quality issues upfront based on the expected priority. I’m so relieved this tool exists, and I can’t wait to share it with you today. ydata-quality is an open-source python library for assessing Data Quality throughout the multiple stages of a data pipeline development. The library is intuitive, easy to use, and you can directly integrate it into your machine learning workflow. To me personally, the cool thing about the library is the availability of priority-based ranking of data quality issues (more on this later), which is helpful when our time is limited, and we want to tackle high-impact data quality issues first. Let me show you how to use a real-world example of messy data. In this example, we will: Load a messy datasetAnalyze the data quality issuesDig further on to the warnings raisedApply strategies to mitigate themCheck the final quality analysis on the semi-cleaned data Load a messy dataset Analyze the data quality issues Dig further on to the warnings raised Apply strategies to mitigate them Check the final quality analysis on the semi-cleaned data It’s always best to create a virtual environment using either venv or conda for the project before installing any library. Once that’s done, type the following on your terminal to install the library: pip install ydata-quality Now that your environment is ready let’s move on to the example. We will use the transformed census dataset for this example, which you can download from this GitHub repository. You can find all codes used in this tutorial in this Jupyter Notebook. I recommend you either clone the repository or download the notebook to follow along with the example. As a first step, we will load the dataset and the necessary libraries. Note that the package has multiple modules (Bias & Fairness, Data Expectations, Data Relations, Drift Analysis, Erroneous Data, Labelling, and Missing) for separate data quality issues, but we can start with the DataQuality engine, which wraps all the individual engines into a single class. from ydata_quality import DataQualityimport pandas as pddf = pd.read_csv('../datasets/transformed/census_10k.csv') This is supposed to be a lengthy process, but the DataQuality engine does an excellent job of abstracting all the details. Simply create the main class and call the evaluate() method. # create the main class that holds all quality modulesdq = DataQuality(df=df)# run the testsresults = dq.evaluate() We would be presented with a report with the data quality issues. Let’s dissect the report: Warnings: These contain the details for issues detected during the data quality analysis. Priority: For every detected issue, a priority is assigned (a lower value indicates high priority) based on the expected impact of the issue. Modules: Every detected issue is linked to a data quality test carried out by a module (Eg: Data relations, Duplicates, etc.) Tying everything together, we notice five warnings have been identified, one of which is a high-priority issue. Detected by the “Duplicates” module, we have an entirely duplicated column that will need fixing. To dive deeper into this issue, we use the get_warnings() method. Simply type in the following: dq.get_warnings(test="Duplicate Columns") We can see the detailed output specific to the issue we want to resolve: [QualityWarning(category='Duplicates', test='Duplicate Columns', description='Found 1 columns with exactly the same feature values as other columns.', priority=<Priority.P1: 1>, data={'workclass': ['workclass2']})] Based on the evaluation, we can see that the columns workclass and workclass2 are entirely duplicated, which can have serious consequences downstream. A complete picture of data quality requires multiple perspectives, and hence the need for eight separate modules. Though they are encapsulated in the DataQuality class, some modules will not run unless we provide specific arguments. For example, DataQuality class did not execute Bias & Fairness quality tests since we didn’t specify the sensitive features. But the beauty of the library is, we can treat it as a standalone test and perform it. Let’s understand it better by performing Bias and Fairness tests. from ydata_quality.bias_fairness import BiasFairness#create the main class that holds all quality modulesbf = BiasFairness(df=df, sensitive_features=['race', 'sex'], label='income')# run the testsbf_results = bf.evaluate() When we ran the code above, we generated another similar report specific to the chosen module. From the report, we understand that we may have a proxy feature leaking information about a sensitive attribute and severe under-representation of feature values of a sensitive attribute. To investigate the first warning, we can fetch more details with the get_warnings() method filtering for a specific test. bf.get_warnings(test='Proxy Identification') We can see the detailed output specific to the issue we want to resolve: [QualityWarning(category='Bias&Fairness', test='Proxy Identification', description='Found 1 feature pairs of correlation to sensitive attributes with values higher than defined threshold (0.5).', priority=<Priority.P2: 2>, data=features relationship_sex 0.650656 Name: association, dtype: float64)] Based on the detailed warning, we inspect the columns relationship and sex and notice that some relationship statuses (e.g., Husband, Wife) are gender-specific, thus impacting the correlation. We could change these categorical values to be gender-neutral (e.g., Married). Let’s be practical. We can never have 100% cleaned data. It’s all about tackling down the most impactful issues in the time available. As a data scientist, it’s a decision that you need to take based on your constraints. For this example, let’s aim to have no high priority (P1) issues and tackle at least one bias and fairness warning. A simple data cleaning function based on the warnings raised can look as below: We drop the duplicated column work_class2and replace the relationship values to be more general and gender-neutral. If you’d like to do further data cleaning, please feel free to. I would love to see how the data cleaning looks like, should you chose to progress further. Remember, you’re the data scientist — and that decision is always in your hand. You may skip this step, but I’m in peace of mind when I check my processed data through another final check. I highly recommend you do it, too, so you know the status of the data after completing your data cleaning transformations. You can simply call the quality engine first and the evaluate() method to retrieve the sample report again. Here’s how the reports for the DataQuality engine and the BiasFairness engine look like after we have cleaned the data. We can infer from the two reports above that our high-priority issue has been resolved, and another lower priority issue has been resolved as we aimed for. Look, just because we hate to clean data doesn’t mean we quit doing that. There’s a reason it’s an integral phase of the machine learning workflow, and the solution is to integrate valuable tools and libraries such as ydata-quality into our workflow. In this article, we learned how to use the open-source package to assess the data quality of our dataset, both with the DataQuality main engine as well as through a specific module engine (e.g. BiasFairness). Further, we saw howQualityWarning provides a high-level measure of severity and points us to the original data that raised the warning. We then defined a data cleaning pipeline based on the data quality issues to transform the messy data and observed how it solved the warnings we aimed for. The library was developed by the team at YData, which is on a mission to improve data quality for the AI industry. Got further questions? Join the friendly slack community and ask away all the questions directly from the developing team (you can find me there too!) Together we can definitely improve the library, and your feedback would mean that the library solves most of your pressing problems in the future. I can’t wait to see you use the library and hear your feedback inside the community.
[ { "code": null, "e": 362, "s": 172, "text": "If you've worked in the AI industry with real-world data, you’d understand the pain. No matter how streamlined the data collection process is, the data we’re about to model is always messy." }, { "code": null, "e": 583, "s": 362, "text": "According to IBM, the 80/20 Rule holds for data science as well. 80% of a data scientist’s valuable time is spent simply finding, cleansing, and organizing data, leaving only 20% of the time actually performing analysis." }, { "code": null, "e": 794, "s": 583, "text": "Wrangling data isn’t fun. I know it’s crucial, “garbage in garbage out,” and all that, but I simply can’t seem to enjoy cleaning whitespaces, fixing regex expressions, and resolving unforeseen problems in data." }, { "code": null, "e": 1079, "s": 794, "text": "According to Google Research: “Everyone wants to do the model work, but not the data work” — I’m guilty as charged. Further, the paper introduces a phenomenon called data cascades which are compounding events causing adverse, downstream effects that arise from underlying data issues." }, { "code": null, "e": 1124, "s": 1079, "text": "In reality, the problem so far is threefold:" }, { "code": null, "e": 1185, "s": 1124, "text": "Most data scientists don’t enjoy cleaning and wrangling data" }, { "code": null, "e": 1246, "s": 1185, "text": "Only 20% of the time is available to do meaningful analytics" }, { "code": null, "e": 1324, "s": 1246, "text": "Data quality issues, if not treated early, will cascade and affect downstream" }, { "code": null, "e": 1608, "s": 1324, "text": "The only solution to these problems is to ensure that cleaning data is easy, quick, and natural. We need tools and technologies that help us, the data scientists, quickly identify and resolve data quality issues to use our valuable time in analytics and AI — the work we truly enjoy." }, { "code": null, "e": 1822, "s": 1608, "text": "In this article, I’d present one such open-source tool that helps identify data quality issues upfront based on the expected priority. I’m so relieved this tool exists, and I can’t wait to share it with you today." }, { "code": null, "e": 2069, "s": 1822, "text": "ydata-quality is an open-source python library for assessing Data Quality throughout the multiple stages of a data pipeline development. The library is intuitive, easy to use, and you can directly integrate it into your machine learning workflow." }, { "code": null, "e": 2315, "s": 2069, "text": "To me personally, the cool thing about the library is the availability of priority-based ranking of data quality issues (more on this later), which is helpful when our time is limited, and we want to tackle high-impact data quality issues first." }, { "code": null, "e": 2404, "s": 2315, "text": "Let me show you how to use a real-world example of messy data. In this example, we will:" }, { "code": null, "e": 2583, "s": 2404, "text": "Load a messy datasetAnalyze the data quality issuesDig further on to the warnings raisedApply strategies to mitigate themCheck the final quality analysis on the semi-cleaned data" }, { "code": null, "e": 2604, "s": 2583, "text": "Load a messy dataset" }, { "code": null, "e": 2636, "s": 2604, "text": "Analyze the data quality issues" }, { "code": null, "e": 2674, "s": 2636, "text": "Dig further on to the warnings raised" }, { "code": null, "e": 2708, "s": 2674, "text": "Apply strategies to mitigate them" }, { "code": null, "e": 2766, "s": 2708, "text": "Check the final quality analysis on the semi-cleaned data" }, { "code": null, "e": 2967, "s": 2766, "text": "It’s always best to create a virtual environment using either venv or conda for the project before installing any library. Once that’s done, type the following on your terminal to install the library:" }, { "code": null, "e": 2993, "s": 2967, "text": "pip install ydata-quality" }, { "code": null, "e": 3058, "s": 2993, "text": "Now that your environment is ready let’s move on to the example." }, { "code": null, "e": 3345, "s": 3058, "text": "We will use the transformed census dataset for this example, which you can download from this GitHub repository. You can find all codes used in this tutorial in this Jupyter Notebook. I recommend you either clone the repository or download the notebook to follow along with the example." }, { "code": null, "e": 3708, "s": 3345, "text": "As a first step, we will load the dataset and the necessary libraries. Note that the package has multiple modules (Bias & Fairness, Data Expectations, Data Relations, Drift Analysis, Erroneous Data, Labelling, and Missing) for separate data quality issues, but we can start with the DataQuality engine, which wraps all the individual engines into a single class." }, { "code": null, "e": 3823, "s": 3708, "text": "from ydata_quality import DataQualityimport pandas as pddf = pd.read_csv('../datasets/transformed/census_10k.csv')" }, { "code": null, "e": 4007, "s": 3823, "text": "This is supposed to be a lengthy process, but the DataQuality engine does an excellent job of abstracting all the details. Simply create the main class and call the evaluate() method." }, { "code": null, "e": 4123, "s": 4007, "text": "# create the main class that holds all quality modulesdq = DataQuality(df=df)# run the testsresults = dq.evaluate()" }, { "code": null, "e": 4189, "s": 4123, "text": "We would be presented with a report with the data quality issues." }, { "code": null, "e": 4215, "s": 4189, "text": "Let’s dissect the report:" }, { "code": null, "e": 4305, "s": 4215, "text": "Warnings: These contain the details for issues detected during the data quality analysis." }, { "code": null, "e": 4447, "s": 4305, "text": "Priority: For every detected issue, a priority is assigned (a lower value indicates high priority) based on the expected impact of the issue." }, { "code": null, "e": 4573, "s": 4447, "text": "Modules: Every detected issue is linked to a data quality test carried out by a module (Eg: Data relations, Duplicates, etc.)" }, { "code": null, "e": 4849, "s": 4573, "text": "Tying everything together, we notice five warnings have been identified, one of which is a high-priority issue. Detected by the “Duplicates” module, we have an entirely duplicated column that will need fixing. To dive deeper into this issue, we use the get_warnings() method." }, { "code": null, "e": 4879, "s": 4849, "text": "Simply type in the following:" }, { "code": null, "e": 4921, "s": 4879, "text": "dq.get_warnings(test=\"Duplicate Columns\")" }, { "code": null, "e": 4994, "s": 4921, "text": "We can see the detailed output specific to the issue we want to resolve:" }, { "code": null, "e": 5209, "s": 4994, "text": "[QualityWarning(category='Duplicates', test='Duplicate Columns', description='Found 1 columns with exactly the same feature values as other columns.', priority=<Priority.P1: 1>, data={'workclass': ['workclass2']})]" }, { "code": null, "e": 5360, "s": 5209, "text": "Based on the evaluation, we can see that the columns workclass and workclass2 are entirely duplicated, which can have serious consequences downstream." }, { "code": null, "e": 5593, "s": 5360, "text": "A complete picture of data quality requires multiple perspectives, and hence the need for eight separate modules. Though they are encapsulated in the DataQuality class, some modules will not run unless we provide specific arguments." }, { "code": null, "e": 5805, "s": 5593, "text": "For example, DataQuality class did not execute Bias & Fairness quality tests since we didn’t specify the sensitive features. But the beauty of the library is, we can treat it as a standalone test and perform it." }, { "code": null, "e": 5871, "s": 5805, "text": "Let’s understand it better by performing Bias and Fairness tests." }, { "code": null, "e": 6094, "s": 5871, "text": "from ydata_quality.bias_fairness import BiasFairness#create the main class that holds all quality modulesbf = BiasFairness(df=df, sensitive_features=['race', 'sex'], label='income')# run the testsbf_results = bf.evaluate()" }, { "code": null, "e": 6189, "s": 6094, "text": "When we ran the code above, we generated another similar report specific to the chosen module." }, { "code": null, "e": 6499, "s": 6189, "text": "From the report, we understand that we may have a proxy feature leaking information about a sensitive attribute and severe under-representation of feature values of a sensitive attribute. To investigate the first warning, we can fetch more details with the get_warnings() method filtering for a specific test." }, { "code": null, "e": 6544, "s": 6499, "text": "bf.get_warnings(test='Proxy Identification')" }, { "code": null, "e": 6617, "s": 6544, "text": "We can see the detailed output specific to the issue we want to resolve:" }, { "code": null, "e": 6919, "s": 6617, "text": "[QualityWarning(category='Bias&Fairness', test='Proxy Identification', description='Found 1 feature pairs of correlation to sensitive attributes with values higher than defined threshold (0.5).', priority=<Priority.P2: 2>, data=features relationship_sex 0.650656 Name: association, dtype: float64)]" }, { "code": null, "e": 7191, "s": 6919, "text": "Based on the detailed warning, we inspect the columns relationship and sex and notice that some relationship statuses (e.g., Husband, Wife) are gender-specific, thus impacting the correlation. We could change these categorical values to be gender-neutral (e.g., Married)." }, { "code": null, "e": 7412, "s": 7191, "text": "Let’s be practical. We can never have 100% cleaned data. It’s all about tackling down the most impactful issues in the time available. As a data scientist, it’s a decision that you need to take based on your constraints." }, { "code": null, "e": 7608, "s": 7412, "text": "For this example, let’s aim to have no high priority (P1) issues and tackle at least one bias and fairness warning. A simple data cleaning function based on the warnings raised can look as below:" }, { "code": null, "e": 7724, "s": 7608, "text": "We drop the duplicated column work_class2and replace the relationship values to be more general and gender-neutral." }, { "code": null, "e": 7960, "s": 7724, "text": "If you’d like to do further data cleaning, please feel free to. I would love to see how the data cleaning looks like, should you chose to progress further. Remember, you’re the data scientist — and that decision is always in your hand." }, { "code": null, "e": 8192, "s": 7960, "text": "You may skip this step, but I’m in peace of mind when I check my processed data through another final check. I highly recommend you do it, too, so you know the status of the data after completing your data cleaning transformations." }, { "code": null, "e": 8420, "s": 8192, "text": "You can simply call the quality engine first and the evaluate() method to retrieve the sample report again. Here’s how the reports for the DataQuality engine and the BiasFairness engine look like after we have cleaned the data." }, { "code": null, "e": 8576, "s": 8420, "text": "We can infer from the two reports above that our high-priority issue has been resolved, and another lower priority issue has been resolved as we aimed for." }, { "code": null, "e": 8827, "s": 8576, "text": "Look, just because we hate to clean data doesn’t mean we quit doing that. There’s a reason it’s an integral phase of the machine learning workflow, and the solution is to integrate valuable tools and libraries such as ydata-quality into our workflow." }, { "code": null, "e": 9172, "s": 8827, "text": "In this article, we learned how to use the open-source package to assess the data quality of our dataset, both with the DataQuality main engine as well as through a specific module engine (e.g. BiasFairness). Further, we saw howQualityWarning provides a high-level measure of severity and points us to the original data that raised the warning." }, { "code": null, "e": 9328, "s": 9172, "text": "We then defined a data cleaning pipeline based on the data quality issues to transform the messy data and observed how it solved the warnings we aimed for." }, { "code": null, "e": 9594, "s": 9328, "text": "The library was developed by the team at YData, which is on a mission to improve data quality for the AI industry. Got further questions? Join the friendly slack community and ask away all the questions directly from the developing team (you can find me there too!)" } ]
jQuery - Selectors
The most important functionality of jQuery is provided by its Selectors. This tutorial will explain jQuery Selectors with simple examples covering all the three standard selectors. jQuery Selectors are used to select HTML element(s) from an HTML document. Consider an HTML document is given and you need to select all the <div> from this document. This is where jQuery Selectors will help. jQuery Selectors can find HTML elements (ie. Select HTML elements) based on the following: HTML element Name HTML element Name Element ID Element ID Element Class Element Class Element attribute name Element attribute name Element attribute value Element attribute value Many more criteria Many more criteria The jQuery library harnesses the power of Cascading Style Sheets (CSS) selectors to let us quickly and easily access elements or groups of elements in the Document Object Model (DOM). jQuery Selectors works in very similar way on an HTML document like an SQL select statement works on a Database. Following is the jQuery Selector Syntax for selecting HTML elements: $(document).ready(function(){ $(selector) }); A jQuery selector starts with a dollar sign $ and then we put a selector inside the braces (). Here $() is called factory function, which makes use of following three building blocks while selecting elements in a given document: Represents an HTML element name available in the DOM. For example $('p') selects all paragraphs <p> in the document. Represents a HTML element available with the given ID in the DOM. For example $('#some-id') selects the single element in the document that has some-id as element Id. Represents a HTML elements available with the given class in the DOM. For example $('.some-class') selects all elements in the document that have a class of some-class. All the above selectors can be used either on their own or in combination with other selectors. All the jQuery selectors are based on the same principle except some tweaking. The jQuery element selector selects HTML element(s) based on the element name. Following is a simple syntax of an element selector: $(document).ready(function(){ $("Html Element Name") }); Please note while using element name as jQuery Selector, we are not giving angle braces alongwith the element. For example, we are giving only plain p instead of <p>. Following is an example to select all the <p> elements from an HTML document and then change the background color of those elements. You will not see any <p> element in the output generated by this example. You can also change the code to use different element names as selector and then click the icon to verify the result. <html> <head> <title>The jQuery Example</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script> <script type = "text/javascript"> $(document).ready(function() { $("p").css("background-color", "yellow"); }); </script> </head> <body> <h1>jQuery Element Selector</h1> <p>This is p tag</p> <span>This is span tag</span> <div>This is div tag</div> </body> </html> The jQuery #id selector selects an HTML element based on the element id attribute. Following is a simple syntax of a #id selector: $(document).ready(function(){ $("#id of the element") }); To use jQuery #id selector, you need to make sure that id attribute should be uniquely assigned to all the elements. If you elements will have similar id then it will not produce correct result. Following is an example to select the <p> element whose id is foo and change the background color of those elements. You can also change the code to use different element id attribute as selector and then click the icon to verify the result. <html> <head> <title>The jQuery Example</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script> <script type = "text/javascript"> $(document).ready(function() { $("#foo").css("background-color", "yellow"); }); </script> </head> <body> <h1>jQuery Element Selector</h1> <p id="foo">This is foo p tag</p> <span id="bar">This is bar span tag</span> <div id="bill">This is bill div tag</div> </body> </html> The jQuery .class selector selects HTML element(s) based on the element class attribute. Following is a simple syntax of a .class selector: $(document).ready(function(){ $(".class of the element") }); Because a class can be assigned to multiple HTML elements with in an HTML document, so it is very much possible to find out multiple elements with a single .class selector statement. Following is an example to select all the <p> elements whose class is foo and change the background color of those elements. You can also change the code to use different element class name as selector and then click the icon to verify the result. <html> <head> <title>The jQuery Example</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script> <script type = "text/javascript"> $(document).ready(function() { $(".foo").css("background-color", "yellow"); }); </script> </head> <body> <h1>jQuery Element Selector</h1> <p class="foo">This is foo p tag</p> <p class="foo">This is one more foo p tag</p> <span class="bar">This is bar span tag</span> <div class="bill">This is bill div tag</div> </body> </html> So far we have covered only three standard jQuery Selectors. For a complete detail of all these jQuery selectors, you can go to through jQuery Selectors Reference. 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2503, "s": 2322, "text": "The most important functionality of jQuery is provided by its Selectors. This tutorial will explain jQuery Selectors with simple examples covering all the three standard selectors." }, { "code": null, "e": 2712, "s": 2503, "text": "jQuery Selectors are used to select HTML element(s) from an HTML document. Consider an HTML document is given and you need to select all the <div> from this document. This is where jQuery Selectors will help." }, { "code": null, "e": 2803, "s": 2712, "text": "jQuery Selectors can find HTML elements (ie. Select HTML elements) based on the following:" }, { "code": null, "e": 2821, "s": 2803, "text": "HTML element Name" }, { "code": null, "e": 2839, "s": 2821, "text": "HTML element Name" }, { "code": null, "e": 2850, "s": 2839, "text": "Element ID" }, { "code": null, "e": 2861, "s": 2850, "text": "Element ID" }, { "code": null, "e": 2875, "s": 2861, "text": "Element Class" }, { "code": null, "e": 2889, "s": 2875, "text": "Element Class" }, { "code": null, "e": 2912, "s": 2889, "text": "Element attribute name" }, { "code": null, "e": 2935, "s": 2912, "text": "Element attribute name" }, { "code": null, "e": 2959, "s": 2935, "text": "Element attribute value" }, { "code": null, "e": 2983, "s": 2959, "text": "Element attribute value" }, { "code": null, "e": 3002, "s": 2983, "text": "Many more criteria" }, { "code": null, "e": 3021, "s": 3002, "text": "Many more criteria" }, { "code": null, "e": 3206, "s": 3021, "text": "The jQuery library harnesses the power of Cascading Style Sheets (CSS) selectors to let us quickly and easily access elements or groups of elements in the Document Object Model (DOM). " }, { "code": null, "e": 3319, "s": 3206, "text": "jQuery Selectors works in very similar way on an HTML document like an SQL select statement works on a Database." }, { "code": null, "e": 3388, "s": 3319, "text": "Following is the jQuery Selector Syntax for selecting HTML elements:" }, { "code": null, "e": 3439, "s": 3388, "text": "$(document).ready(function(){\n $(selector)\n});\n" }, { "code": null, "e": 3668, "s": 3439, "text": "A jQuery selector starts with a dollar sign $ and then we put a selector inside the braces (). Here $() is called factory function, which makes use of following three building blocks while selecting elements in a given document:" }, { "code": null, "e": 3785, "s": 3668, "text": "Represents an HTML element name available in the DOM. For example $('p') selects all paragraphs <p> in the document." }, { "code": null, "e": 3952, "s": 3785, "text": "Represents a HTML element available with the given ID in the DOM. For example $('#some-id') selects the single element in the document that has some-id as element Id." }, { "code": null, "e": 4121, "s": 3952, "text": "Represents a HTML elements available with the given class in the DOM. For example $('.some-class') selects all elements in the document that have a class of some-class." }, { "code": null, "e": 4296, "s": 4121, "text": "All the above selectors can be used either on their own or in combination with other selectors. All the jQuery selectors are based on the same principle except some tweaking." }, { "code": null, "e": 4428, "s": 4296, "text": "The jQuery element selector selects HTML element(s) based on the element name. Following is a simple syntax of an element selector:" }, { "code": null, "e": 4490, "s": 4428, "text": "$(document).ready(function(){\n $(\"Html Element Name\")\n});\n" }, { "code": null, "e": 4657, "s": 4490, "text": "Please note while using element name as jQuery Selector, we are not giving angle braces alongwith the element. For example, we are giving only plain p instead of <p>." }, { "code": null, "e": 4983, "s": 4657, "text": "Following is an example to select all the <p> elements from an HTML document and then change the background color of those elements. You will not see any <p> element in the output generated by this example. You can also change the code to use different element names as selector and then click the icon to verify the result." }, { "code": null, "e": 5488, "s": 4983, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\">\n $(document).ready(function() {\n $(\"p\").css(\"background-color\", \"yellow\");\n });\n </script>\n </head>\n\t\n <body>\n <h1>jQuery Element Selector</h1>\n <p>This is p tag</p>\n <span>This is span tag</span>\n <div>This is div tag</div>\n </body>\n</html>\n" }, { "code": null, "e": 5619, "s": 5488, "text": "The jQuery #id selector selects an HTML element based on the element id attribute. Following is a simple syntax of a #id selector:" }, { "code": null, "e": 5682, "s": 5619, "text": "$(document).ready(function(){\n $(\"#id of the element\")\n});\n" }, { "code": null, "e": 5877, "s": 5682, "text": "To use jQuery #id selector, you need to make sure that id attribute should be uniquely assigned to all the elements. If you elements will have similar id then it will not produce correct result." }, { "code": null, "e": 6120, "s": 5877, "text": "Following is an example to select the <p> element whose id is foo and change the background color of those elements. You can also change the code to use different element id attribute as selector and then click the icon to verify the result." }, { "code": null, "e": 6670, "s": 6120, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\">\n $(document).ready(function() {\n $(\"#foo\").css(\"background-color\", \"yellow\");\n });\n </script>\n </head>\n\t\n <body>\n <h1>jQuery Element Selector</h1>\n <p id=\"foo\">This is foo p tag</p>\n <span id=\"bar\">This is bar span tag</span>\n <div id=\"bill\">This is bill div tag</div>\n </body>\n</html>\n" }, { "code": null, "e": 6810, "s": 6670, "text": "The jQuery .class selector selects HTML element(s) based on the element class attribute. Following is a simple syntax of a .class selector:" }, { "code": null, "e": 6876, "s": 6810, "text": "$(document).ready(function(){\n $(\".class of the element\")\n});\n" }, { "code": null, "e": 7060, "s": 6876, "text": "Because a class can be assigned to multiple HTML elements with in an HTML document, so it is very much possible to find out multiple elements with a single .class selector statement. " }, { "code": null, "e": 7309, "s": 7060, "text": "Following is an example to select all the <p> elements whose class is foo and change the background color of those elements. You can also change the code to use different element class name as selector and then click the icon to verify the result." }, { "code": null, "e": 7920, "s": 7309, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\">\n $(document).ready(function() {\n $(\".foo\").css(\"background-color\", \"yellow\");\n });\n </script>\n </head>\n\t\n <body>\n <h1>jQuery Element Selector</h1>\n <p class=\"foo\">This is foo p tag</p>\n <p class=\"foo\">This is one more foo p tag</p>\n <span class=\"bar\">This is bar span tag</span>\n <div class=\"bill\">This is bill div tag</div>\n </body>\n</html>\n" }, { "code": null, "e": 8086, "s": 7920, "text": "So far we have covered only three standard jQuery Selectors. For a complete detail of all these jQuery selectors, you can go to through jQuery Selectors Reference. \n" }, { "code": null, "e": 8119, "s": 8086, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 8133, "s": 8119, "text": " Mahesh Kumar" }, { "code": null, "e": 8168, "s": 8133, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8182, "s": 8168, "text": " Pratik Singh" }, { "code": null, "e": 8217, "s": 8182, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8234, "s": 8217, "text": " Frahaan Hussain" }, { "code": null, "e": 8267, "s": 8234, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 8295, "s": 8267, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 8328, "s": 8295, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 8349, "s": 8328, "text": " Sandip Bhattacharya" }, { "code": null, "e": 8381, "s": 8349, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 8398, "s": 8381, "text": " Laurence Svekis" }, { "code": null, "e": 8405, "s": 8398, "text": " Print" }, { "code": null, "e": 8416, "s": 8405, "text": " Add Notes" } ]
How to merge two different array of objects using JavaScript?
Suppose, we have two different array of objects that contains information about the questions answered by some people − const arr1=[ { PersonalID: '11', qusetionNumber: '1', value: 'Something' }, { PersonalID: '12', qusetionNumber: '2', value: 'whatever' }, { PersonalID: '13', qusetionNumber: '3', value: 'anything' }, { PersonalID: '14', qusetionNumber: '4', value: 'null' } ]; const arr2=[ { qusetionNumber: '2', chID: '111', cValue: 'red' }, { qusetionNumber: '2', chID: '112', cValue: 'green'}, { qusetionNumber: '2', chID: '113', cValue: 'blue' }, {qusetionNumber: '3', choiceID: '114', cValue: 'yellow'}, {qusetionNumber: '4', choiceID: '115', cValue: 'red'} ]; We are required to write a function that groups this data, present in both arrays according to unique persons, i.e., one object depicting the question and choices for each unique person. Therefore, the final output should look something like this − const output = [{ personalID:11, qusetionNumber:1, value: 'Something' }, { personalID:12, qusetionNumber:2, value: 'whatever', choice:[ { qusetionNumber: '2', chID: '111', cValue: 'red' }, { qusetionNumber: '2', chID: '112', cValue: 'green'}, { qusetionNumber: '2', chID: '113', cValue: 'blue' } ] }, { personalID:13, qusetionNumber:3, value: 'anything', choice:[ { qusetionNumber: '3', chID: '114', cValue: 'yellow' } ] }, { personalID:14, qusetionNumber:4, value: 'null', choice:[ { qusetionNumber: '4', chID: '115', cValue: 'red' } ] }]; The code for this will be − const arr1=[ { PersonalID: '11', qusetionNumber: '1', value: 'Something' }, { PersonalID: '12', qusetionNumber: '2', value: 'whatever' }, { PersonalID: '13', qusetionNumber: '3', value: 'anything' }, { PersonalID: '14', qusetionNumber: '4', value: 'null' } ]; const arr2=[ { qusetionNumber: '2', chID: '111', cValue: 'red' }, { qusetionNumber: '2', chID: '112', cValue: 'green'}, { qusetionNumber: '2', chID: '113', cValue: 'blue' }, {qusetionNumber: '3', choiceID: '114', cValue: 'yellow'}, {qusetionNumber: '4', choiceID: '115', cValue: 'red'} ]; const mergeArray = (arr1 = [], arr2 = []) => { let i = -1; const copy = arr1.slice(); copy.forEach(obj => { const helper = []; arr2.forEach(obj2 => { if(obj.qusetionNumber == obj2.qusetionNumber){ i++; helper.push(arr2[i]); }; }) if(helper.length !== 0){ obj.choice = helper; }; }) return copy; }; console.log(JSON.stringify(mergeArray(arr1, arr2), undefined, 4)); And the output in the console will be − [ { "PersonalID": "11", "qusetionNumber": "1", "value": "Something" }, { "PersonalID": "12", "qusetionNumber": "2", "value": "whatever", "choice": [ { "qusetionNumber": "2", "chID": "111", "cValue": "red" }, { "qusetionNumber": "2", "chID": "112", "cValue": "green" }, { "qusetionNumber": "2", "chID": "113", "cValue": "blue" } ] }, { "PersonalID": "13", "qusetionNumber": "3", "value": "anything", "choice": [ { "qusetionNumber": "3", "choiceID": "114", "cValue": "yellow" } ] }, { "PersonalID": "14", "qusetionNumber": "4", "value": "null", "choice": [ { "qusetionNumber": "4", "choiceID": "115", "cValue": "red" } ] } ]
[ { "code": null, "e": 1182, "s": 1062, "text": "Suppose, we have two different array of objects that contains information about the questions answered by some people −" }, { "code": null, "e": 1758, "s": 1182, "text": "const arr1=[\n { PersonalID: '11', qusetionNumber: '1', value: 'Something' },\n { PersonalID: '12', qusetionNumber: '2', value: 'whatever' },\n { PersonalID: '13', qusetionNumber: '3', value: 'anything' },\n { PersonalID: '14', qusetionNumber: '4', value: 'null' }\n];\nconst arr2=[\n { qusetionNumber: '2', chID: '111', cValue: 'red' },\n { qusetionNumber: '2', chID: '112', cValue: 'green'},\n { qusetionNumber: '2', chID: '113', cValue: 'blue' },\n {qusetionNumber: '3', choiceID: '114', cValue: 'yellow'},\n {qusetionNumber: '4', choiceID: '115', cValue: 'red'}\n];" }, { "code": null, "e": 1945, "s": 1758, "text": "We are required to write a function that groups this data, present in both arrays according to unique persons, i.e., one object depicting the question and choices for each unique person." }, { "code": null, "e": 2007, "s": 1945, "text": "Therefore, the final output should look something like this −" }, { "code": null, "e": 2632, "s": 2007, "text": "const output = [{\n personalID:11,\n qusetionNumber:1,\n value: 'Something'\n},\n{\n personalID:12,\n qusetionNumber:2,\n value: 'whatever',\n choice:[\n { qusetionNumber: '2', chID: '111', cValue: 'red' },\n { qusetionNumber: '2', chID: '112', cValue: 'green'},\n { qusetionNumber: '2', chID: '113', cValue: 'blue' }\n ]\n},\n{\n personalID:13,\n qusetionNumber:3,\n value: 'anything',\n choice:[\n { qusetionNumber: '3', chID: '114', cValue: 'yellow' }\n ]\n},\n{\n personalID:14,\n qusetionNumber:4,\n value: 'null',\n choice:[\n { qusetionNumber: '4', chID: '115', cValue: 'red' }\n ]\n}];" }, { "code": null, "e": 2660, "s": 2632, "text": "The code for this will be −" }, { "code": null, "e": 3697, "s": 2660, "text": "const arr1=[\n { PersonalID: '11', qusetionNumber: '1', value: 'Something' },\n { PersonalID: '12', qusetionNumber: '2', value: 'whatever' },\n { PersonalID: '13', qusetionNumber: '3', value: 'anything' },\n { PersonalID: '14', qusetionNumber: '4', value: 'null' }\n];\nconst arr2=[\n { qusetionNumber: '2', chID: '111', cValue: 'red' },\n { qusetionNumber: '2', chID: '112', cValue: 'green'},\n { qusetionNumber: '2', chID: '113', cValue: 'blue' },\n {qusetionNumber: '3', choiceID: '114', cValue: 'yellow'},\n {qusetionNumber: '4', choiceID: '115', cValue: 'red'}\n];\nconst mergeArray = (arr1 = [], arr2 = []) => {\n let i = -1;\n const copy = arr1.slice();\n copy.forEach(obj => {\n const helper = [];\n arr2.forEach(obj2 => {\n if(obj.qusetionNumber == obj2.qusetionNumber){\n i++;\n helper.push(arr2[i]);\n };\n })\n if(helper.length !== 0){\n obj.choice = helper;\n };\n })\n return copy;\n};\nconsole.log(JSON.stringify(mergeArray(arr1, arr2), undefined, 4));" }, { "code": null, "e": 3737, "s": 3697, "text": "And the output in the console will be −" }, { "code": null, "e": 4762, "s": 3737, "text": "[\n {\n \"PersonalID\": \"11\",\n \"qusetionNumber\": \"1\",\n \"value\": \"Something\"\n },\n {\n \"PersonalID\": \"12\",\n \"qusetionNumber\": \"2\",\n \"value\": \"whatever\",\n \"choice\": [\n {\n \"qusetionNumber\": \"2\",\n \"chID\": \"111\",\n \"cValue\": \"red\"\n },\n {\n \"qusetionNumber\": \"2\",\n \"chID\": \"112\",\n \"cValue\": \"green\"\n },\n {\n \"qusetionNumber\": \"2\",\n \"chID\": \"113\",\n \"cValue\": \"blue\"\n }\n ]\n },\n {\n \"PersonalID\": \"13\",\n \"qusetionNumber\": \"3\",\n \"value\": \"anything\",\n \"choice\": [\n {\n \"qusetionNumber\": \"3\",\n \"choiceID\": \"114\",\n \"cValue\": \"yellow\"\n }\n ]\n },\n {\n \"PersonalID\": \"14\",\n \"qusetionNumber\": \"4\",\n \"value\": \"null\",\n \"choice\": [\n {\n \"qusetionNumber\": \"4\",\n \"choiceID\": \"115\",\n \"cValue\": \"red\"\n }\n ]\n }\n]" } ]
C++ program to overload extraction operator
Suppose we have a Person class with two attributes first_name and the last_name. It also has two methods called get_first_name() and get_last_name() to retrieve or set first name and last name respectively. We shall have to overload the extraction operator (<<) to print the first name and the last name to print them using cout statement. So, if the input is like a person object with first name and last name ("Sumit", "Ray"), then the output will be First name − Sumit, Last name − Ray. To solve this, we will follow these steps − To overload extraction operator, it should be defined outside the class To overload extraction operator, it should be defined outside the class The return type will be an ostream reference The return type will be an ostream reference The input parameters are an ostream reference variable os, and object reference variable The input parameters are an ostream reference variable os, and object reference variable using os extract all parts of the object in proper order using os extract all parts of the object in proper order return os object reference. return os object reference. Let us see the following implementation to get better understanding − #include <iostream> using namespace std; class Person { private: string f_name; string l_name; public: Person(string first_name, string last_name) : f_name(first_name), l_name(last_name) {} string& get_first_name() { return f_name; } string& get_last_name() { return l_name; } }; ostream& operator<<(ostream& os, Person& p) { os << "First name: " << p.get_first_name() << ", Last name: " << p.get_last_name(); return os; } int main(){ Person p("Sumit", "Ray"); cout << p << ", he is our member."; } p("Sumit", "Ray") First name: Sumit, Last name: Ray, he is our member.
[ { "code": null, "e": 1402, "s": 1062, "text": "Suppose we have a Person class with two attributes first_name and the last_name. It also has two methods called get_first_name() and get_last_name() to retrieve or set first name and last name respectively. We shall have to overload the extraction operator (<<) to print the first name and the last name to print them using cout statement." }, { "code": null, "e": 1552, "s": 1402, "text": "So, if the input is like a person object with first name and last name (\"Sumit\", \"Ray\"), then the output will be First name − Sumit, Last name − Ray." }, { "code": null, "e": 1596, "s": 1552, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1668, "s": 1596, "text": "To overload extraction operator, it should be defined outside the class" }, { "code": null, "e": 1740, "s": 1668, "text": "To overload extraction operator, it should be defined outside the class" }, { "code": null, "e": 1785, "s": 1740, "text": "The return type will be an ostream reference" }, { "code": null, "e": 1830, "s": 1785, "text": "The return type will be an ostream reference" }, { "code": null, "e": 1919, "s": 1830, "text": "The input parameters are an ostream reference variable os, and object reference variable" }, { "code": null, "e": 2008, "s": 1919, "text": "The input parameters are an ostream reference variable os, and object reference variable" }, { "code": null, "e": 2065, "s": 2008, "text": "using os extract all parts of the object in proper order" }, { "code": null, "e": 2122, "s": 2065, "text": "using os extract all parts of the object in proper order" }, { "code": null, "e": 2150, "s": 2122, "text": "return os object reference." }, { "code": null, "e": 2178, "s": 2150, "text": "return os object reference." }, { "code": null, "e": 2248, "s": 2178, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2850, "s": 2248, "text": "#include <iostream>\nusing namespace std;\nclass Person {\n private:\n string f_name;\n string l_name;\n public:\n Person(string first_name, string last_name) : f_name(first_name), l_name(last_name) {}\n string& get_first_name() {\n return f_name;\n }\n string& get_last_name() {\n return l_name;\n }\n};\nostream& operator<<(ostream& os, Person& p) {\n os << \"First name: \" << p.get_first_name() << \", Last name: \" << p.get_last_name();\n return os;\n}\nint main(){\n Person p(\"Sumit\", \"Ray\");\n \n cout << p << \", he is our member.\";\n}\n" }, { "code": null, "e": 2868, "s": 2850, "text": "p(\"Sumit\", \"Ray\")" }, { "code": null, "e": 2921, "s": 2868, "text": "First name: Sumit, Last name: Ray, he is our member." } ]
Appending One Row at a Time in Empty Pandas DataFrame | Towards Data Science
A very common question in the context of pandas is whether you can actually create an empty DataFrame and then iteratively fill it in by appending -say- one row at a time. However, this approach tends to be quite inefficient and should be avoided at all costs. In today’s article we are going to discuss an alternative approach that will give you the same result but much more efficiently than creating an empty DataFrame and then using loops to append rows in it. Of course, it is actually possible to create an empty pandas DataFrame and then append rows in an iteratively fashion. This approach in particular would look like below: import numpy as npimport pandas as pdfrom numpy.random import randint# Make sure results are reproduciblenp.random.seed(10)# Instantiate an empty pandas DFdf = pd.DataFrame(columns=['colA', 'colB', 'colC'])# Fill in the dataframe using random integersfor i in range(7): df.loc[i] = [i] + list(randint(100, size=2))print(df) colA colB colC0 0 9 151 1 64 282 2 89 933 3 29 84 4 73 05 5 40 366 6 16 11 Even though the approach above will do the trick, it must be avoided since it is quite inefficient and there are certainly way more efficient approaches rather than creating an empty DataFrame and then build it up using iterative loops. An even worse approach, is the use of append() or concat() methods inside loops. It is worth noting that concat() (and therefore append()) makes a full copy of the data, and that constantly reusing this function can create a significant performance hit. If you need to use the operation over several datasets, use a list comprehension. — pandas docs Instead of appending rows in an iterative fashion using loc[] property or append/concat methods, you can actually append the data into a list and finally instantiate a new pandas DataFrame directly from the pre-created list. This is even mentioned in the official pandas documentation. Iteratively appending rows to a DataFrame can be more computationally intensive than a single concatenate. A better solution is to append those rows to a list and then concatenate the list with the original DataFrame all at once. — pandas docs import numpy as npimport pandas as pdfrom numpy.random import randint# Make sure results are reproduciblenp.random.seed(10)data = []for i in range(7): data.append([i] + list(randint(100, size=2))df = pd.DataFrame(data, columns=['colA', 'colB', 'colC'])print(df) colA colB colC0 0 9 151 1 64 282 2 89 933 3 29 84 4 73 05 5 40 366 6 16 11 Working with lists (either appending or removing elements) is much more efficient and you must always prefer this approach when it comes to iteratively appending rows to pandas DataFrames. In today’s article, we discussed why it is important to avoid creating empty pandas DataFrames and iteratively filling them up as this is going to significantly affect the performance. Instead, we explored how to iteratively build such constructs using lists and finally create new pandas DataFrames out of the created lists. Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium. You may also like
[ { "code": null, "e": 433, "s": 172, "text": "A very common question in the context of pandas is whether you can actually create an empty DataFrame and then iteratively fill it in by appending -say- one row at a time. However, this approach tends to be quite inefficient and should be avoided at all costs." }, { "code": null, "e": 637, "s": 433, "text": "In today’s article we are going to discuss an alternative approach that will give you the same result but much more efficiently than creating an empty DataFrame and then using loops to append rows in it." }, { "code": null, "e": 807, "s": 637, "text": "Of course, it is actually possible to create an empty pandas DataFrame and then append rows in an iteratively fashion. This approach in particular would look like below:" }, { "code": null, "e": 1262, "s": 807, "text": "import numpy as npimport pandas as pdfrom numpy.random import randint# Make sure results are reproduciblenp.random.seed(10)# Instantiate an empty pandas DFdf = pd.DataFrame(columns=['colA', 'colB', 'colC'])# Fill in the dataframe using random integersfor i in range(7): df.loc[i] = [i] + list(randint(100, size=2))print(df) colA colB colC0 0 9 151 1 64 282 2 89 933 3 29 84 4 73 05 5 40 366 6 16 11" }, { "code": null, "e": 1499, "s": 1262, "text": "Even though the approach above will do the trick, it must be avoided since it is quite inefficient and there are certainly way more efficient approaches rather than creating an empty DataFrame and then build it up using iterative loops." }, { "code": null, "e": 1580, "s": 1499, "text": "An even worse approach, is the use of append() or concat() methods inside loops." }, { "code": null, "e": 1835, "s": 1580, "text": "It is worth noting that concat() (and therefore append()) makes a full copy of the data, and that constantly reusing this function can create a significant performance hit. If you need to use the operation over several datasets, use a list comprehension." }, { "code": null, "e": 1849, "s": 1835, "text": "— pandas docs" }, { "code": null, "e": 2135, "s": 1849, "text": "Instead of appending rows in an iterative fashion using loc[] property or append/concat methods, you can actually append the data into a list and finally instantiate a new pandas DataFrame directly from the pre-created list. This is even mentioned in the official pandas documentation." }, { "code": null, "e": 2365, "s": 2135, "text": "Iteratively appending rows to a DataFrame can be more computationally intensive than a single concatenate. A better solution is to append those rows to a list and then concatenate the list with the original DataFrame all at once." }, { "code": null, "e": 2379, "s": 2365, "text": "— pandas docs" }, { "code": null, "e": 2796, "s": 2379, "text": "import numpy as npimport pandas as pdfrom numpy.random import randint# Make sure results are reproduciblenp.random.seed(10)data = []for i in range(7): data.append([i] + list(randint(100, size=2))df = pd.DataFrame(data, columns=['colA', 'colB', 'colC'])print(df) colA colB colC0 0 9 151 1 64 282 2 89 933 3 29 84 4 73 05 5 40 366 6 16 11" }, { "code": null, "e": 2985, "s": 2796, "text": "Working with lists (either appending or removing elements) is much more efficient and you must always prefer this approach when it comes to iteratively appending rows to pandas DataFrames." }, { "code": null, "e": 3170, "s": 2985, "text": "In today’s article, we discussed why it is important to avoid creating empty pandas DataFrames and iteratively filling them up as this is going to significantly affect the performance." }, { "code": null, "e": 3311, "s": 3170, "text": "Instead, we explored how to iteratively build such constructs using lists and finally create new pandas DataFrames out of the created lists." }, { "code": null, "e": 3482, "s": 3311, "text": "Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium." } ]
Combinatorial Game Theory | Set 3 (Grundy Numbers/Numbers and Mex) - GeeksforGeeks
24 Aug, 2021 We have introduced Combinatorial Game Theory in Set 1 and discussed Game of Nim in Set 2.Grundy Number is a number that defines a state of a game. We can define any impartial game (example : nim game) in terms of Grundy Number. Grundy Numbers or Numbers determine how any Impartial Game (not only the Game of Nim) can be solved once we have calculated the Grundy Numbers associated with that game using Sprague-Grundy Theorem.But before calculating Grundy Numbers, we need to learn about another term- Mex. What is Mex? ‘Minimum excludant’ a.k.a ‘Mex’ of a set of numbers is the smallest non-negative number not present in the set. How to calculate Grundy Numbers? We use this definition- The Grundy Number/ number is equal to 0 for a game that is lost immediately by the first player and is equal to Mex of the numbers of all possible next positions for any other game.Below are three example games and programs to calculate Grundy Number and Mex for each of them. Calculation of Grundy Numbers is done basically by a recursive function called as calculateGrundy() function which uses calculateMex() function as its sub-routine. Example 1 The game starts with a pile of n stones, and the player to move may take any positive number of stones. Calculate the Grundy Numbers for this game. The last player to move wins. Which player wins the game?Since if the first player has 0 stones, he will lose immediately, so Grundy(0) = 0If a player has 1 stones, then he can take all the stones and win. So the next possible position of the game (for the other player) is (0) stonesHence, Grundy(1) = Mex(0) = 1 [According to the definition of Mex]Similarly, If a player has 2 stones, then he can take only 1 stone or he can take all the stones and wins. So the next possible position of the game (for the other player) is (1, 0) stones respectively.Hence, Grundy(2) = Mex(0, 1) = 2 [According to the definition of Mex]Similarly, If a player has ‘n’ stones, then he can take only 1 stone, or he can take 2 stones........ or he can take all the stones and win. So the next possible position of the game (for the other player) is (n-1, n-2,....1) stones respectively.Hence, Grundy(n) = Mex (0, 1, 2, ....n-1) = n [According to the definition of Mex] We summarize the first the Grundy Value from 0 to 10 in the below table- C++ Java Python3 C# Javascript /* A recursive C++ program to find Grundy Number for a game which is like a one-pile version of Nim. Game Description : The game starts with a pile of n stones, and the player to move may take any positive number of stones. The last player to move wins. Which player wins the game? */#include<bits/stdc++.h>using namespace std; // A Function to calculate Mex of all the values in// that set.int calculateMex(unordered_set<int> Set){ int Mex = 0; while (Set.find(Mex) != Set.end()) Mex++; return (Mex);} // A function to Compute Grundy Number of 'n'// Only this function varies according to the gameint calculateGrundy(int n){ if (n == 0) return (0); unordered_set<int> Set; // A Hash Table for (int i=0; i<=n-1; i++) Set.insert(calculateGrundy(i)); return (calculateMex(Set));} // Driver program to test above functionsint main(){ int n = 10; printf("%d", calculateGrundy(n)); return (0);} // A recursive Java program to find Grundy// Number for a game which is like a // one-pile version of Nim. Game // Description : The game starts// with a pile of n stones, and the// player to move may take any// positive number of stones. // The last player to move wins.// Which player wins the game? import java.util.*; class GFG{ // A Function to calculate Mex of all// the values in that set. public static int calculateMex(Set<Integer> Set) { int Mex = 0; while (Set.contains(Mex)) Mex++; return (Mex); } // A function to Compute Grundy Number// of 'n'. Only this function varies// according to the game public static int calculateGrundy(int n) { if (n == 0) return (0); // A Hash Table Set<Integer> Set = new HashSet<Integer>(); for(int i = 0; i <= n - 1; i++) Set.add(calculateGrundy(i)); return (calculateMex(Set)); } // Driver codepublic static void main(String[] args){ int n = 10; System.out.print(calculateGrundy(n));}} // This code is contributed by divyeshrabadiya07 ''' A recursive Python3 program to find Grundy Number fora game which is like a one-pile version of Nim.Game Description : The game starts with a pile of n stones,and the player to move may take any positive number of stones. The last player to move wins. Which player wins the game? ''' # A Function to calculate Mex of all the values in# that set.def calculateMex(Set): Mex = 0 while (Mex in Set): Mex += 1 return (Mex) # A function to Compute Grundy Number of 'n'# Only this function varies according to the gamedef calculateGrundy( n): if (n == 0): return (0) Set = set() # A Hash Table for i in range(n): Set.add(calculateGrundy(i)); return (calculateMex(Set)) # Driver program to test above functionsn = 10;print(calculateGrundy(n)) # This code is contributed by ANKITKUMAR34 // A recursive C# program to find Grundy// Number for a game which is like a // one-pile version of Nim. Game // Description : The game starts // with a pile of n stones, and // the player to move may take// any positive number of stones.// The last player to move wins.// Which player wins the game?using System;using System.Collections; using System.Collections.Generic; class GFG{ // A Function to calculate Mex of all// the values in that set. static int calculateMex(HashSet<int> Set) { int Mex = 0; while (Set.Contains(Mex)) Mex++; return (Mex); } // A function to Compute Grundy Number// of 'n'. Only this function varies// according to the game static int calculateGrundy(int n) { if (n == 0) return (0); // A Hash Table HashSet<int> Set = new HashSet<int>(); for(int i = 0; i <= n - 1; i++) Set.Add(calculateGrundy(i)); return (calculateMex(Set)); } // Driver codepublic static void Main(string []arg){ int n = 10; Console.Write(calculateGrundy(n)); }} // This code is contributed by rutvik_56 <script>// A recursive javascript program to find Grundy// Number for a game which is like a // one-pile version of Nim. Game // Description : The game starts// with a pile of n stones, and the// player to move may take any// positive number of stones. // The last player to move wins.// Which player wins the game? // A Function to calculate Mex of all // the values in that set. function calculateMex( Set) { var Mex = 0; while (Set.has(Mex)) Mex++; return (Mex); } // A function to Compute Grundy Number // of 'n'. Only this function varies // according to the game function calculateGrundy(n) { if (n == 0) return (0); // A Hash Table var set = new Set(); for (i = 0; i <= n - 1; i++) set.add(calculateGrundy(i)); return (calculateMex(set)); } // Driver code var n = 10; document.write(calculateGrundy(n)); // This code contributed by aashish1995</script> Output : 10 The above solution can be optimized using Dynamic Programming as there are overlapping subproblems. The Dynamic programming based implementation can be found here. Example 2 The game starts with a pile of n stones, and the player to move may take any positive number of stones up to 3 only. The last player to move wins. Which player wins the game? This game is 1 pile version of Nim.Since if the first player has 0 stones, he will lose immediately, so Grundy(0) = 0If a player has 1 stones, then he can take all the stones and win. So the next possible position of the game (for the other player) is (0) stones Hence, Grundy(1) = Mex(0) = 1 [According to the definition of Mex]Similarly, if a player has 2 stones, then he can take only 1 stone or he can take 2 stones and win. So the next possible position of the game (for the other player) is (1, 0) stones respectively.Hence, Grundy(2) = Mex(0, 1) = 2 [According to the definition of Mex]Similarly, Grundy(3) = Mex(0, 1, 2) = 3 [According to the definition of Mex] But what about 4 stones ? If a player has 4 stones, then he can take 1 stone or he can take 2 stones or 3 stones, but he can’t take 4 stones (see the constraints of the game). So the next possible position of the game (for the other player) is (3, 2, 1) stones respectively.Hence, Grundy(4) = Mex (1, 2, 3) = 0 [According to the definition of Mex]So we can define Grundy Number of any n >= 4 recursively as-Grundy(n) = Mex[Grundy (n-1), Grundy (n-2), Grundy (n-3)] We summarize the first the Grundy Value from 0 to 10 in the below table- C++ Java Python3 C# Javascript /* A recursive C++ program to find Grundy Number fora game which is one-pile version of Nim.Game Description : The game starts with a pile ofn stones, and the player to move may take anypositive number of stones up to 3 only.The last player to move wins. */#include<bits/stdc++.h>using namespace std; // A Function to calculate Mex of all the values in// that set. // A function to Compute Grundy Number of 'n'// Only this function varies according to the gameint calculateGrundy(int n){ if (n == 0) return (0); if (n == 1) return (1); if (n == 2) return (2); if (n == 3) return (3); else return (n%(3+1));} // Driver program to test above functionsint main(){ int n = 10; printf("%d", calculateGrundy(n)); return (0);} /* A recursive Java program to find Grundy Number for a game which is one-pile version of Nim.Game Description : The game starts witha pile of n stones, and the player tomove may take any positive number of stones up to 3 only.The last player to move wins. */import java.util.*; class GFG{ // A function to Compute Grundy // Number of 'n' Only this function // varies according to the game static int calculateGrundy(int n) { if (n == 0) return 0; if (n == 1) return 1; if (n == 2) return 2; if (n == 3) return 3; else return (n%(3+1)); } // Driver code public static void main(String[] args) { int n = 10; System.out.printf("%d", calculateGrundy(n)); }} // This code is contributed by rahulnamdevrn27 # A recursive Python3 program to find Grundy Number # for a game which is one-pile version of Nim. # Game Description : The game starts with a pile # of n stones, and the player to move may take # any positive number of stones up to 3 only. # The last player to move wins. # A function to Compute Grundy Number of 'n' # Only this function varies according to the game def calculateGrundy(n): if 0 <= n <= 3: return n else: return (n%(3+1)); # Driver program to test above functions if __name__ == "__main__": n = 10 print(calculateGrundy(n)) # This code is contributed by rahulnamdevrn27 /* A recursive Java program to find Grundy Number for a game which is one-pile version of Nim. Game Description : The game starts with a pile of n stones, and the player to move may take any positive number of stones up to 3 only.The last player to move wins. */using System; using System.Collections.Generic; class GFG { // A function to Compute Grundy Number of // 'n' Only this function varies according // to the game static int calculateGrundy(int n) { if (n == 0) return 0; if (n == 1) return 1; if (n == 2) return 2; if (n == 3) return 3; else return (n%(3+1)); } // Driver code public static void Main(String[] args) { int n = 10; Console.Write(calculateGrundy(n)); } } // This code is contributed by rahulnamdevrn27 <script> /* A recursive Javascript program to findGrundy Number for a game which isone-pile version of Nim.Game Description : The game starts witha pile of n stones, and the player tomove may take any positive number of stonesup to 3 only.The last player to move wins. */ // A function to Compute Grundy// Number of 'n' Only this function// varies according to the gamefunction calculateGrundy(n){ if (n == 0) return 0; if (n == 1) return 1; if (n == 2) return 2; if (n == 3) return 3; else return (n % (3 + 1));} // Driver codelet n = 10; document.write(calculateGrundy(n)); // This code is contributed by rag2127 </script> Output : 2 The general solution for above code when we are allowed to pick upto k stones can be found here. Example 3 The game starts with a number- ‘n’ and the player to move divides the number- ‘n’ with 2, 3 or 6 and then takes the floor. If the integer becomes 0, it is removed. The last player to move wins. Which player wins the game? We summarize the first the Grundy Value from 0 to 10 in the below table: Think about how we generated this table. C++ Java Python3 C# Javascript /* A recursive C++ program to find Grundy Number for a game. Game Description: The game starts with a number- 'n' and the player to move divides the number- 'n' with 2, 3 or 6 and then takes the floor. If the integer becomes 0, it is removed. The last player to move wins. */#include<bits/stdc++.h>using namespace std; // A Function to calculate Mex of all the values in// that set.int calculateMex(unordered_set<int> Set){ int Mex = 0; while (Set.find(Mex) != Set.end()) Mex++; return (Mex);} // A function to Compute Grundy Number of 'n'// Only this function varies according to the gameint calculateGrundy (int n){ if (n == 0) return (0); unordered_set<int> Set; // A Hash Table Set.insert(calculateGrundy(n/2)); Set.insert(calculateGrundy(n/3)); Set.insert(calculateGrundy(n/6)); return (calculateMex(Set));} // Driver program to test above functionsint main(){ int n = 10; printf("%d", calculateGrundy (n)); return (0);} /* A recursive Java program to find Grundy Number fora game.Game Description : The game starts with a number- 'n'and the player to move divides the number- 'n' with 2, 3or 6 and then takes the floor. If the integer becomes 0,it is removed. The last player to move wins. */import java.util.*; class GFG { // A Function to calculate Mex of all the values in // that set. static int calculateMex(HashSet<Integer> Set) { int Mex = 0; while (Set.contains(Mex)) { Mex++; } return (Mex); } // A function to Compute Grundy Number of 'n' // Only this function varies according to the game static int calculateGrundy(int n) { if (n == 0) { return (0); } HashSet<Integer> Set = new HashSet<Integer>(); // A Hash Table Set.add(calculateGrundy(n / 2)); Set.add(calculateGrundy(n / 3)); Set.add(calculateGrundy(n / 6)); return (calculateMex(Set)); } // Driver code public static void main(String[] args) { int n = 10; System.out.printf("%d", calculateGrundy(n)); }} // This code is contributed by PrinciRaj1992 # A recursive Python3 program to # find Grundy Number for a game. # Game Description : The game starts with a number- 'n' # and the player to move divides the number- 'n' with 2, 3 # or 6 and then take the floor. If the integer becomes 0, # it is removed. The last player to move wins. # A Function to calculate Mex # of all the values in that set. def calculateMex(Set): Mex = 0 while Mex in Set: Mex += 1 return Mex # A function to Compute Grundy Number of 'n' # Only this function varies according to the game def calculateGrundy(n): if n == 0: return 0 Set = set() # A Hash Table Set.add(calculateGrundy(n // 2)) Set.add(calculateGrundy(n // 3)) Set.add(calculateGrundy(n // 6)) return (calculateMex(Set)) # Driver program to test above functions if __name__ == "__main__": n = 10 print(calculateGrundy(n)) # This code is contributed by Rituraj Jain /* A recursive C# program to find Grundy Number for a game. Game Description: The game starts with a number- 'n' and the player to move divides the number- 'n' with 2, 3 or 6 and then takes the floor. If the integer becomes 0, it is removed. The last player to move wins. */using System;using System.Collections.Generic; class GFG { // A Function to calculate Mex of // all the values in that set. static int calculateMex(HashSet<int> Set) { int Mex = 0; while (Set.Contains(Mex)) { Mex++; } return (Mex); } // A function to Compute Grundy Number of 'n' // Only this function varies according to the game static int calculateGrundy(int n) { if (n == 0) { return (0); } // A Hash Table HashSet<int> Set = new HashSet<int>(); Set.Add(calculateGrundy(n / 2)); Set.Add(calculateGrundy(n / 3)); Set.Add(calculateGrundy(n / 6)); return (calculateMex(Set)); } // Driver code public static void Main() { int n = 10; Console.WriteLine(calculateGrundy(n)); } } // This code is contributed by PrinciRaj1992 <script> /* A recursive Javascript program to find Grundy Number for a game.Game Description : The game starts with a number- 'n' and the player to move divides the number- 'n' with 2, 3 or 6 and thentakes the floor. If the integer becomes 0,it is removed. The last player to move wins. */ // A Function to calculate Mex of all// the values in that set.function calculateMex(set){ let Mex = 0; while (set.has(Mex)) { Mex++; } return (Mex);} // A function to Compute Grundy Number // of 'n'. Only this function varies// according to the gamefunction calculateGrundy(n){ if (n == 0) { return (0); } // A Hash Table let set = new Set(); set.add(calculateGrundy(Math.floor(n / 2))); set.add(calculateGrundy(Math.floor(n / 3))); set.add(calculateGrundy(Math.floor(n / 6))); return(calculateMex(set));} // Driver codelet n = 10; document.write(calculateGrundy(n)); // This code is contributed by avanitrachhadiya2155 </script> Output : 0 The above solution can be optimized using Dynamic Programming as there are overlapping subproblems. The Dynamic programming based implementation can be found here. References- https://en.wikipedia.org/wiki/Mex_(mathematics) https://en.wikipedia.org/wiki/NumberIn the next post, we will be discussing solutions to Impartial Games using Grundy Numbers or Numbers.This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above ozym4nd145 princiraj1992 29AjayKumar Rajput-Ji rituraj_jain rahulnamdevrn27 ANKITKUMAR34 rutvik_56 divyeshrabadiya07 aashish1995 rag2127 avanitrachhadiya2155 sumitgumber28 Game Theory Game Theory Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Minimax Algorithm in Game Theory | Set 2 (Introduction to Evaluation Function) Expectimax Algorithm in Game Theory Classification of Algorithms with Examples Game Theory (Normal-form Game) | Set 4 (Dominance Property-Pure Strategy) Game Theory (Normal-form game) | Set 3 (Game with Mixed Strategy) A modified game of Nim Coin game of two corners (Greedy Approach) Pareto Optimality and its application in Game Theory Choice of Area Find winner when players remove multiples of A or B from Array in each turn
[ { "code": null, "e": 24868, "s": 24840, "text": "\n24 Aug, 2021" }, { "code": null, "e": 25096, "s": 24868, "text": "We have introduced Combinatorial Game Theory in Set 1 and discussed Game of Nim in Set 2.Grundy Number is a number that defines a state of a game. We can define any impartial game (example : nim game) in terms of Grundy Number." }, { "code": null, "e": 25375, "s": 25096, "text": "Grundy Numbers or Numbers determine how any Impartial Game (not only the Game of Nim) can be solved once we have calculated the Grundy Numbers associated with that game using Sprague-Grundy Theorem.But before calculating Grundy Numbers, we need to learn about another term- Mex." }, { "code": null, "e": 25502, "s": 25375, "text": "What is Mex? ‘Minimum excludant’ a.k.a ‘Mex’ of a set of numbers is the smallest non-negative number not present in the set. " }, { "code": null, "e": 26000, "s": 25502, "text": "How to calculate Grundy Numbers? We use this definition- The Grundy Number/ number is equal to 0 for a game that is lost immediately by the first player and is equal to Mex of the numbers of all possible next positions for any other game.Below are three example games and programs to calculate Grundy Number and Mex for each of them. Calculation of Grundy Numbers is done basically by a recursive function called as calculateGrundy() function which uses calculateMex() function as its sub-routine." }, { "code": null, "e": 27109, "s": 26000, "text": "Example 1 The game starts with a pile of n stones, and the player to move may take any positive number of stones. Calculate the Grundy Numbers for this game. The last player to move wins. Which player wins the game?Since if the first player has 0 stones, he will lose immediately, so Grundy(0) = 0If a player has 1 stones, then he can take all the stones and win. So the next possible position of the game (for the other player) is (0) stonesHence, Grundy(1) = Mex(0) = 1 [According to the definition of Mex]Similarly, If a player has 2 stones, then he can take only 1 stone or he can take all the stones and wins. So the next possible position of the game (for the other player) is (1, 0) stones respectively.Hence, Grundy(2) = Mex(0, 1) = 2 [According to the definition of Mex]Similarly, If a player has ‘n’ stones, then he can take only 1 stone, or he can take 2 stones........ or he can take all the stones and win. So the next possible position of the game (for the other player) is (n-1, n-2,....1) stones respectively.Hence, Grundy(n) = Mex (0, 1, 2, ....n-1) = n [According to the definition of Mex] " }, { "code": null, "e": 27183, "s": 27109, "text": "We summarize the first the Grundy Value from 0 to 10 in the below table- " }, { "code": null, "e": 27187, "s": 27183, "text": "C++" }, { "code": null, "e": 27192, "s": 27187, "text": "Java" }, { "code": null, "e": 27200, "s": 27192, "text": "Python3" }, { "code": null, "e": 27203, "s": 27200, "text": "C#" }, { "code": null, "e": 27214, "s": 27203, "text": "Javascript" }, { "code": "/* A recursive C++ program to find Grundy Number for a game which is like a one-pile version of Nim. Game Description : The game starts with a pile of n stones, and the player to move may take any positive number of stones. The last player to move wins. Which player wins the game? */#include<bits/stdc++.h>using namespace std; // A Function to calculate Mex of all the values in// that set.int calculateMex(unordered_set<int> Set){ int Mex = 0; while (Set.find(Mex) != Set.end()) Mex++; return (Mex);} // A function to Compute Grundy Number of 'n'// Only this function varies according to the gameint calculateGrundy(int n){ if (n == 0) return (0); unordered_set<int> Set; // A Hash Table for (int i=0; i<=n-1; i++) Set.insert(calculateGrundy(i)); return (calculateMex(Set));} // Driver program to test above functionsint main(){ int n = 10; printf(\"%d\", calculateGrundy(n)); return (0);}", "e": 28176, "s": 27214, "text": null }, { "code": "// A recursive Java program to find Grundy// Number for a game which is like a // one-pile version of Nim. Game // Description : The game starts// with a pile of n stones, and the// player to move may take any// positive number of stones. // The last player to move wins.// Which player wins the game? import java.util.*; class GFG{ // A Function to calculate Mex of all// the values in that set. public static int calculateMex(Set<Integer> Set) { int Mex = 0; while (Set.contains(Mex)) Mex++; return (Mex); } // A function to Compute Grundy Number// of 'n'. Only this function varies// according to the game public static int calculateGrundy(int n) { if (n == 0) return (0); // A Hash Table Set<Integer> Set = new HashSet<Integer>(); for(int i = 0; i <= n - 1; i++) Set.add(calculateGrundy(i)); return (calculateMex(Set)); } // Driver codepublic static void main(String[] args){ int n = 10; System.out.print(calculateGrundy(n));}} // This code is contributed by divyeshrabadiya07", "e": 29268, "s": 28176, "text": null }, { "code": "''' A recursive Python3 program to find Grundy Number fora game which is like a one-pile version of Nim.Game Description : The game starts with a pile of n stones,and the player to move may take any positive number of stones. The last player to move wins. Which player wins the game? ''' # A Function to calculate Mex of all the values in# that set.def calculateMex(Set): Mex = 0 while (Mex in Set): Mex += 1 return (Mex) # A function to Compute Grundy Number of 'n'# Only this function varies according to the gamedef calculateGrundy( n): if (n == 0): return (0) Set = set() # A Hash Table for i in range(n): Set.add(calculateGrundy(i)); return (calculateMex(Set)) # Driver program to test above functionsn = 10;print(calculateGrundy(n)) # This code is contributed by ANKITKUMAR34", "e": 30106, "s": 29268, "text": null }, { "code": "// A recursive C# program to find Grundy// Number for a game which is like a // one-pile version of Nim. Game // Description : The game starts // with a pile of n stones, and // the player to move may take// any positive number of stones.// The last player to move wins.// Which player wins the game?using System;using System.Collections; using System.Collections.Generic; class GFG{ // A Function to calculate Mex of all// the values in that set. static int calculateMex(HashSet<int> Set) { int Mex = 0; while (Set.Contains(Mex)) Mex++; return (Mex); } // A function to Compute Grundy Number// of 'n'. Only this function varies// according to the game static int calculateGrundy(int n) { if (n == 0) return (0); // A Hash Table HashSet<int> Set = new HashSet<int>(); for(int i = 0; i <= n - 1; i++) Set.Add(calculateGrundy(i)); return (calculateMex(Set)); } // Driver codepublic static void Main(string []arg){ int n = 10; Console.Write(calculateGrundy(n)); }} // This code is contributed by rutvik_56", "e": 31221, "s": 30106, "text": null }, { "code": "<script>// A recursive javascript program to find Grundy// Number for a game which is like a // one-pile version of Nim. Game // Description : The game starts// with a pile of n stones, and the// player to move may take any// positive number of stones. // The last player to move wins.// Which player wins the game? // A Function to calculate Mex of all // the values in that set. function calculateMex( Set) { var Mex = 0; while (Set.has(Mex)) Mex++; return (Mex); } // A function to Compute Grundy Number // of 'n'. Only this function varies // according to the game function calculateGrundy(n) { if (n == 0) return (0); // A Hash Table var set = new Set(); for (i = 0; i <= n - 1; i++) set.add(calculateGrundy(i)); return (calculateMex(set)); } // Driver code var n = 10; document.write(calculateGrundy(n)); // This code contributed by aashish1995</script>", "e": 32241, "s": 31221, "text": null }, { "code": null, "e": 32251, "s": 32241, "text": "Output : " }, { "code": null, "e": 32254, "s": 32251, "text": "10" }, { "code": null, "e": 32418, "s": 32254, "text": "The above solution can be optimized using Dynamic Programming as there are overlapping subproblems. The Dynamic programming based implementation can be found here." }, { "code": null, "e": 32866, "s": 32418, "text": "Example 2 The game starts with a pile of n stones, and the player to move may take any positive number of stones up to 3 only. The last player to move wins. Which player wins the game? This game is 1 pile version of Nim.Since if the first player has 0 stones, he will lose immediately, so Grundy(0) = 0If a player has 1 stones, then he can take all the stones and win. So the next possible position of the game (for the other player) is (0) stones" }, { "code": null, "e": 33273, "s": 32866, "text": "Hence, Grundy(1) = Mex(0) = 1 [According to the definition of Mex]Similarly, if a player has 2 stones, then he can take only 1 stone or he can take 2 stones and win. So the next possible position of the game (for the other player) is (1, 0) stones respectively.Hence, Grundy(2) = Mex(0, 1) = 2 [According to the definition of Mex]Similarly, Grundy(3) = Mex(0, 1, 2) = 3 [According to the definition of Mex]" }, { "code": null, "e": 33738, "s": 33273, "text": "But what about 4 stones ? If a player has 4 stones, then he can take 1 stone or he can take 2 stones or 3 stones, but he can’t take 4 stones (see the constraints of the game). So the next possible position of the game (for the other player) is (3, 2, 1) stones respectively.Hence, Grundy(4) = Mex (1, 2, 3) = 0 [According to the definition of Mex]So we can define Grundy Number of any n >= 4 recursively as-Grundy(n) = Mex[Grundy (n-1), Grundy (n-2), Grundy (n-3)]" }, { "code": null, "e": 33813, "s": 33738, "text": "We summarize the first the Grundy Value from 0 to 10 in the below table- " }, { "code": null, "e": 33817, "s": 33813, "text": "C++" }, { "code": null, "e": 33822, "s": 33817, "text": "Java" }, { "code": null, "e": 33830, "s": 33822, "text": "Python3" }, { "code": null, "e": 33833, "s": 33830, "text": "C#" }, { "code": null, "e": 33844, "s": 33833, "text": "Javascript" }, { "code": "/* A recursive C++ program to find Grundy Number fora game which is one-pile version of Nim.Game Description : The game starts with a pile ofn stones, and the player to move may take anypositive number of stones up to 3 only.The last player to move wins. */#include<bits/stdc++.h>using namespace std; // A Function to calculate Mex of all the values in// that set. // A function to Compute Grundy Number of 'n'// Only this function varies according to the gameint calculateGrundy(int n){ if (n == 0) return (0); if (n == 1) return (1); if (n == 2) return (2); if (n == 3) return (3); else return (n%(3+1));} // Driver program to test above functionsint main(){ int n = 10; printf(\"%d\", calculateGrundy(n)); return (0);}", "e": 34626, "s": 33844, "text": null }, { "code": "/* A recursive Java program to find Grundy Number for a game which is one-pile version of Nim.Game Description : The game starts witha pile of n stones, and the player tomove may take any positive number of stones up to 3 only.The last player to move wins. */import java.util.*; class GFG{ // A function to Compute Grundy // Number of 'n' Only this function // varies according to the game static int calculateGrundy(int n) { if (n == 0) return 0; if (n == 1) return 1; if (n == 2) return 2; if (n == 3) return 3; else return (n%(3+1)); } // Driver code public static void main(String[] args) { int n = 10; System.out.printf(\"%d\", calculateGrundy(n)); }} // This code is contributed by rahulnamdevrn27", "e": 35479, "s": 34626, "text": null }, { "code": "# A recursive Python3 program to find Grundy Number # for a game which is one-pile version of Nim. # Game Description : The game starts with a pile # of n stones, and the player to move may take # any positive number of stones up to 3 only. # The last player to move wins. # A function to Compute Grundy Number of 'n' # Only this function varies according to the game def calculateGrundy(n): if 0 <= n <= 3: return n else: return (n%(3+1)); # Driver program to test above functions if __name__ == \"__main__\": n = 10 print(calculateGrundy(n)) # This code is contributed by rahulnamdevrn27", "e": 36134, "s": 35479, "text": null }, { "code": "/* A recursive Java program to find Grundy Number for a game which is one-pile version of Nim. Game Description : The game starts with a pile of n stones, and the player to move may take any positive number of stones up to 3 only.The last player to move wins. */using System; using System.Collections.Generic; class GFG { // A function to Compute Grundy Number of // 'n' Only this function varies according // to the game static int calculateGrundy(int n) { if (n == 0) return 0; if (n == 1) return 1; if (n == 2) return 2; if (n == 3) return 3; else return (n%(3+1)); } // Driver code public static void Main(String[] args) { int n = 10; Console.Write(calculateGrundy(n)); } } // This code is contributed by rahulnamdevrn27", "e": 37029, "s": 36134, "text": null }, { "code": "<script> /* A recursive Javascript program to findGrundy Number for a game which isone-pile version of Nim.Game Description : The game starts witha pile of n stones, and the player tomove may take any positive number of stonesup to 3 only.The last player to move wins. */ // A function to Compute Grundy// Number of 'n' Only this function// varies according to the gamefunction calculateGrundy(n){ if (n == 0) return 0; if (n == 1) return 1; if (n == 2) return 2; if (n == 3) return 3; else return (n % (3 + 1));} // Driver codelet n = 10; document.write(calculateGrundy(n)); // This code is contributed by rag2127 </script>", "e": 37710, "s": 37029, "text": null }, { "code": null, "e": 37720, "s": 37710, "text": "Output : " }, { "code": null, "e": 37722, "s": 37720, "text": "2" }, { "code": null, "e": 37819, "s": 37722, "text": "The general solution for above code when we are allowed to pick upto k stones can be found here." }, { "code": null, "e": 38051, "s": 37819, "text": "Example 3 The game starts with a number- ‘n’ and the player to move divides the number- ‘n’ with 2, 3 or 6 and then takes the floor. If the integer becomes 0, it is removed. The last player to move wins. Which player wins the game?" }, { "code": null, "e": 38125, "s": 38051, "text": "We summarize the first the Grundy Value from 0 to 10 in the below table: " }, { "code": null, "e": 38166, "s": 38125, "text": "Think about how we generated this table." }, { "code": null, "e": 38170, "s": 38166, "text": "C++" }, { "code": null, "e": 38175, "s": 38170, "text": "Java" }, { "code": null, "e": 38183, "s": 38175, "text": "Python3" }, { "code": null, "e": 38186, "s": 38183, "text": "C#" }, { "code": null, "e": 38197, "s": 38186, "text": "Javascript" }, { "code": "/* A recursive C++ program to find Grundy Number for a game. Game Description: The game starts with a number- 'n' and the player to move divides the number- 'n' with 2, 3 or 6 and then takes the floor. If the integer becomes 0, it is removed. The last player to move wins. */#include<bits/stdc++.h>using namespace std; // A Function to calculate Mex of all the values in// that set.int calculateMex(unordered_set<int> Set){ int Mex = 0; while (Set.find(Mex) != Set.end()) Mex++; return (Mex);} // A function to Compute Grundy Number of 'n'// Only this function varies according to the gameint calculateGrundy (int n){ if (n == 0) return (0); unordered_set<int> Set; // A Hash Table Set.insert(calculateGrundy(n/2)); Set.insert(calculateGrundy(n/3)); Set.insert(calculateGrundy(n/6)); return (calculateMex(Set));} // Driver program to test above functionsint main(){ int n = 10; printf(\"%d\", calculateGrundy (n)); return (0);}", "e": 39190, "s": 38197, "text": null }, { "code": "/* A recursive Java program to find Grundy Number fora game.Game Description : The game starts with a number- 'n'and the player to move divides the number- 'n' with 2, 3or 6 and then takes the floor. If the integer becomes 0,it is removed. The last player to move wins. */import java.util.*; class GFG { // A Function to calculate Mex of all the values in // that set. static int calculateMex(HashSet<Integer> Set) { int Mex = 0; while (Set.contains(Mex)) { Mex++; } return (Mex); } // A function to Compute Grundy Number of 'n' // Only this function varies according to the game static int calculateGrundy(int n) { if (n == 0) { return (0); } HashSet<Integer> Set = new HashSet<Integer>(); // A Hash Table Set.add(calculateGrundy(n / 2)); Set.add(calculateGrundy(n / 3)); Set.add(calculateGrundy(n / 6)); return (calculateMex(Set)); } // Driver code public static void main(String[] args) { int n = 10; System.out.printf(\"%d\", calculateGrundy(n)); }} // This code is contributed by PrinciRaj1992", "e": 40380, "s": 39190, "text": null }, { "code": "# A recursive Python3 program to # find Grundy Number for a game. # Game Description : The game starts with a number- 'n' # and the player to move divides the number- 'n' with 2, 3 # or 6 and then take the floor. If the integer becomes 0, # it is removed. The last player to move wins. # A Function to calculate Mex # of all the values in that set. def calculateMex(Set): Mex = 0 while Mex in Set: Mex += 1 return Mex # A function to Compute Grundy Number of 'n' # Only this function varies according to the game def calculateGrundy(n): if n == 0: return 0 Set = set() # A Hash Table Set.add(calculateGrundy(n // 2)) Set.add(calculateGrundy(n // 3)) Set.add(calculateGrundy(n // 6)) return (calculateMex(Set)) # Driver program to test above functions if __name__ == \"__main__\": n = 10 print(calculateGrundy(n)) # This code is contributed by Rituraj Jain", "e": 41322, "s": 40380, "text": null }, { "code": "/* A recursive C# program to find Grundy Number for a game. Game Description: The game starts with a number- 'n' and the player to move divides the number- 'n' with 2, 3 or 6 and then takes the floor. If the integer becomes 0, it is removed. The last player to move wins. */using System;using System.Collections.Generic; class GFG { // A Function to calculate Mex of // all the values in that set. static int calculateMex(HashSet<int> Set) { int Mex = 0; while (Set.Contains(Mex)) { Mex++; } return (Mex); } // A function to Compute Grundy Number of 'n' // Only this function varies according to the game static int calculateGrundy(int n) { if (n == 0) { return (0); } // A Hash Table HashSet<int> Set = new HashSet<int>(); Set.Add(calculateGrundy(n / 2)); Set.Add(calculateGrundy(n / 3)); Set.Add(calculateGrundy(n / 6)); return (calculateMex(Set)); } // Driver code public static void Main() { int n = 10; Console.WriteLine(calculateGrundy(n)); } } // This code is contributed by PrinciRaj1992", "e": 42546, "s": 41322, "text": null }, { "code": "<script> /* A recursive Javascript program to find Grundy Number for a game.Game Description : The game starts with a number- 'n' and the player to move divides the number- 'n' with 2, 3 or 6 and thentakes the floor. If the integer becomes 0,it is removed. The last player to move wins. */ // A Function to calculate Mex of all// the values in that set.function calculateMex(set){ let Mex = 0; while (set.has(Mex)) { Mex++; } return (Mex);} // A function to Compute Grundy Number // of 'n'. Only this function varies// according to the gamefunction calculateGrundy(n){ if (n == 0) { return (0); } // A Hash Table let set = new Set(); set.add(calculateGrundy(Math.floor(n / 2))); set.add(calculateGrundy(Math.floor(n / 3))); set.add(calculateGrundy(Math.floor(n / 6))); return(calculateMex(set));} // Driver codelet n = 10; document.write(calculateGrundy(n)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 43544, "s": 42546, "text": null }, { "code": null, "e": 43554, "s": 43544, "text": "Output : " }, { "code": null, "e": 43556, "s": 43554, "text": "0" }, { "code": null, "e": 43720, "s": 43556, "text": "The above solution can be optimized using Dynamic Programming as there are overlapping subproblems. The Dynamic programming based implementation can be found here." }, { "code": null, "e": 44312, "s": 43720, "text": "References- https://en.wikipedia.org/wiki/Mex_(mathematics) https://en.wikipedia.org/wiki/NumberIn the next post, we will be discussing solutions to Impartial Games using Grundy Numbers or Numbers.This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 44323, "s": 44312, "text": "ozym4nd145" }, { "code": null, "e": 44337, "s": 44323, "text": "princiraj1992" }, { "code": null, "e": 44349, "s": 44337, "text": "29AjayKumar" }, { "code": null, "e": 44359, "s": 44349, "text": "Rajput-Ji" }, { "code": null, "e": 44372, "s": 44359, "text": "rituraj_jain" }, { "code": null, "e": 44388, "s": 44372, "text": "rahulnamdevrn27" }, { "code": null, "e": 44401, "s": 44388, "text": "ANKITKUMAR34" }, { "code": null, "e": 44411, "s": 44401, "text": "rutvik_56" }, { "code": null, "e": 44429, "s": 44411, "text": "divyeshrabadiya07" }, { "code": null, "e": 44441, "s": 44429, "text": "aashish1995" }, { "code": null, "e": 44449, "s": 44441, "text": "rag2127" }, { "code": null, "e": 44470, "s": 44449, "text": "avanitrachhadiya2155" }, { "code": null, "e": 44484, "s": 44470, "text": "sumitgumber28" }, { "code": null, "e": 44496, "s": 44484, "text": "Game Theory" }, { "code": null, "e": 44508, "s": 44496, "text": "Game Theory" }, { "code": null, "e": 44606, "s": 44508, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44615, "s": 44606, "text": "Comments" }, { "code": null, "e": 44628, "s": 44615, "text": "Old Comments" }, { "code": null, "e": 44707, "s": 44628, "text": "Minimax Algorithm in Game Theory | Set 2 (Introduction to Evaluation Function)" }, { "code": null, "e": 44743, "s": 44707, "text": "Expectimax Algorithm in Game Theory" }, { "code": null, "e": 44786, "s": 44743, "text": "Classification of Algorithms with Examples" }, { "code": null, "e": 44860, "s": 44786, "text": "Game Theory (Normal-form Game) | Set 4 (Dominance Property-Pure Strategy)" }, { "code": null, "e": 44926, "s": 44860, "text": "Game Theory (Normal-form game) | Set 3 (Game with Mixed Strategy)" }, { "code": null, "e": 44949, "s": 44926, "text": "A modified game of Nim" }, { "code": null, "e": 44992, "s": 44949, "text": "Coin game of two corners (Greedy Approach)" }, { "code": null, "e": 45045, "s": 44992, "text": "Pareto Optimality and its application in Game Theory" }, { "code": null, "e": 45060, "s": 45045, "text": "Choice of Area" } ]
KnockoutJS - Declarative Bindings
Declarative binding in KnockoutJS provides a powerful way to connect data to UI. It is important to understand the relationship between bindings and Observables. Technically, these two are different. You can use normal JavaScript object as ViewModel and KnockoutJS can process View's binding correctly. Without Observable, the property from the UI will be processed only for the first time. In this case, it cannot update automatically based on the underlying data update. To achieve this, bindings must be referred to Observable properties. The binding consists of 2 items, the binding name and value. Following is a simple example − Today is : <span data-bind = "text: whatDay"></span> Here, text is the binding name and whatDay is the binding value. You can have multiple bindings separated by comma, as shown in the following syntax. Your name: <input data-bind = "value: yourName, valueUpdate: 'afterkeydown'" /> Here, value is updated after each key is pressed. The binding value can be a single value, literal, a variable or can be a JavaScript expression. If the binding refers to some invalid expression or reference, then KO will produce an error and stop processing the binding. Following are few examples of bindings. <!-- simple text binding --> <p>Enter employee name: <input -bind = 'value: empName' /></p> <!-- click binding, call a specific function --> <button data-bind="click: sortEmpArray">Sort Array</button> <!-- options binding --> <select multiple = "true" size = "8" data-bind = "options: empArray , selectedOptions: chosenItem"> </select> Note the following points − Whitespaces do not make any difference. Whitespaces do not make any difference. Starting from KO 3.0, you can skip the binding value which will give binding an undefined value. Starting from KO 3.0, you can skip the binding value which will give binding an undefined value. The data that is being used in current bindings can be referenced by an object. This object is called binding context. Context hierarchy is created and managed by KnockoutJS automatically. Following table lists the different types of binding contexts provided by KO. $root This always refers to top level ViewModel. This makes it possible to access top level methods for manipulating ViewModel. This is usually the object, which is passed to ko.applyBindings. $data This property is lot like this keyword in Javascript object. $data property in a binding context refers to ViewModel object for the current context. $index This property contains index of a current item of an array inside a foreach loop. The value of $index will change automatically as and when the underlying Observable array is updated. Obviously, this context is available only for foreach bindings. $parent This property refers to parent ViewModel object. This is useful when you want to access outer ViewModel properties from inside of a nested loop. $parentContext The context object which is bound at the parent level is called $parentContext. This is different from $parent. $parent refers to data. Whereas, $parentContext refers to binding context. E.g. you might need to access the index of outer foreach item from an inner context. $rawdata This context holds raw ViewModel value in the current situation. This resembles $data but the difference is, if ViewModel is wrapped in Observable, then $data becomes just unwrapped. ViewModel and $rawdata becomes actual Observable data. $component This context is used to refer to ViewModel of that component, when you are inside a particular component. E.g. you might want to access some property from ViewModel instead of current data in the template section of component. $componentTemplateNodes This represents an array of DOM nodes passed to that particular component when you are within a specific component template. Following terms are also available in binding but are not actually binding context. $context − This is nothing but existing binding context object. $context − This is nothing but existing binding context object. $element − This object refers to an element in DOM in the current binding. $element − This object refers to an element in DOM in the current binding. Following is a list of binding types provided by KO to deal with text and visual appearances. To show or hide HTML DOM element depending on certain conditions. To set the content of an HTML DOM element. To set the HTML markup contents of a DOM element. To apply CSS classes to an element. To define the inline style attribute of an element. To add attributes to an element dynamically. Following is a list of Control Flow Binding types provided by KO. In this binding, each array item is referenced in HTML markup in a loop. If the condition is true, then the given HTML markup will be processed. Else, it will be removed from DOM. Negation of If. If the condition is true, then the given HTML markup will be processed. Else, it will be removed from DOM. This binding is used to bind the child elements of an object in the specified object's context. This binding is used to insert a component into DOM elements and pass the parameters optionally. Following is the list of Form Fields Binding types provided by KO. This binding is used to invoke a JavaScript function associated with a DOM element based on a click. This binding is used to listen to the specified DOM events and call associated handler functions based on them. This binding is used to invoke a JavaScript function when the associated DOM element is submitted. This binding is used to enable certain DOM elements based on a specified condition. This binding disables the associated DOM element when the parameter evaluates to true. This binding is used to link respective DOM element's value into ViewModel property. This binding is used to create 2-way binding between text box or textarea and ViewModel property. This binding is used to manually set the focus of a HTML DOM element through a ViewModel property. This binding is used to create a link between a checkable form element and ViewModel property. This binding is used to define the options for a select element. This binding is used to work with elements which are selected currently in multi list select form control. This binding is used to generate a unique name for a DOM element. 38 Lectures 2 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 1933, "s": 1852, "text": "Declarative binding in KnockoutJS provides a powerful way to connect data to UI." }, { "code": null, "e": 2155, "s": 1933, "text": "It is important to understand the relationship between bindings and Observables. Technically, these two are different. You can use normal JavaScript object as ViewModel and KnockoutJS can process View's binding correctly." }, { "code": null, "e": 2394, "s": 2155, "text": "Without Observable, the property from the UI will be processed only for the first time. In this case, it cannot update automatically based on the underlying data update. To achieve this, bindings must be referred to Observable properties." }, { "code": null, "e": 2487, "s": 2394, "text": "The binding consists of 2 items, the binding name and value. Following is a simple example −" }, { "code": null, "e": 2541, "s": 2487, "text": "Today is : <span data-bind = \"text: whatDay\"></span>\n" }, { "code": null, "e": 2691, "s": 2541, "text": "Here, text is the binding name and whatDay is the binding value. You can have multiple bindings separated by comma, as shown in the following syntax." }, { "code": null, "e": 2772, "s": 2691, "text": "Your name: <input data-bind = \"value: yourName, valueUpdate: 'afterkeydown'\" />\n" }, { "code": null, "e": 2822, "s": 2772, "text": "Here, value is updated after each key is pressed." }, { "code": null, "e": 3044, "s": 2822, "text": "The binding value can be a single value, literal, a variable or can be a JavaScript expression. If the binding refers to some invalid expression or reference, then KO will produce an error and stop processing the binding." }, { "code": null, "e": 3084, "s": 3044, "text": "Following are few examples of bindings." }, { "code": null, "e": 3428, "s": 3084, "text": "<!-- simple text binding -->\n<p>Enter employee name: <input -bind = 'value: empName' /></p>\n\n<!-- click binding, call a specific function -->\n<button data-bind=\"click: sortEmpArray\">Sort Array</button>\n\n<!-- options binding -->\n<select multiple = \"true\" size = \"8\" data-bind = \"options: empArray , \n selectedOptions: chosenItem\"> </select>" }, { "code": null, "e": 3456, "s": 3428, "text": "Note the following points −" }, { "code": null, "e": 3496, "s": 3456, "text": "Whitespaces do not make any difference." }, { "code": null, "e": 3536, "s": 3496, "text": "Whitespaces do not make any difference." }, { "code": null, "e": 3633, "s": 3536, "text": "Starting from KO 3.0, you can skip the binding value which will give binding an undefined value." }, { "code": null, "e": 3730, "s": 3633, "text": "Starting from KO 3.0, you can skip the binding value which will give binding an undefined value." }, { "code": null, "e": 3849, "s": 3730, "text": "The data that is being used in current bindings can be referenced by an object. This object is called binding context." }, { "code": null, "e": 3998, "s": 3849, "text": "Context hierarchy is created and managed by KnockoutJS automatically. Following table lists the different types of binding contexts provided by KO. " }, { "code": null, "e": 4004, "s": 3998, "text": "$root" }, { "code": null, "e": 4191, "s": 4004, "text": "This always refers to top level ViewModel. This makes it possible to access top level methods for manipulating ViewModel. This is usually the object, which is passed to ko.applyBindings." }, { "code": null, "e": 4197, "s": 4191, "text": "$data" }, { "code": null, "e": 4346, "s": 4197, "text": "This property is lot like this keyword in Javascript object. $data property in a binding context refers to ViewModel object for the current context." }, { "code": null, "e": 4353, "s": 4346, "text": "$index" }, { "code": null, "e": 4601, "s": 4353, "text": "This property contains index of a current item of an array inside a foreach loop. The value of $index will change automatically as and when the underlying Observable array is updated. Obviously, this context is available only for foreach bindings." }, { "code": null, "e": 4609, "s": 4601, "text": "$parent" }, { "code": null, "e": 4754, "s": 4609, "text": "This property refers to parent ViewModel object. This is useful when you want to access outer ViewModel properties from inside of a nested loop." }, { "code": null, "e": 4769, "s": 4754, "text": "$parentContext" }, { "code": null, "e": 5041, "s": 4769, "text": "The context object which is bound at the parent level is called $parentContext. This is different from $parent. $parent refers to data. Whereas, $parentContext refers to binding context. E.g. you might need to access the index of outer foreach item from an inner context." }, { "code": null, "e": 5050, "s": 5041, "text": "$rawdata" }, { "code": null, "e": 5288, "s": 5050, "text": "This context holds raw ViewModel value in the current situation. This resembles $data but the difference is, if ViewModel is wrapped in Observable, then $data becomes just unwrapped. ViewModel and $rawdata becomes actual Observable data." }, { "code": null, "e": 5299, "s": 5288, "text": "$component" }, { "code": null, "e": 5526, "s": 5299, "text": "This context is used to refer to ViewModel of that component, when you are inside a particular component. E.g. you might want to access some property from ViewModel instead of current data in the template section of component." }, { "code": null, "e": 5550, "s": 5526, "text": "$componentTemplateNodes" }, { "code": null, "e": 5675, "s": 5550, "text": "This represents an array of DOM nodes passed to that particular component when you are within a specific component template." }, { "code": null, "e": 5759, "s": 5675, "text": "Following terms are also available in binding but are not actually binding context." }, { "code": null, "e": 5823, "s": 5759, "text": "$context − This is nothing but existing binding context object." }, { "code": null, "e": 5887, "s": 5823, "text": "$context − This is nothing but existing binding context object." }, { "code": null, "e": 5962, "s": 5887, "text": "$element − This object refers to an element in DOM in the current binding." }, { "code": null, "e": 6037, "s": 5962, "text": "$element − This object refers to an element in DOM in the current binding." }, { "code": null, "e": 6131, "s": 6037, "text": "Following is a list of binding types provided by KO to deal with text and visual appearances." }, { "code": null, "e": 6197, "s": 6131, "text": "To show or hide HTML DOM element depending on certain conditions." }, { "code": null, "e": 6240, "s": 6197, "text": "To set the content of an HTML DOM element." }, { "code": null, "e": 6290, "s": 6240, "text": "To set the HTML markup contents of a DOM element." }, { "code": null, "e": 6326, "s": 6290, "text": "To apply CSS classes to an element." }, { "code": null, "e": 6378, "s": 6326, "text": "To define the inline style attribute of an element." }, { "code": null, "e": 6423, "s": 6378, "text": "To add attributes to an element dynamically." }, { "code": null, "e": 6489, "s": 6423, "text": "Following is a list of Control Flow Binding types provided by KO." }, { "code": null, "e": 6562, "s": 6489, "text": "In this binding, each array item is referenced in HTML markup in a loop." }, { "code": null, "e": 6669, "s": 6562, "text": "If the condition is true, then the given HTML markup will be processed. Else, it will be removed from DOM." }, { "code": null, "e": 6792, "s": 6669, "text": "Negation of If. If the condition is true, then the given HTML markup will be processed. Else, it will be removed from DOM." }, { "code": null, "e": 6888, "s": 6792, "text": "This binding is used to bind the child elements of an object in the specified object's context." }, { "code": null, "e": 6985, "s": 6888, "text": "This binding is used to insert a component into DOM elements and pass the parameters optionally." }, { "code": null, "e": 7052, "s": 6985, "text": "Following is the list of Form Fields Binding types provided by KO." }, { "code": null, "e": 7153, "s": 7052, "text": "This binding is used to invoke a JavaScript function associated with a DOM element based on a click." }, { "code": null, "e": 7265, "s": 7153, "text": "This binding is used to listen to the specified DOM events and call associated handler functions based on them." }, { "code": null, "e": 7364, "s": 7265, "text": "This binding is used to invoke a JavaScript function when the associated DOM element is submitted." }, { "code": null, "e": 7448, "s": 7364, "text": "This binding is used to enable certain DOM elements based on a specified condition." }, { "code": null, "e": 7535, "s": 7448, "text": "This binding disables the associated DOM element when the parameter evaluates to true." }, { "code": null, "e": 7620, "s": 7535, "text": "This binding is used to link respective DOM element's value into ViewModel property." }, { "code": null, "e": 7718, "s": 7620, "text": "This binding is used to create 2-way binding between text box or textarea and ViewModel property." }, { "code": null, "e": 7817, "s": 7718, "text": "This binding is used to manually set the focus of a HTML DOM element through a ViewModel property." }, { "code": null, "e": 7912, "s": 7817, "text": "This binding is used to create a link between a checkable form element and ViewModel property." }, { "code": null, "e": 7977, "s": 7912, "text": "This binding is used to define the options for a select element." }, { "code": null, "e": 8084, "s": 7977, "text": "This binding is used to work with elements which are selected currently in multi list select form control." }, { "code": null, "e": 8150, "s": 8084, "text": "This binding is used to generate a unique name for a DOM element." }, { "code": null, "e": 8183, "s": 8150, "text": "\n 38 Lectures \n 2 hours \n" }, { "code": null, "e": 8203, "s": 8183, "text": " Skillbakerystudios" }, { "code": null, "e": 8210, "s": 8203, "text": " Print" }, { "code": null, "e": 8221, "s": 8210, "text": " Add Notes" } ]
Visualizing AI. Deconstructing and Optimizing the SHAP... | by Wai On | Towards Data Science
Now that you understand how the various components of the SHAP Summary Plot work together (part 1), I will provide an example of its use in explaining a black box Machine Learning model. In addition, I will discuss some of the problems with the visualization in the example before offering some ideas for improving it. The goal of these articles is to help the reader interpret the visualization, optimize it, and to arrive at a deeper understanding of the results. The code for this example can be found here on GitHub. The data I’m using is the HR data from IBM that is available at Kaggle. The original purpose of the data was to understand attrition, but here I’m using it to understand performance rating in the workplace. To reduce the amount of data-prep necessary, I’ve simplified the data by pairing down the number of features. In addition, an examination of the data shows that the performance ratings are restricted to either a 3 or a 4 (out of a scale of 1–4). So in order to use the data to illustrate the capabilities of the Summary Plot for regression data, I’ve re-scaled the rating to a real number between 0–9 by applying a set of transformations (see data file on GitHub). In the discussion of the results below, I will analyze this supposedly fictional data and hypothesize a possible story behind the data and the resulting model. For this exercise, I used the Random Forest algorithm from scikit-learn and used the SHAP Tree Explainer for explanation. model = RandomForestRegressor(max_depth=4, random_state=1, n_estimators=10)model.fit(X_train, y_train)shap_values = shap.TreeExplainer(model).shap_values(X_train) The following diagram shows the process of using SHAP in our example. The bar graph below shows the feature names and their corresponding mean SHAP value. A bar graph of this type is the typical presentation of results for feature attribution algorithms. Here, it lists the features in descending order of importance, according to the mean SHAP value. As shown above, the feature with the highest mean SHAP value is “PercentSalaryHike”. This value is so dominant that it makes it difficult to tell the relative difference of other top influencers. In fact, “PercentSalaryHike” is so dominant that it suggests that something might be problematic with the data or our interpretation of it. Let’s investigate further. The Summary Plot looks like this: The Summary Plot above shows that high values (red points) of “PercentSalaryHike” are associated with positive SHAP values and low values (blue points) of “PercentSalaryHike” are, in general, associated with negative SHAP values. Since the original data does not specify the timing of Salary Hike relative to Performance Rating, there are two interpretations of the result: High performance rating is the result of high salary hike from the previous salary review.High salary hike is the result of high performance rating. In other words, employees are rewarded for good work performance with a good salary hike. High performance rating is the result of high salary hike from the previous salary review. High salary hike is the result of high performance rating. In other words, employees are rewarded for good work performance with a good salary hike. In my view, the logical interpretation is probably #2. That is, employees received a high percentage increase in salary because they performed well. Of course, this is conjecture on my part but it serves as a good reminder that XAI tools reflect the nature of the underlying Machine Learning algorithms in general. Specifically, they operate in the realm of correlation and their results are ambiguous in terms of causal directions. The result, therefore, does not tell us that “PercentSalaryHike” is a cause of good work performance, it only tells us it is highly correlated. In this case, significantly more so than other features in the model. Of the top five features, “Age” also seems to follow a pattern where high values are associated with high SHAP values and low values are associated with low SHAP values. This pattern also seems to be applied to “StockOptionLevel” in the Summary Plot, albeit with less contrast. The SHAP values for the remaining features seem to cluster around zero but it’s hard to see the details because of scaling needed in the plot. That is, the visualization has to be compressed in order to accommodate the large values from the first feature. Clearly, although the Summary Plot is useful as it is, there are a number of problems that are preventing us from understanding the result more easily. In this section, I will discuss some of these and to offer suggestions for tackling them in SHAP. First and foremost is the use of the color red to indicate high values. Red is an intensely emotional color. It is typically used as a warning of danger and generally has a negative connotation in western cultures. The use of red in and off itself is not the problem. However, in our example, it is particularly problematic since we are dealing with monetary values, experience, and age, where a high value may not be a negative thing. Making sense of a plot in this type of situation is particularly difficult because of the cognitive interference due to interactions between color and feature value. The second issue is that the transition from blue to red may cause differentiation issues for some users due to color insensitivity. In particular, the use of blue and purple next to one another being a combination to avoid. The mistake that the Summary Plot designers made is similar to those that use the “rainbow color” scheme for data visualization (e.g. in “heat maps”). That is, the rainbow color palette looks attractive but is perceptually and semantically problematic. There have been discussions on providing custom color palettes for the ‘dot’ type (primarily as a way to deal with business requirements) but so far it’s still forthcoming. To address the issues discussed, I tweaked the source code and removed the use of red. I also chose a single color but varied the luminosity to make it easier to see the color difference. The new Summary Plot looks like this: I think the resulting plot is easier to parse at a glance since there are fewer colors to decipher. In addition, switching to a more luminous blue as an indication of high numbers make the higher values standout. However, this may be a problem for users who are accustomed to seeing blue as the low number. If this is the case, I would recommend flipping the two end colors. Following a well-known design strategy, I eliminated some of the information that was not useful. Since most of the values for the features are so close to each other and since most the SHAP values are close to zero, it makes sense for us to focus on the top set of features by setting the max_display parameter: shap.summary_plot(shap_values, X_train, max_display=5) As mentioned above, it’s unclear if “PercentSalaryHike” was a prior measure or a post measure of performance rating. If the employee received a high salary hike as a result of a good performance rating then this is less of an interest since we are interested in factors that contribute to good performance. Although it may also be interesting to see if a previous salary hike has any effect on performance rating, given it is unclear what the timing of salary increase is, it’s prudent to eliminate this altogether. The above comments on “PercentSalaryHike” ambiguity can also be applied to other features associated with monetary values. For the top 5, this includes “StockOptionLevel”. For our analysis, we can assume that others (e.g. distanceFromWork, Age) stay relatively similar whether they are post or pre-measure of work performance rating. Since “PercentSalaryHike” is so dominant, the scale for the x-axis has to extend to accommodate for the magnitude of the values. As a result, it is difficult to see how the SHAP values are distributed. Luckily, removing the features “PercentSalaryHike” and “StockOptionLevel” from the top five features automatically address this issue. The new summary plot for our model is as shown below with a better suited magnification. The resulting plot is simpler and easier to understand. The plot shows that higher values of total working years and age correlate with higher SHAP values (which in turn means higher performance ratings). In addition, low values also correlates with low SHAP values. This supports the thinking that maturity and work experience contribute to good work performance. The third feature is more difficult to interpret. Higher values of “DistanceFromHome” (that is, living further from a place of work) seem to correlate with high SHAP values. Without understanding work from home policies and how employees feel about working from home, it’s hard to interpret the result. In addition, the contrast between the color patches isn’t particularly clear since the plot shows some high values also negatively impact performance rating (light blue dots to the left). This result shows this is an area worth looking into and suggests further research from HR in the areas of commuting and the effects of work from home policies in general. Of course, this is fictitious data so any interpretation here is purely an exercise in demonstrating the potential analysis that could be done. In addition to the small size of the SHAP values and the small difference between them, the fact that the Summary Plot shows that most of the values tend to cluster around zero also reminds us that it’s best to interpret the results cautiously as well as the need to gather additional corroborative evidence. Although designing better XAI systems, in general, is beyond the scope of this article, I want to briefly discuss some tentative ideas for improvements that current tools can make immediately; particularly in the areas of User Experience and Data Visualizations design. Providing better contrast and color choice. Not only avoiding colors that might be confusing (e.g. using red to indicate a good outcome) but also providing choice in color palettes that are easily discernible and universal to all users. Be able to interactively remove specific features from visualizations. Research from Social Science suggests that “explanations are selected” in the sense that we pick one or two causes from a set of possible causes as being the explanation. For XAI tools to be used by end users, visualizations need to become more interactive. They need to allow users to easily select a set of features and focus on them without the need to explicitly do so programmatically. Support iterative exploration. A recent study has shown that much of the process of finding an explanation is iterative. Indeed, the process described above in localizing a handful of influential features follows the pattern of iterative analysis in finding an explanation. The ability to see results, explore different possibilities, contrast different features, examine their interaction, etc. and do this iteratively is immensely valuable for users at the receiving end of explanations. Support transition to and from a high level view to an individual view at the feature level. Following up on the earlier point, the ability to zoom in/out, transition from focusing on one feature or contrast a group of features would allow users to follow their investigation as well as deal with scaling issues that we encountered in our example. Without waiting for major research breakthroughs in XAI, I think there are some concrete improvements that can be made immediately so that they can be used to better explain the results of Machine Learning models. I hope to write more about this topic in the future. In this article, I used the SHAP Summary Plot to explain the influences behind a black box model’s output. Using the visualization, I hypothesized a possible story behind the data and the resulting model. As part of the process of telling a hypothetical story, I identified a number of ambiguities in the data as well as problems with the design of the SHAP Summary Plot. I then offered some ideas for improving the visualization as well as identifying further work needed to clarify the data. Finally, I provided some tentative ideas for XAI systems so that they can be tailored to the way users behave when seeking explanations. SHAP comes with a number of rich visualizations that deserve more attention than they are currently receiving. If you are a Data Scientist responsible for delivering systems or reports to end users, then hopefully this article has helped you to make the necessary adjustments to use the visualization more effectively. If you are an end user decision maker or end user consumer, you should now have a better understanding of the SHAP Summary Plot. This, in turn, will hopefully empower you to demand results to be presented in a way that is easier to understand.
[ { "code": null, "e": 638, "s": 172, "text": "Now that you understand how the various components of the SHAP Summary Plot work together (part 1), I will provide an example of its use in explaining a black box Machine Learning model. In addition, I will discuss some of the problems with the visualization in the example before offering some ideas for improving it. The goal of these articles is to help the reader interpret the visualization, optimize it, and to arrive at a deeper understanding of the results." }, { "code": null, "e": 693, "s": 638, "text": "The code for this example can be found here on GitHub." }, { "code": null, "e": 900, "s": 693, "text": "The data I’m using is the HR data from IBM that is available at Kaggle. The original purpose of the data was to understand attrition, but here I’m using it to understand performance rating in the workplace." }, { "code": null, "e": 1365, "s": 900, "text": "To reduce the amount of data-prep necessary, I’ve simplified the data by pairing down the number of features. In addition, an examination of the data shows that the performance ratings are restricted to either a 3 or a 4 (out of a scale of 1–4). So in order to use the data to illustrate the capabilities of the Summary Plot for regression data, I’ve re-scaled the rating to a real number between 0–9 by applying a set of transformations (see data file on GitHub)." }, { "code": null, "e": 1525, "s": 1365, "text": "In the discussion of the results below, I will analyze this supposedly fictional data and hypothesize a possible story behind the data and the resulting model." }, { "code": null, "e": 1647, "s": 1525, "text": "For this exercise, I used the Random Forest algorithm from scikit-learn and used the SHAP Tree Explainer for explanation." }, { "code": null, "e": 1824, "s": 1647, "text": "model = RandomForestRegressor(max_depth=4, random_state=1, n_estimators=10)model.fit(X_train, y_train)shap_values = shap.TreeExplainer(model).shap_values(X_train)" }, { "code": null, "e": 1894, "s": 1824, "text": "The following diagram shows the process of using SHAP in our example." }, { "code": null, "e": 1979, "s": 1894, "text": "The bar graph below shows the feature names and their corresponding mean SHAP value." }, { "code": null, "e": 2176, "s": 1979, "text": "A bar graph of this type is the typical presentation of results for feature attribution algorithms. Here, it lists the features in descending order of importance, according to the mean SHAP value." }, { "code": null, "e": 2512, "s": 2176, "text": "As shown above, the feature with the highest mean SHAP value is “PercentSalaryHike”. This value is so dominant that it makes it difficult to tell the relative difference of other top influencers. In fact, “PercentSalaryHike” is so dominant that it suggests that something might be problematic with the data or our interpretation of it." }, { "code": null, "e": 2573, "s": 2512, "text": "Let’s investigate further. The Summary Plot looks like this:" }, { "code": null, "e": 2803, "s": 2573, "text": "The Summary Plot above shows that high values (red points) of “PercentSalaryHike” are associated with positive SHAP values and low values (blue points) of “PercentSalaryHike” are, in general, associated with negative SHAP values." }, { "code": null, "e": 2947, "s": 2803, "text": "Since the original data does not specify the timing of Salary Hike relative to Performance Rating, there are two interpretations of the result:" }, { "code": null, "e": 3186, "s": 2947, "text": "High performance rating is the result of high salary hike from the previous salary review.High salary hike is the result of high performance rating. In other words, employees are rewarded for good work performance with a good salary hike." }, { "code": null, "e": 3277, "s": 3186, "text": "High performance rating is the result of high salary hike from the previous salary review." }, { "code": null, "e": 3426, "s": 3277, "text": "High salary hike is the result of high performance rating. In other words, employees are rewarded for good work performance with a good salary hike." }, { "code": null, "e": 4073, "s": 3426, "text": "In my view, the logical interpretation is probably #2. That is, employees received a high percentage increase in salary because they performed well. Of course, this is conjecture on my part but it serves as a good reminder that XAI tools reflect the nature of the underlying Machine Learning algorithms in general. Specifically, they operate in the realm of correlation and their results are ambiguous in terms of causal directions. The result, therefore, does not tell us that “PercentSalaryHike” is a cause of good work performance, it only tells us it is highly correlated. In this case, significantly more so than other features in the model." }, { "code": null, "e": 4351, "s": 4073, "text": "Of the top five features, “Age” also seems to follow a pattern where high values are associated with high SHAP values and low values are associated with low SHAP values. This pattern also seems to be applied to “StockOptionLevel” in the Summary Plot, albeit with less contrast." }, { "code": null, "e": 4607, "s": 4351, "text": "The SHAP values for the remaining features seem to cluster around zero but it’s hard to see the details because of scaling needed in the plot. That is, the visualization has to be compressed in order to accommodate the large values from the first feature." }, { "code": null, "e": 4857, "s": 4607, "text": "Clearly, although the Summary Plot is useful as it is, there are a number of problems that are preventing us from understanding the result more easily. In this section, I will discuss some of these and to offer suggestions for tackling them in SHAP." }, { "code": null, "e": 5459, "s": 4857, "text": "First and foremost is the use of the color red to indicate high values. Red is an intensely emotional color. It is typically used as a warning of danger and generally has a negative connotation in western cultures. The use of red in and off itself is not the problem. However, in our example, it is particularly problematic since we are dealing with monetary values, experience, and age, where a high value may not be a negative thing. Making sense of a plot in this type of situation is particularly difficult because of the cognitive interference due to interactions between color and feature value." }, { "code": null, "e": 5684, "s": 5459, "text": "The second issue is that the transition from blue to red may cause differentiation issues for some users due to color insensitivity. In particular, the use of blue and purple next to one another being a combination to avoid." }, { "code": null, "e": 5937, "s": 5684, "text": "The mistake that the Summary Plot designers made is similar to those that use the “rainbow color” scheme for data visualization (e.g. in “heat maps”). That is, the rainbow color palette looks attractive but is perceptually and semantically problematic." }, { "code": null, "e": 6298, "s": 5937, "text": "There have been discussions on providing custom color palettes for the ‘dot’ type (primarily as a way to deal with business requirements) but so far it’s still forthcoming. To address the issues discussed, I tweaked the source code and removed the use of red. I also chose a single color but varied the luminosity to make it easier to see the color difference." }, { "code": null, "e": 6336, "s": 6298, "text": "The new Summary Plot looks like this:" }, { "code": null, "e": 6711, "s": 6336, "text": "I think the resulting plot is easier to parse at a glance since there are fewer colors to decipher. In addition, switching to a more luminous blue as an indication of high numbers make the higher values standout. However, this may be a problem for users who are accustomed to seeing blue as the low number. If this is the case, I would recommend flipping the two end colors." }, { "code": null, "e": 7024, "s": 6711, "text": "Following a well-known design strategy, I eliminated some of the information that was not useful. Since most of the values for the features are so close to each other and since most the SHAP values are close to zero, it makes sense for us to focus on the top set of features by setting the max_display parameter:" }, { "code": null, "e": 7079, "s": 7024, "text": "shap.summary_plot(shap_values, X_train, max_display=5)" }, { "code": null, "e": 7595, "s": 7079, "text": "As mentioned above, it’s unclear if “PercentSalaryHike” was a prior measure or a post measure of performance rating. If the employee received a high salary hike as a result of a good performance rating then this is less of an interest since we are interested in factors that contribute to good performance. Although it may also be interesting to see if a previous salary hike has any effect on performance rating, given it is unclear what the timing of salary increase is, it’s prudent to eliminate this altogether." }, { "code": null, "e": 7929, "s": 7595, "text": "The above comments on “PercentSalaryHike” ambiguity can also be applied to other features associated with monetary values. For the top 5, this includes “StockOptionLevel”. For our analysis, we can assume that others (e.g. distanceFromWork, Age) stay relatively similar whether they are post or pre-measure of work performance rating." }, { "code": null, "e": 8131, "s": 7929, "text": "Since “PercentSalaryHike” is so dominant, the scale for the x-axis has to extend to accommodate for the magnitude of the values. As a result, it is difficult to see how the SHAP values are distributed." }, { "code": null, "e": 8355, "s": 8131, "text": "Luckily, removing the features “PercentSalaryHike” and “StockOptionLevel” from the top five features automatically address this issue. The new summary plot for our model is as shown below with a better suited magnification." }, { "code": null, "e": 8720, "s": 8355, "text": "The resulting plot is simpler and easier to understand. The plot shows that higher values of total working years and age correlate with higher SHAP values (which in turn means higher performance ratings). In addition, low values also correlates with low SHAP values. This supports the thinking that maturity and work experience contribute to good work performance." }, { "code": null, "e": 9383, "s": 8720, "text": "The third feature is more difficult to interpret. Higher values of “DistanceFromHome” (that is, living further from a place of work) seem to correlate with high SHAP values. Without understanding work from home policies and how employees feel about working from home, it’s hard to interpret the result. In addition, the contrast between the color patches isn’t particularly clear since the plot shows some high values also negatively impact performance rating (light blue dots to the left). This result shows this is an area worth looking into and suggests further research from HR in the areas of commuting and the effects of work from home policies in general." }, { "code": null, "e": 9836, "s": 9383, "text": "Of course, this is fictitious data so any interpretation here is purely an exercise in demonstrating the potential analysis that could be done. In addition to the small size of the SHAP values and the small difference between them, the fact that the Summary Plot shows that most of the values tend to cluster around zero also reminds us that it’s best to interpret the results cautiously as well as the need to gather additional corroborative evidence." }, { "code": null, "e": 10106, "s": 9836, "text": "Although designing better XAI systems, in general, is beyond the scope of this article, I want to briefly discuss some tentative ideas for improvements that current tools can make immediately; particularly in the areas of User Experience and Data Visualizations design." }, { "code": null, "e": 10343, "s": 10106, "text": "Providing better contrast and color choice. Not only avoiding colors that might be confusing (e.g. using red to indicate a good outcome) but also providing choice in color palettes that are easily discernible and universal to all users." }, { "code": null, "e": 10805, "s": 10343, "text": "Be able to interactively remove specific features from visualizations. Research from Social Science suggests that “explanations are selected” in the sense that we pick one or two causes from a set of possible causes as being the explanation. For XAI tools to be used by end users, visualizations need to become more interactive. They need to allow users to easily select a set of features and focus on them without the need to explicitly do so programmatically." }, { "code": null, "e": 11295, "s": 10805, "text": "Support iterative exploration. A recent study has shown that much of the process of finding an explanation is iterative. Indeed, the process described above in localizing a handful of influential features follows the pattern of iterative analysis in finding an explanation. The ability to see results, explore different possibilities, contrast different features, examine their interaction, etc. and do this iteratively is immensely valuable for users at the receiving end of explanations." }, { "code": null, "e": 11643, "s": 11295, "text": "Support transition to and from a high level view to an individual view at the feature level. Following up on the earlier point, the ability to zoom in/out, transition from focusing on one feature or contrast a group of features would allow users to follow their investigation as well as deal with scaling issues that we encountered in our example." }, { "code": null, "e": 11910, "s": 11643, "text": "Without waiting for major research breakthroughs in XAI, I think there are some concrete improvements that can be made immediately so that they can be used to better explain the results of Machine Learning models. I hope to write more about this topic in the future." }, { "code": null, "e": 12541, "s": 11910, "text": "In this article, I used the SHAP Summary Plot to explain the influences behind a black box model’s output. Using the visualization, I hypothesized a possible story behind the data and the resulting model. As part of the process of telling a hypothetical story, I identified a number of ambiguities in the data as well as problems with the design of the SHAP Summary Plot. I then offered some ideas for improving the visualization as well as identifying further work needed to clarify the data. Finally, I provided some tentative ideas for XAI systems so that they can be tailored to the way users behave when seeking explanations." } ]
Singleton Design Pattern | Introduction - GeeksforGeeks
01 Sep, 2021 Singleton is a part of Gang of Four design pattern and it is categorized under creational design patterns. In this article, we are going to take a deeper look into the usage of the Singleton pattern. It is one of the most simple design patterns in terms of the modelling but on the other hand, this is one of the most controversial patterns in terms of complexity of usage. Singleton pattern is a design pattern which restricts a class to instantiate its multiple objects. It is nothing but a way of defining a class. Class is defined in such a way that only one instance of the class is created in the complete execution of a program or project. It is used where only a single instance of a class is required to control the action throughout the execution. A singleton class shouldn’t have multiple instances in any case and at any cost. Singleton classes are used for logging, driver objects, caching and thread pool, database connections. Singleton Design Pattern Implementation of Singleton class An implementation of singleton class should have following properties: It should have only one instance : This is done by providing an instance of the class from within the class. Outer classes or subclasses should be prevented to create the instance. This is done by making the constructor private in java so that no class can access the constructor and hence cannot instantiate it.Instance should be globally accessible : Instance of singleton class should be globally accessible so that each class can use it. In Java, it is done by making the access-specifier of instance public. It should have only one instance : This is done by providing an instance of the class from within the class. Outer classes or subclasses should be prevented to create the instance. This is done by making the constructor private in java so that no class can access the constructor and hence cannot instantiate it. Instance should be globally accessible : Instance of singleton class should be globally accessible so that each class can use it. In Java, it is done by making the access-specifier of instance public. //A singleton class should have public visibility//so that complete application can usepublic class GFG { //static instance of class globally accessible public static GFG instance = new GFG(); private GFG() { // private constructor so that class //cannot be instantiated from outside //this class }} Detailed Article: Implementation of Singleton Design Pattern in Java Initialization Types of Singleton Singleton class can be instantiated by two methods:Early initialization : In this method, class is initialized whether it is to be used or not. The main advantage of this method is its simplicity. You initiate the class at the time of class loading. Its drawback is that class is always initialized whether it is being used or not.Lazy initialization : In this method, class in initialized only when it is required. It can save you from instantiating the class when you don’t need it. Generally, lazy initialization is used when we create a singleton class. Early initialization : In this method, class is initialized whether it is to be used or not. The main advantage of this method is its simplicity. You initiate the class at the time of class loading. Its drawback is that class is always initialized whether it is being used or not. Lazy initialization : In this method, class in initialized only when it is required. It can save you from instantiating the class when you don’t need it. Generally, lazy initialization is used when we create a singleton class. Examples of Singleton class java.lang.Runtime : Java provides a class Runtime in its lang package which is singleton in nature. Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime() method.An application cannot instantiate this class so multiple objects can’t be created for this class. Hence Runtime is a singleton class.java.awt.Desktop : The Desktop class allows a Java application to launch associated applications registered on the native desktop to handle a URI or a file.Supported operations include:launching the user-default browser to show a specified URI;launching the user-default mail client with an optional mailto URI;launching a registered application to open, edit or print a specified file.This class provides methods corresponding to these operations. The methods look for the associated application registered on the current platform, and launch it to handle a URI or file. If there is no associated application or the associated application fails to be launched, an exception is thrown.Each operation is an action type represented by the Desktop.Action class.This class also cannot be instantiated from application. Hence it is also a singleton class. java.lang.Runtime : Java provides a class Runtime in its lang package which is singleton in nature. Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime() method.An application cannot instantiate this class so multiple objects can’t be created for this class. Hence Runtime is a singleton class. java.awt.Desktop : The Desktop class allows a Java application to launch associated applications registered on the native desktop to handle a URI or a file.Supported operations include:launching the user-default browser to show a specified URI;launching the user-default mail client with an optional mailto URI;launching a registered application to open, edit or print a specified file.This class provides methods corresponding to these operations. The methods look for the associated application registered on the current platform, and launch it to handle a URI or file. If there is no associated application or the associated application fails to be launched, an exception is thrown.Each operation is an action type represented by the Desktop.Action class.This class also cannot be instantiated from application. Hence it is also a singleton class. launching the user-default browser to show a specified URI;launching the user-default mail client with an optional mailto URI; launching a registered application to open, edit or print a specified file. This class provides methods corresponding to these operations. The methods look for the associated application registered on the current platform, and launch it to handle a URI or file. If there is no associated application or the associated application fails to be launched, an exception is thrown. Each operation is an action type represented by the Desktop.Action class. This class also cannot be instantiated from application. Hence it is also a singleton class. Applications of Singleton classes There is a lot of applications of singleton pattern like cache-memory, database connection, drivers, logging. Some major of them are :- Hardware interface access: The use of singleton depends on the requirements. Singleton classes are also used to prevent concurrent access of class. Practically singleton can be used in case external hardware resource usage limitation required e.g. Hardware printers where the print spooler can be made a singleton to avoid multiple concurrent accesses and creating deadlock.Logger : Singleton classes are used in log file generations. Log files are created by the logger class object. Suppose an application where the logging utility has to produce one log file based on the messages received from the users. If there is multiple client application using this logging utility class they might create multiple instances of this class and it can potentially cause issues during concurrent access to the same logger file. We can use the logger utility class as a singleton and provide a global point of reference so that each user can use this utility and no 2 users access it at the same time.Configuration File: This is another potential candidate for Singleton pattern because this has a performance benefit as it prevents multiple users to repeatedly access and read the configuration file or properties file. It creates a single instance of the configuration file which can be accessed by multiple calls concurrently as it will provide static config data loaded into in-memory objects. The application only reads from the configuration file for the first time and thereafter from second call onwards the client applications read the data from in-memory objects.Cache: We can use the cache as a singleton object as it can have a global point of reference and for all future calls to the cache object the client application will use the in-memory object. Hardware interface access: The use of singleton depends on the requirements. Singleton classes are also used to prevent concurrent access of class. Practically singleton can be used in case external hardware resource usage limitation required e.g. Hardware printers where the print spooler can be made a singleton to avoid multiple concurrent accesses and creating deadlock. Logger : Singleton classes are used in log file generations. Log files are created by the logger class object. Suppose an application where the logging utility has to produce one log file based on the messages received from the users. If there is multiple client application using this logging utility class they might create multiple instances of this class and it can potentially cause issues during concurrent access to the same logger file. We can use the logger utility class as a singleton and provide a global point of reference so that each user can use this utility and no 2 users access it at the same time. Configuration File: This is another potential candidate for Singleton pattern because this has a performance benefit as it prevents multiple users to repeatedly access and read the configuration file or properties file. It creates a single instance of the configuration file which can be accessed by multiple calls concurrently as it will provide static config data loaded into in-memory objects. The application only reads from the configuration file for the first time and thereafter from second call onwards the client applications read the data from in-memory objects. Cache: We can use the cache as a singleton object as it can have a global point of reference and for all future calls to the cache object the client application will use the in-memory object. Important points Singleton classes can have only one instance and that instance should be globally accessible. java.lang.Runtime and java.awt.Desktop are 2 singleton classes provided by JVM. Singleton Design pattern is a type of creational design pattern. Outer classes should be prevented to create instance of singleton class. Further Read: Singleton Pattern in Python References:-https://en.wikipedia.org/wiki/Singleton_patternhttps://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.htmlhttps://docs.oracle.com/javase/7/docs/api/java/awt/Desktop.html This article is contributed by Vishal Garg. 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. Akanksha_Rai Design Pattern Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Factory method design pattern in Java Unified Modeling Language (UML) | An Introduction MVC Design Pattern Builder Design Pattern Unified Modeling Language (UML) | Activity Diagrams 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": 24460, "s": 24432, "text": "\n01 Sep, 2021" }, { "code": null, "e": 24834, "s": 24460, "text": "Singleton is a part of Gang of Four design pattern and it is categorized under creational design patterns. In this article, we are going to take a deeper look into the usage of the Singleton pattern. It is one of the most simple design patterns in terms of the modelling but on the other hand, this is one of the most controversial patterns in terms of complexity of usage." }, { "code": null, "e": 25402, "s": 24834, "text": "Singleton pattern is a design pattern which restricts a class to instantiate its multiple objects. It is nothing but a way of defining a class. Class is defined in such a way that only one instance of the class is created in the complete execution of a program or project. It is used where only a single instance of a class is required to control the action throughout the execution. A singleton class shouldn’t have multiple instances in any case and at any cost. Singleton classes are used for logging, driver objects, caching and thread pool, database connections." }, { "code": null, "e": 25427, "s": 25402, "text": "Singleton Design Pattern" }, { "code": null, "e": 25461, "s": 25427, "text": "Implementation of Singleton class" }, { "code": null, "e": 25532, "s": 25461, "text": "An implementation of singleton class should have following properties:" }, { "code": null, "e": 26045, "s": 25532, "text": "It should have only one instance : This is done by providing an instance of the class from within the class. Outer classes or subclasses should be prevented to create the instance. This is done by making the constructor private in java so that no class can access the constructor and hence cannot instantiate it.Instance should be globally accessible : Instance of singleton class should be globally accessible so that each class can use it. In Java, it is done by making the access-specifier of instance public." }, { "code": null, "e": 26358, "s": 26045, "text": "It should have only one instance : This is done by providing an instance of the class from within the class. Outer classes or subclasses should be prevented to create the instance. This is done by making the constructor private in java so that no class can access the constructor and hence cannot instantiate it." }, { "code": null, "e": 26559, "s": 26358, "text": "Instance should be globally accessible : Instance of singleton class should be globally accessible so that each class can use it. In Java, it is done by making the access-specifier of instance public." }, { "code": "//A singleton class should have public visibility//so that complete application can usepublic class GFG { //static instance of class globally accessible public static GFG instance = new GFG(); private GFG() { // private constructor so that class //cannot be instantiated from outside //this class }}", "e": 26876, "s": 26559, "text": null }, { "code": null, "e": 26945, "s": 26876, "text": "Detailed Article: Implementation of Singleton Design Pattern in Java" }, { "code": null, "e": 26979, "s": 26945, "text": "Initialization Types of Singleton" }, { "code": null, "e": 27537, "s": 26979, "text": "Singleton class can be instantiated by two methods:Early initialization : In this method, class is initialized whether it is to be used or not. The main advantage of this method is its simplicity. You initiate the class at the time of class loading. Its drawback is that class is always initialized whether it is being used or not.Lazy initialization : In this method, class in initialized only when it is required. It can save you from instantiating the class when you don’t need it. Generally, lazy initialization is used when we create a singleton class." }, { "code": null, "e": 27818, "s": 27537, "text": "Early initialization : In this method, class is initialized whether it is to be used or not. The main advantage of this method is its simplicity. You initiate the class at the time of class loading. Its drawback is that class is always initialized whether it is being used or not." }, { "code": null, "e": 28045, "s": 27818, "text": "Lazy initialization : In this method, class in initialized only when it is required. It can save you from instantiating the class when you don’t need it. Generally, lazy initialization is used when we create a singleton class." }, { "code": null, "e": 28073, "s": 28045, "text": "Examples of Singleton class" }, { "code": null, "e": 29383, "s": 28073, "text": "java.lang.Runtime : Java provides a class Runtime in its lang package which is singleton in nature. Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime() method.An application cannot instantiate this class so multiple objects can’t be created for this class. Hence Runtime is a singleton class.java.awt.Desktop : The Desktop class allows a Java application to launch associated applications registered on the native desktop to handle a URI or a file.Supported operations include:launching the user-default browser to show a specified URI;launching the user-default mail client with an optional mailto URI;launching a registered application to open, edit or print a specified file.This class provides methods corresponding to these operations. The methods look for the associated application registered on the current platform, and launch it to handle a URI or file. If there is no associated application or the associated application fails to be launched, an exception is thrown.Each operation is an action type represented by the Desktop.Action class.This class also cannot be instantiated from application. Hence it is also a singleton class." }, { "code": null, "e": 29843, "s": 29383, "text": "java.lang.Runtime : Java provides a class Runtime in its lang package which is singleton in nature. Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime() method.An application cannot instantiate this class so multiple objects can’t be created for this class. Hence Runtime is a singleton class." }, { "code": null, "e": 30694, "s": 29843, "text": "java.awt.Desktop : The Desktop class allows a Java application to launch associated applications registered on the native desktop to handle a URI or a file.Supported operations include:launching the user-default browser to show a specified URI;launching the user-default mail client with an optional mailto URI;launching a registered application to open, edit or print a specified file.This class provides methods corresponding to these operations. The methods look for the associated application registered on the current platform, and launch it to handle a URI or file. If there is no associated application or the associated application fails to be launched, an exception is thrown.Each operation is an action type represented by the Desktop.Action class.This class also cannot be instantiated from application. Hence it is also a singleton class." }, { "code": null, "e": 30821, "s": 30694, "text": "launching the user-default browser to show a specified URI;launching the user-default mail client with an optional mailto URI;" }, { "code": null, "e": 30897, "s": 30821, "text": "launching a registered application to open, edit or print a specified file." }, { "code": null, "e": 31197, "s": 30897, "text": "This class provides methods corresponding to these operations. The methods look for the associated application registered on the current platform, and launch it to handle a URI or file. If there is no associated application or the associated application fails to be launched, an exception is thrown." }, { "code": null, "e": 31271, "s": 31197, "text": "Each operation is an action type represented by the Desktop.Action class." }, { "code": null, "e": 31364, "s": 31271, "text": "This class also cannot be instantiated from application. Hence it is also a singleton class." }, { "code": null, "e": 31398, "s": 31364, "text": "Applications of Singleton classes" }, { "code": null, "e": 31534, "s": 31398, "text": "There is a lot of applications of singleton pattern like cache-memory, database connection, drivers, logging. Some major of them are :-" }, { "code": null, "e": 33289, "s": 31534, "text": "Hardware interface access: The use of singleton depends on the requirements. Singleton classes are also used to prevent concurrent access of class. Practically singleton can be used in case external hardware resource usage limitation required e.g. Hardware printers where the print spooler can be made a singleton to avoid multiple concurrent accesses and creating deadlock.Logger : Singleton classes are used in log file generations. Log files are created by the logger class object. Suppose an application where the logging utility has to produce one log file based on the messages received from the users. If there is multiple client application using this logging utility class they might create multiple instances of this class and it can potentially cause issues during concurrent access to the same logger file. We can use the logger utility class as a singleton and provide a global point of reference so that each user can use this utility and no 2 users access it at the same time.Configuration File: This is another potential candidate for Singleton pattern because this has a performance benefit as it prevents multiple users to repeatedly access and read the configuration file or properties file. It creates a single instance of the configuration file which can be accessed by multiple calls concurrently as it will provide static config data loaded into in-memory objects. The application only reads from the configuration file for the first time and thereafter from second call onwards the client applications read the data from in-memory objects.Cache: We can use the cache as a singleton object as it can have a global point of reference and for all future calls to the cache object the client application will use the in-memory object." }, { "code": null, "e": 33664, "s": 33289, "text": "Hardware interface access: The use of singleton depends on the requirements. Singleton classes are also used to prevent concurrent access of class. Practically singleton can be used in case external hardware resource usage limitation required e.g. Hardware printers where the print spooler can be made a singleton to avoid multiple concurrent accesses and creating deadlock." }, { "code": null, "e": 34282, "s": 33664, "text": "Logger : Singleton classes are used in log file generations. Log files are created by the logger class object. Suppose an application where the logging utility has to produce one log file based on the messages received from the users. If there is multiple client application using this logging utility class they might create multiple instances of this class and it can potentially cause issues during concurrent access to the same logger file. We can use the logger utility class as a singleton and provide a global point of reference so that each user can use this utility and no 2 users access it at the same time." }, { "code": null, "e": 34855, "s": 34282, "text": "Configuration File: This is another potential candidate for Singleton pattern because this has a performance benefit as it prevents multiple users to repeatedly access and read the configuration file or properties file. It creates a single instance of the configuration file which can be accessed by multiple calls concurrently as it will provide static config data loaded into in-memory objects. The application only reads from the configuration file for the first time and thereafter from second call onwards the client applications read the data from in-memory objects." }, { "code": null, "e": 35047, "s": 34855, "text": "Cache: We can use the cache as a singleton object as it can have a global point of reference and for all future calls to the cache object the client application will use the in-memory object." }, { "code": null, "e": 35064, "s": 35047, "text": "Important points" }, { "code": null, "e": 35158, "s": 35064, "text": "Singleton classes can have only one instance and that instance should be globally accessible." }, { "code": null, "e": 35238, "s": 35158, "text": "java.lang.Runtime and java.awt.Desktop are 2 singleton classes provided by JVM." }, { "code": null, "e": 35303, "s": 35238, "text": "Singleton Design pattern is a type of creational design pattern." }, { "code": null, "e": 35376, "s": 35303, "text": "Outer classes should be prevented to create instance of singleton class." }, { "code": null, "e": 35418, "s": 35376, "text": "Further Read: Singleton Pattern in Python" }, { "code": null, "e": 35605, "s": 35418, "text": "References:-https://en.wikipedia.org/wiki/Singleton_patternhttps://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.htmlhttps://docs.oracle.com/javase/7/docs/api/java/awt/Desktop.html" }, { "code": null, "e": 35900, "s": 35605, "text": "This article is contributed by Vishal Garg. 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": 36025, "s": 35900, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 36038, "s": 36025, "text": "Akanksha_Rai" }, { "code": null, "e": 36053, "s": 36038, "text": "Design Pattern" }, { "code": null, "e": 36058, "s": 36053, "text": "Java" }, { "code": null, "e": 36063, "s": 36058, "text": "Java" }, { "code": null, "e": 36161, "s": 36063, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36170, "s": 36161, "text": "Comments" }, { "code": null, "e": 36183, "s": 36170, "text": "Old Comments" }, { "code": null, "e": 36221, "s": 36183, "text": "Factory method design pattern in Java" }, { "code": null, "e": 36271, "s": 36221, "text": "Unified Modeling Language (UML) | An Introduction" }, { "code": null, "e": 36290, "s": 36271, "text": "MVC Design Pattern" }, { "code": null, "e": 36313, "s": 36290, "text": "Builder Design Pattern" }, { "code": null, "e": 36365, "s": 36313, "text": "Unified Modeling Language (UML) | Activity Diagrams" }, { "code": null, "e": 36380, "s": 36365, "text": "Arrays in Java" }, { "code": null, "e": 36424, "s": 36380, "text": "Split() String method in Java with examples" }, { "code": null, "e": 36446, "s": 36424, "text": "For-each loop in Java" }, { "code": null, "e": 36482, "s": 36446, "text": "Arrays.sort() in Java with examples" } ]
DateSerial() and DateValue() Function in MS Access - GeeksforGeeks
25 Sep, 2020 In this article, we are going to cover DateSerial() and DateValue() Function in MS Access with examples and will cover DateSerial and DateValue query with output. DateSerial() Function :The format of the DateSerial functions contains three parts year, month, and day values. And it returns date in a specified format. There are three parameters first one is year second one is month and the third one is the day. Syntax : DateSerial(year, month, day) Parameter Values : Example-1 : SELECT DateSerial(2020-10, 10-1, 20-5); Output : 9/15/2010 Example-2 : SELECT DateSerial(2020, 4, 20); Output : 4/20/2020 DateValue() Function :In MS Access, DateValue() function returns a date based on a string.In this function, a string that contains day, month, and year will be passed and it will return the date based on the string. Note :If the year part of the string is not given then it will take the current year. Syntax : DateValue(string_date) Parameter Values : Example-1 : SELECT DateValue("May 12, 2010"); Output : 5/12/2010 Example-2 : SELECT DateValue("July 10"); Output : 7/10/2020 DBMS-SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Alter Multiple Columns at Once in SQL Server? How to Update Multiple Columns in Single Update Statement in SQL? What is Temporary Table in SQL? SQL using Python SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL | Subquery SQL | Date functions SQL Query for Matching Multiple Values in the Same Column SQL Query to Convert VARCHAR to INT SQL | DROP, TRUNCATE
[ { "code": null, "e": 24268, "s": 24240, "text": "\n25 Sep, 2020" }, { "code": null, "e": 24431, "s": 24268, "text": "In this article, we are going to cover DateSerial() and DateValue() Function in MS Access with examples and will cover DateSerial and DateValue query with output." }, { "code": null, "e": 24681, "s": 24431, "text": "DateSerial() Function :The format of the DateSerial functions contains three parts year, month, and day values. And it returns date in a specified format. There are three parameters first one is year second one is month and the third one is the day." }, { "code": null, "e": 24690, "s": 24681, "text": "Syntax :" }, { "code": null, "e": 24720, "s": 24690, "text": "DateSerial(year, month, day)\n" }, { "code": null, "e": 24739, "s": 24720, "text": "Parameter Values :" }, { "code": null, "e": 24751, "s": 24739, "text": "Example-1 :" }, { "code": null, "e": 24792, "s": 24751, "text": "SELECT DateSerial(2020-10, 10-1, 20-5);\n" }, { "code": null, "e": 24801, "s": 24792, "text": "Output :" }, { "code": null, "e": 24813, "s": 24801, "text": "9/15/2010 \n" }, { "code": null, "e": 24825, "s": 24813, "text": "Example-2 :" }, { "code": null, "e": 24858, "s": 24825, "text": "SELECT DateSerial(2020, 4, 20);\n" }, { "code": null, "e": 24867, "s": 24858, "text": "Output :" }, { "code": null, "e": 24879, "s": 24867, "text": "4/20/2020 \n" }, { "code": null, "e": 25095, "s": 24879, "text": "DateValue() Function :In MS Access, DateValue() function returns a date based on a string.In this function, a string that contains day, month, and year will be passed and it will return the date based on the string." }, { "code": null, "e": 25181, "s": 25095, "text": "Note :If the year part of the string is not given then it will take the current year." }, { "code": null, "e": 25190, "s": 25181, "text": "Syntax :" }, { "code": null, "e": 25214, "s": 25190, "text": "DateValue(string_date)\n" }, { "code": null, "e": 25233, "s": 25214, "text": "Parameter Values :" }, { "code": null, "e": 25245, "s": 25233, "text": "Example-1 :" }, { "code": null, "e": 25280, "s": 25245, "text": "SELECT DateValue(\"May 12, 2010\");\n" }, { "code": null, "e": 25289, "s": 25280, "text": "Output :" }, { "code": null, "e": 25300, "s": 25289, "text": "5/12/2010\n" }, { "code": null, "e": 25312, "s": 25300, "text": "Example-2 :" }, { "code": null, "e": 25342, "s": 25312, "text": "SELECT DateValue(\"July 10\");\n" }, { "code": null, "e": 25351, "s": 25342, "text": "Output :" }, { "code": null, "e": 25363, "s": 25351, "text": "7/10/2020 \n" }, { "code": null, "e": 25372, "s": 25363, "text": "DBMS-SQL" }, { "code": null, "e": 25376, "s": 25372, "text": "SQL" }, { "code": null, "e": 25380, "s": 25376, "text": "SQL" }, { "code": null, "e": 25478, "s": 25380, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25487, "s": 25478, "text": "Comments" }, { "code": null, "e": 25500, "s": 25487, "text": "Old Comments" }, { "code": null, "e": 25553, "s": 25500, "text": "How to Alter Multiple Columns at Once in SQL Server?" }, { "code": null, "e": 25619, "s": 25553, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 25651, "s": 25619, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 25668, "s": 25651, "text": "SQL using Python" }, { "code": null, "e": 25746, "s": 25668, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 25761, "s": 25746, "text": "SQL | Subquery" }, { "code": null, "e": 25782, "s": 25761, "text": "SQL | Date functions" }, { "code": null, "e": 25840, "s": 25782, "text": "SQL Query for Matching Multiple Values in the Same Column" }, { "code": null, "e": 25876, "s": 25840, "text": "SQL Query to Convert VARCHAR to INT" } ]
How to make multi-index index charts with Plotly | by Nikita Khutorni | Towards Data Science
When working with time series data, raw numbers often provide little insight. If you have multiple variables that vary in magnitude, changes in smaller values are hard to see. There is a simple solution to this problem: Using index charts that index the data. While regular index charts work fine, by using a simple extension to indexing you can significantly improve your visual presentation and help your charts communicate causalities in the data. This extension is what I refer to as “multi-indexing” — using multiple indices instead of one. That allows you to analyze data from different vantage points. It is especially useful when you suspect that there were events at specific points in time that had a significant influence on the growth of variables in question. As an example, if you were to compare stock prices for some stocks from 1980 to today, you would find that the Black Monday in 1987, the Dot-com bubble in 2000, and the stock market crash in 2008 were all events that influenced the market heavily and would be interesting to look at. So, you would add them to the indices list, reference data to each of these dates and compare how the prices developed with respect to each reference point. Looking at the prices this way would give you a better intuition of the magnitude of each event compared to just a single index date. In this article I will teach you how you can implement multi-indexing in time-series plots using the Python Plotly data visualization library. I will present three approaches with complete code and explain them in detail, including the advantages and disadvantages of each approach and when to use which. To keep up with the article, you should be familiar with Python and Pandas and preferably have had some exposure to Plotly. If you care about only one of the three charts I will talk about, feel free to skip the others — the article is written in a modular way, so you won’t miss anything. However make sure to thoroughly read part 1 (Setup and Preparation), because it contains important concepts and function definitions that will be used in every chart. [You can find the entire Jupyter Notebook of this post here.] Setup and preparationIndex chart with fixed reference dates Setup and preparation Index chart with fixed reference dates 3. Dynamic index chart 4. Index chart with variable index in JupyterLab As already mentioned, data preparation tasks will be done with Pandas. Most of the plotting will be handled by the Plotly graph_objects module. Additionaly for one plot we will use the ipywidgets library, which provides widgets for interacting with plots in Jupyter Notebook and JupyterLab. For the time series data we are going to use historic stock market data from Yahoo!Finance API. There is a great Python library called yfinance which we will use to interface with the API. Our goal is to build index charts that will enable the user to compare the development of selected stocks relative to a selected date on the first glance. So, let’s pick some stocks to compare. We will be featuring Facebook (FB), Amazon (AMZN), DowDupont (DD) and also Berkshire Hathaway class A shares (BRK-A) which is the highest-ever priced share for a stock. I purposefully chose stocks from a very broad price range, to demonstrate the effectiveness of indexing. The call to yf.download() downloads data for the given time period in given intervals, in our case starting from today and dating 3 years back, once per week. The result is stored in a multi-indexed Pandas dataframe. Setting group_by='column' specifies how the data will be grouped, either by price type (column) or tickers (ticker). This translates to whether price types or tickers will be the top-level index of our dataframe. The table contains five different prices. To simplify things, we will only look at the adjusted closing price and drop everything else. We’ll remove empty values as well. df = df.filter(regex="Adj Close")df = df.dropna()df.head(5) Now that our data is ready, let’s take a first glance at the values. df.plot() Plotting raw values helps little in comparing the stocks. Due to by magnitudes higher prices of BRK-A shares, changes in all other stocks are practically invisible. Maybe scaling the data logarithmically will alleviate the problem? df.plot(logy=True) Even at logarithmic scale the discrepancy in values is too big for us to meaningfully compare the stocks. It is evident that we need indexing. Indexing is simple: Pick a date D, the index, and divide the price at every date by the value at date D. Now, all resulting values are represented as their ratio to the value V at D and can be easily compared to each other. In our case, we need to distinguish between different stocks, so for every stock we divide all values by the value at date D for the respective stock. We can do this easily in Pandas, as we have a multi-indexed dataframe. Calling iloc on a specific index returns a Pandas series containing the values of all stocks for the specific index. When we divide the dataframe by a series, Pandas divides every column by the corresponding element in the series. We will also add some cosmetics. Multiplying the new values by 100 will give us percentage values, that are more comfortable to work with. The second optional cosmetic is subtracting 100 from the result. This effectively sets 100% to 0% and changes ratio to relative difference. As an example, a drop to 30% of the original value will now be interpreted as original value — 70 %. Personally, I think that this interpretation is easier to comprehend. Note that I will refer to the index date as reference date and index value as reference value. This is done to avoid confusion with the dataframe index. # use the first date as index reference_value = df.iloc[0]# dividing by the series divides each column by the # corresponding element in the seriestmp_df = df.div(reference_value) * 100 - 100tmp_df.plot()prepared_df = df.copy() This looks much better. The stock price trends are immediately visible and comparable. We are going to use indexing many more times, so let’s write a generalized function create_indexed_columns() for this technique. The function will take the following parameters: date - the reference date that is the indexdf - the dataframe to work ontop_level_name - (optional) name for the top level index of the normalized dataframe date - the reference date that is the index df - the dataframe to work on top_level_name - (optional) name for the top level index of the normalized dataframe and return a new dataframe with normalized data and a new top level index. One important consideration is how to handle an input date that is not in the dataframe. Luckily, dataframe indices have a very useful method get_loc() that will find the integer index of given index. When we pass the method=nearest parameter to the method, Pandas will search for the closest index to the provided input. As our index is of type datetime, the date that is closest to the provided date will be matched. Before we move on to the first Plotly index chart, let’s recap the concept of “multi-index” charts. As we have seen, indexing data to one point in time is very effective. However, often it is useful to look at multiple reference points. These might be specific events in the time series that had a big influence on our data. Looking at the data from multiple points gives the user the ability to easily see how the variable in question has grown relative to different reference points. The best way to accomplish this is to embed this functionality directly into the chart. This quick introduction only briefly touches on the basic concepts of Plotly. Skip it if you have worked with Plotly before. Having multiple indices in a plot implies that they need to be switchable on the fly, therefore our plot has to be interactive. Plotly is interactive out of the box and extending interactability is relatively simple, which is why Plotly is the library of choice. In Plotly, every figure is a JSON-like data structure with three main properties (called attributes): data, layout and frames. The first two are self-explanatory while the frames attribute contains optional frames that are used in animations. You can either first write the entire figure structure using JSON or Python dictionaries and then instantiate the figure object, or create the figure object first and update figure attributes incrementally. As a warm up, let’s recreate the default matplotlib chart that we generated by calling df.plot() in Plotly. In the above example we instantiate the Figure object and then add individual traces to said object one by one. We can call update_layout() with a dictionary of updated attributes to change the layout of the figure. All changes to a Plotly figure are done this way, passing a dictionary of attributes to the figure. Plotly supports “magic underscore notation” which means that we don’t need to stepwise deepen into the object to access inner attributes but rather are able to access inner attributes directly. For example, we can simply write fig.update_layout(yaxis_type='log') instead of accessing the type attribute of the yaxis attribute - in many cases a more readable approach. Now that we are all set, we can get on to our first chart. For this chart, we are going to use preselected dates around the time of stock market recessions and dates that had an impact on the companies we are analyzing. The dates listed below may not be entirely accurate, but they lay approximately in the timerange of the listed events. ref_dict = { "Cambridge Analytica scandal": "2018-03-28", "DowDuPont separation": "2019-04-15", "Corona stock market drop": "2020-02-14"} We will index our data with respect to each of these dates and include all differently indexed data in our chart. Switching between the different indexed data will be accomplished by using a dropdown menu with an item for every reference date. Plotly refers to this as “buttons”. Clicking a button will display only the data indexed by the respective reference date. To achieve this, we need to switch the visibility of the traces we want to show to on, and switch it off for the remanining traces. First, let’s calculate values for each reference date and populate our dataframe with the resulting data. We will create a new dataframe for each reference date and then join them into one dataframe. We will also store the closest date to the given reference date, in case that we don’t have values for that reference date. Now that our table is transformed we can build our Plotly object. We will create a new figure and add a trace for each newly computed column. We are going to provide an additional meta attribute to every trace. The meta attribute can store arbitrary JSON data and has many applications. We will use it to store the reference date that a trace belongs to. This will allow us to identify a group of traces that will be switched to visible/invisible at the same time. That’s a lot of traces! We want to show only those that belong to one reference date. Just like before, we won’t hardcode the buttons for our exact data. It is better to generalize our procedure so that we’ll be able to handle a different set of reference dates and tickers. To show or hide traces, we will need to set the visibility attribute of our figure. Because this is an attribute of the figure and not an individual trace, by default changes to this attribute apply to all traces. Internally, visibility is represented as an array of boolean values, where the value at a specific index represents the visibility of the trace with the same index. The trace index is the position of a trace within that array and because traces are added one by one, trace index represents the order in which the traces were added to the figure. The visibility array allows us to target individual traces, either by passing the index of a specific trace or passing an array of boolean values where the value at each index indicates whether the corresponding trace will be shown. For example, with 4 traces, passing the array [True, False, True, False] will display only the first and third trace. As you can imagine, relying on the order in which the traces were added to create permanent buttons is a brittle approach. If you add traces in a different order or add more traces, every mention of the visibility array would have to be checked and updated manually. This is why we added the meta attribute - this way, we don't need to rely on the order of the traces to identify which traces to switch on/off. A simple function create_visibility_array will create the visibility array by comparing the meta value of every trace to the passed in value. Finally, we will write a function for generating buttons. Let’s clarify the button description. method specifies the Plotly method that the button calls on clicking. restyle updates the data and the layout of the plot. The args argument takes a list of chart attributes that will be updated by clicking the button, in our case the visibility attribute. Lastly we will add the buttons to the figure and inspect the result. Great, the buttons work as expected. The only problem is that it is somewhat hard to see the actual reference date. We can solve this by adding a vertical line at the x-coordinate of every reference date. Naturally, we’ll need to be able to toggle the visibility of these reference lines with our existing buttons. There are two ways to do this in Plotly: The standard way is by adding a shape object to the figure. In our case we would simply add a line shape by calling figure.add_shape() and specifying the x and y coordinates. While this approach may seem straightforward, there are some difficulties specific to our case. Because shapes aren't traces, we can't change their visibility with our existing method. Rather, the visibility attribute of an individual shape object has to be set, doing which is somewhat obscure (this Stack Overflow question illustrates the process). Furthermore, there seems to be no concise way, similar to the trace visibility array, to change the visibility of multiple shapes at once. The second way to add reference lines is by adding a trace that will be drawn as a vertical line. To do this, two y-coordinates must be chosen that will set the boundaries of the line. However, we need to ensure that the line covers the entire plot heightwise and in addition to that, the reference line must not affect the scaling of the plot — this means that we can’t simply choose some value below and above the minimum and respectively maximum values in our dataframe as boundaries, as this would skew the scale of the remaining values. The solution is to add a secondary, invisible y-axis to the plot that will be independent of the values in the dataframe and scale the reference lines with respect to itself. Although the secondary y-axis somewhat increases the complexity of our figure, using traces as reference lines provides a significant benefit: We can toggle the visibility of the reference lines the same way as we do with all other traces. Thus, we only need to add the reference line trace and set its meta parameter to the reference date it refers to. As you can see, the second approach is a better fit for our situation, which is why we will utilize it. Before we add the reference lines, let’s first add the secondary y-axis to the plot. While we are at it, we might as well add some simple styling to the plot. The hovermode attribute specifies how the hoverlabels will be displayed in our plot. Setting this value to 'x' will display the values of every trace at the x-value the mouse is hovering over. We set the secondary y-axis to a fixed range. This way, the line will always extend throughout the entire height of the plot. Setting the overlaying attribute to 'y' is very important, as this will force the traces that are defined with respect to the secondary y-axis to behave as if they were defined on the first y-axis - concretely, the combination of this attribute and fixedrange is exactly what allows us to see the reference lines yet makes their scale independent of the y-axis. Now that the figure is prepared, we can write a create_reference_line() function that will generate the reference lines for us. One important thing to note is that as we specify two values for y-coordinates, symmetrically, we need to provide a list with two x-values as well. The only additions to our previous scatter trace definitions are: mode="lines" - specifies that the traces should be drawn as lines only, without marking the points in between yaxis="y2" - specifies that the secondary y-axis is to be used as the y-axis line - determines the styling of the line Finally, the last step consists of adding the reference line traces to the plot and regenerating the visibility buttons. Done! The second chart we will look at is a dynamic index chart. This chart allows the user to quickly move between reference dates, creating a visually appealing chart. Because we are using only the Plotly graphing library, the best approach here is to create a frame for each reference date and then use a Plotly slider to move between them. By using a slider we can also add an animation effect for transitioning between reference dates, which will make the transitions much smoother. First off we need to index the data to every date and create traces for it. The resulting data will be stored in a frame which is simply a figure['data'] dictionary that with an identifying name. We will create the traces like in the previous example using the create_indexed_columns and create_reference_line functions. A frame will be identified by the date that the data in the frame is indexed to. The function create_traces_for_date will bundle this functionality. Next, we will create a slider dictionary that will define our slider. Some important attributes that we use are: yanchor and xanchor - specify where the slider will be positioned pad - padding for the slider currentvalue - describes how the current value of the slider will be displayed including position, font size and a prefix. len - describes the length of the slider relative to the chart. 1 indicates that it matches the length exactly, which is what we want. steps - is a list of steps that the slider will cycle through. We will leave it empty at first and add to it later. The next thing to do is to create steps that we will add to our slider. A step is described by the attributes label, method and args. method specifies which Plotly function will be called when the slider value changes. By using animate we will get a smooth transition between frames. The args attribute describes the data that will be passed to the Plotly function specifed in method, consisting of a list of frames and a dictionary specifying how to transition between them. You can actually specify multiple frames for each slider step that will all be cycled through when the slider is moved to that step. In our case, we only want one frame and identify it by its name. After that we describe the transitioning properties: frame - duration specifies the total time the frame will be displayed, redraw whether the chart should be redrawn after each step. mode - specifies how a new call to the animate function interacts with current animations. Setting it to "next" means that the current running frame will be finished before switching to the next one. transition - specifies the duration of the transitioning part of the total frame duration and the easing function that is used. There are a few important details to note here. First, setting redraw=False provides significant performance benefits in our case, as we have hundreds of frames, each with hundreds of points. Without that setting, the chart updates visibly lag behind, as you will see soon. However, there are some drawbacks to disabling redraw: For example, a rangeslider which allows you to set the view range will not be updated if redraw is deactivated. Another important drawback is that the range of the y-axis will not be automatically updated, which sometimes may not show all points on the chart. In the third part of this article we will see how to combine the best of both implementations, that is, fast updates and redrawing of the chart, at the cost of some dynamicity and requiring a Jupyter notebook. There is also a way to have it all (for a reasonable amount of data points) without compromising, but this solution requires the Dash server which is beyond the scope of this article. The other thing to remember is that the transition duration time is a part of the frame duration time, so setting it larger than the frame duration won’t change the total duration. Furthermore, Plotly will animate transitions between multiple frames during a slider step and the transition between frames of two neighbouring slider steps. Now, with all functions set, we can actually create frames and steps and populate our figure. For every date, we will create a frame with traces indexed to that date and a slider step for that frame. Note that we set the name of a frame to a iso-formatted string of the date it represents and immediately pass that string to our create_slider_step function. This is done because the slider uses the frame name to determine which frame to display. Lastly, we build our figure. We simply use the first frame as the data attribute of our figure. We use the style_plot function to configure the secondary y-axis, and we are finished! I have warned you about enabling redraw, but let's actually see it in action. We will create the exact same index chart as before, but this time with redraw set to true. As you see, the chart is significantly slower than before. Personally, I find this amount of lag barely acceptable; however this is the limit: if you increase the amount of data points to above 5000, the chart will be to slow for anyone to enjoy using it. To keep the speed acceptable, you need to keep the amount of data points below this number. The third chart will allow a user to select a custom reference date. If you plan on presenting your work in a JupyterLab, don’t need fancy animations like in the dynamic index chart, yet still want to enbale the user to pick any date as the reference date, this chart is right for you. Note that this chart will work only in JupyterLab and not in Jupyter Notebooks! The chart will be implemented with the ipywidgets library that uses widgets. According to the official docs, widgets are eventful Python objects that have a representation in the browser, often as a controller like a slider, textbox, etc. [..] You can use widgets to build interactive GUIs for your notebooks. You can also use widgets to synchronize stateful and stateless information between Python and JavaScript. (Source) The idea is to use widgets to provide input for our chart via GUI and to update the chart. This way, after a different reference date was selected, the chart data will be updated through a Jupyter callback and not a Plotly event. We will build two version of the chart, using two different widgets. One will be a DatePicker widget and the second will be a SelectionSlider widget. The second version will be a robust implementation of the dynamic index chart from part 2. First off we copy our initial dataframe and import additional libraries. Ipython.display is used to render the widgets in the browser. from IPython.display import displayfrom ipywidgets import widgets as wgdfs = df.copy() Next, we create the chart object. Because we want our Plotly chart to be compatible with Jupyter widgets, our chart needs to be a FigureWidget object rather than a Figure object. The style function we defined before works on FigureWidget objects as well, so we can simply apply it to our plot. Before we can add interactivity, we need to populate our chart with initial data. We need to provide an initial state for our chart. In our case, state represents the selected reference date. We’ll use the starting date as our initial state, index the data to with respect to that date with create_indexed_columns and add all traces including the black reference line to the plot. We have the base, our initial state. The next step is to write the update_chart function, that will receive a date as an input and property of the widget, normalize our data to that date using create_indexed_columns and update the y-values of the traces with these new values. To update mulitple values at once, we will perform the updates using the figure.batch_update() context manager. Every change to the layout and data inside the with figure.batch_update() block will be sent to the chart in one message, instead of multiple messages like with update and thus prevent stuttering. Now we are set to implement both the date picker variant and the slider variant. We’ll start off with the first. There are four steps left: Create a DatePicker widget.Define a callback function picker_response that listens to changes in the widget and calls update_chart.Connect the callback function to the widget.Put the widgets into containers and display everything. Create a DatePicker widget. Define a callback function picker_response that listens to changes in the widget and calls update_chart. Connect the callback function to the widget. Put the widgets into containers and display everything. Step 1 is straightforward. For step 2 and 3, a special handler function picker_response with the signature handler(change) must be used for the callback. change is a dictionary that holds the information about the change, such as the old and new values and the names of the widget's changed attributes. We'll use the new key to get the new value that was set on change. To bind the handler to the widget we use the observe method of the widget. By setting the names parameter of observe we specify on which attributes of the widget the callback function will be executed. In our case we need to set names='value' because we want to pass the value of the slider, i.e. the selected date to the handler. In step 4, we simply call the ipython.display function with a vertical box widget, that contains the date picker widget (wrapped in a horizontal box) and the figure widget. The boxes act like containers, similar to HTML divs. And that's it! The chart works as expected. Now let’s reimplement the dynamic index chart with the slider using a slider widget. The procedure here is structurally identical to the previous chart. First, we define a selection slider widget, that stores a list of option values. We will use the dates in the index transformed to strings for our options. We use strings, because otherwise the current date will be formatted with zeroes for hours, which isn’t pretty. Here is the part that will allow us to make this chart a robust alternative for the dynamic index chart: By setting the continuous_update attribute of the widget to false, the callback function will be executed only on release events. This will produce a chart that is not as fancy as the dynamic index chart, but with the same date selection interface and all the benefits of redrawing on every date slider change. If you enable continuous_update, the chart will behave exactly like the dynamic index chart, with the same (if not worse) speed. Next, we write the callback function and connect it to the slider with observe. Finally, we wrap everything into a VBox widget and call display. Et voilà - the chart is ready! I hope you liked my first article! Follow me on Medium for more high-quality stuff and check out my GitHub to get the entire JupyterNotebook for this post. Some rights reserved
[ { "code": null, "e": 432, "s": 172, "text": "When working with time series data, raw numbers often provide little insight. If you have multiple variables that vary in magnitude, changes in smaller values are hard to see. There is a simple solution to this problem: Using index charts that index the data." }, { "code": null, "e": 945, "s": 432, "text": "While regular index charts work fine, by using a simple extension to indexing you can significantly improve your visual presentation and help your charts communicate causalities in the data. This extension is what I refer to as “multi-indexing” — using multiple indices instead of one. That allows you to analyze data from different vantage points. It is especially useful when you suspect that there were events at specific points in time that had a significant influence on the growth of variables in question." }, { "code": null, "e": 1520, "s": 945, "text": "As an example, if you were to compare stock prices for some stocks from 1980 to today, you would find that the Black Monday in 1987, the Dot-com bubble in 2000, and the stock market crash in 2008 were all events that influenced the market heavily and would be interesting to look at. So, you would add them to the indices list, reference data to each of these dates and compare how the prices developed with respect to each reference point. Looking at the prices this way would give you a better intuition of the magnitude of each event compared to just a single index date." }, { "code": null, "e": 1949, "s": 1520, "text": "In this article I will teach you how you can implement multi-indexing in time-series plots using the Python Plotly data visualization library. I will present three approaches with complete code and explain them in detail, including the advantages and disadvantages of each approach and when to use which. To keep up with the article, you should be familiar with Python and Pandas and preferably have had some exposure to Plotly." }, { "code": null, "e": 2282, "s": 1949, "text": "If you care about only one of the three charts I will talk about, feel free to skip the others — the article is written in a modular way, so you won’t miss anything. However make sure to thoroughly read part 1 (Setup and Preparation), because it contains important concepts and function definitions that will be used in every chart." }, { "code": null, "e": 2344, "s": 2282, "text": "[You can find the entire Jupyter Notebook of this post here.]" }, { "code": null, "e": 2404, "s": 2344, "text": "Setup and preparationIndex chart with fixed reference dates" }, { "code": null, "e": 2426, "s": 2404, "text": "Setup and preparation" }, { "code": null, "e": 2465, "s": 2426, "text": "Index chart with fixed reference dates" }, { "code": null, "e": 2488, "s": 2465, "text": "3. Dynamic index chart" }, { "code": null, "e": 2537, "s": 2488, "text": "4. Index chart with variable index in JupyterLab" }, { "code": null, "e": 3017, "s": 2537, "text": "As already mentioned, data preparation tasks will be done with Pandas. Most of the plotting will be handled by the Plotly graph_objects module. Additionaly for one plot we will use the ipywidgets library, which provides widgets for interacting with plots in Jupyter Notebook and JupyterLab. For the time series data we are going to use historic stock market data from Yahoo!Finance API. There is a great Python library called yfinance which we will use to interface with the API." }, { "code": null, "e": 3485, "s": 3017, "text": "Our goal is to build index charts that will enable the user to compare the development of selected stocks relative to a selected date on the first glance. So, let’s pick some stocks to compare. We will be featuring Facebook (FB), Amazon (AMZN), DowDupont (DD) and also Berkshire Hathaway class A shares (BRK-A) which is the highest-ever priced share for a stock. I purposefully chose stocks from a very broad price range, to demonstrate the effectiveness of indexing." }, { "code": null, "e": 3702, "s": 3485, "text": "The call to yf.download() downloads data for the given time period in given intervals, in our case starting from today and dating 3 years back, once per week. The result is stored in a multi-indexed Pandas dataframe." }, { "code": null, "e": 3915, "s": 3702, "text": "Setting group_by='column' specifies how the data will be grouped, either by price type (column) or tickers (ticker). This translates to whether price types or tickers will be the top-level index of our dataframe." }, { "code": null, "e": 4086, "s": 3915, "text": "The table contains five different prices. To simplify things, we will only look at the adjusted closing price and drop everything else. We’ll remove empty values as well." }, { "code": null, "e": 4146, "s": 4086, "text": "df = df.filter(regex=\"Adj Close\")df = df.dropna()df.head(5)" }, { "code": null, "e": 4215, "s": 4146, "text": "Now that our data is ready, let’s take a first glance at the values." }, { "code": null, "e": 4225, "s": 4215, "text": "df.plot()" }, { "code": null, "e": 4457, "s": 4225, "text": "Plotting raw values helps little in comparing the stocks. Due to by magnitudes higher prices of BRK-A shares, changes in all other stocks are practically invisible. Maybe scaling the data logarithmically will alleviate the problem?" }, { "code": null, "e": 4476, "s": 4457, "text": "df.plot(logy=True)" }, { "code": null, "e": 4619, "s": 4476, "text": "Even at logarithmic scale the discrepancy in values is too big for us to meaningfully compare the stocks. It is evident that we need indexing." }, { "code": null, "e": 5296, "s": 4619, "text": "Indexing is simple: Pick a date D, the index, and divide the price at every date by the value at date D. Now, all resulting values are represented as their ratio to the value V at D and can be easily compared to each other. In our case, we need to distinguish between different stocks, so for every stock we divide all values by the value at date D for the respective stock. We can do this easily in Pandas, as we have a multi-indexed dataframe. Calling iloc on a specific index returns a Pandas series containing the values of all stocks for the specific index. When we divide the dataframe by a series, Pandas divides every column by the corresponding element in the series." }, { "code": null, "e": 5746, "s": 5296, "text": "We will also add some cosmetics. Multiplying the new values by 100 will give us percentage values, that are more comfortable to work with. The second optional cosmetic is subtracting 100 from the result. This effectively sets 100% to 0% and changes ratio to relative difference. As an example, a drop to 30% of the original value will now be interpreted as original value — 70 %. Personally, I think that this interpretation is easier to comprehend." }, { "code": null, "e": 5899, "s": 5746, "text": "Note that I will refer to the index date as reference date and index value as reference value. This is done to avoid confusion with the dataframe index." }, { "code": null, "e": 6127, "s": 5899, "text": "# use the first date as index reference_value = df.iloc[0]# dividing by the series divides each column by the # corresponding element in the seriestmp_df = df.div(reference_value) * 100 - 100tmp_df.plot()prepared_df = df.copy()" }, { "code": null, "e": 6214, "s": 6127, "text": "This looks much better. The stock price trends are immediately visible and comparable." }, { "code": null, "e": 6392, "s": 6214, "text": "We are going to use indexing many more times, so let’s write a generalized function create_indexed_columns() for this technique. The function will take the following parameters:" }, { "code": null, "e": 6549, "s": 6392, "text": "date - the reference date that is the indexdf - the dataframe to work ontop_level_name - (optional) name for the top level index of the normalized dataframe" }, { "code": null, "e": 6593, "s": 6549, "text": "date - the reference date that is the index" }, { "code": null, "e": 6623, "s": 6593, "text": "df - the dataframe to work on" }, { "code": null, "e": 6708, "s": 6623, "text": "top_level_name - (optional) name for the top level index of the normalized dataframe" }, { "code": null, "e": 6783, "s": 6708, "text": "and return a new dataframe with normalized data and a new top level index." }, { "code": null, "e": 7202, "s": 6783, "text": "One important consideration is how to handle an input date that is not in the dataframe. Luckily, dataframe indices have a very useful method get_loc() that will find the integer index of given index. When we pass the method=nearest parameter to the method, Pandas will search for the closest index to the provided input. As our index is of type datetime, the date that is closest to the provided date will be matched." }, { "code": null, "e": 7776, "s": 7202, "text": "Before we move on to the first Plotly index chart, let’s recap the concept of “multi-index” charts. As we have seen, indexing data to one point in time is very effective. However, often it is useful to look at multiple reference points. These might be specific events in the time series that had a big influence on our data. Looking at the data from multiple points gives the user the ability to easily see how the variable in question has grown relative to different reference points. The best way to accomplish this is to embed this functionality directly into the chart." }, { "code": null, "e": 7901, "s": 7776, "text": "This quick introduction only briefly touches on the basic concepts of Plotly. Skip it if you have worked with Plotly before." }, { "code": null, "e": 8164, "s": 7901, "text": "Having multiple indices in a plot implies that they need to be switchable on the fly, therefore our plot has to be interactive. Plotly is interactive out of the box and extending interactability is relatively simple, which is why Plotly is the library of choice." }, { "code": null, "e": 8614, "s": 8164, "text": "In Plotly, every figure is a JSON-like data structure with three main properties (called attributes): data, layout and frames. The first two are self-explanatory while the frames attribute contains optional frames that are used in animations. You can either first write the entire figure structure using JSON or Python dictionaries and then instantiate the figure object, or create the figure object first and update figure attributes incrementally." }, { "code": null, "e": 8722, "s": 8614, "text": "As a warm up, let’s recreate the default matplotlib chart that we generated by calling df.plot() in Plotly." }, { "code": null, "e": 8938, "s": 8722, "text": "In the above example we instantiate the Figure object and then add individual traces to said object one by one. We can call update_layout() with a dictionary of updated attributes to change the layout of the figure." }, { "code": null, "e": 9406, "s": 8938, "text": "All changes to a Plotly figure are done this way, passing a dictionary of attributes to the figure. Plotly supports “magic underscore notation” which means that we don’t need to stepwise deepen into the object to access inner attributes but rather are able to access inner attributes directly. For example, we can simply write fig.update_layout(yaxis_type='log') instead of accessing the type attribute of the yaxis attribute - in many cases a more readable approach." }, { "code": null, "e": 9465, "s": 9406, "text": "Now that we are all set, we can get on to our first chart." }, { "code": null, "e": 9745, "s": 9465, "text": "For this chart, we are going to use preselected dates around the time of stock market recessions and dates that had an impact on the companies we are analyzing. The dates listed below may not be entirely accurate, but they lay approximately in the timerange of the listed events." }, { "code": null, "e": 9902, "s": 9745, "text": "ref_dict = { \"Cambridge Analytica scandal\": \"2018-03-28\", \"DowDuPont separation\": \"2019-04-15\", \"Corona stock market drop\": \"2020-02-14\"}" }, { "code": null, "e": 10401, "s": 9902, "text": "We will index our data with respect to each of these dates and include all differently indexed data in our chart. Switching between the different indexed data will be accomplished by using a dropdown menu with an item for every reference date. Plotly refers to this as “buttons”. Clicking a button will display only the data indexed by the respective reference date. To achieve this, we need to switch the visibility of the traces we want to show to on, and switch it off for the remanining traces." }, { "code": null, "e": 10725, "s": 10401, "text": "First, let’s calculate values for each reference date and populate our dataframe with the resulting data. We will create a new dataframe for each reference date and then join them into one dataframe. We will also store the closest date to the given reference date, in case that we don’t have values for that reference date." }, { "code": null, "e": 11190, "s": 10725, "text": "Now that our table is transformed we can build our Plotly object. We will create a new figure and add a trace for each newly computed column. We are going to provide an additional meta attribute to every trace. The meta attribute can store arbitrary JSON data and has many applications. We will use it to store the reference date that a trace belongs to. This will allow us to identify a group of traces that will be switched to visible/invisible at the same time." }, { "code": null, "e": 11465, "s": 11190, "text": "That’s a lot of traces! We want to show only those that belong to one reference date. Just like before, we won’t hardcode the buttons for our exact data. It is better to generalize our procedure so that we’ll be able to handle a different set of reference dates and tickers." }, { "code": null, "e": 12025, "s": 11465, "text": "To show or hide traces, we will need to set the visibility attribute of our figure. Because this is an attribute of the figure and not an individual trace, by default changes to this attribute apply to all traces. Internally, visibility is represented as an array of boolean values, where the value at a specific index represents the visibility of the trace with the same index. The trace index is the position of a trace within that array and because traces are added one by one, trace index represents the order in which the traces were added to the figure." }, { "code": null, "e": 12376, "s": 12025, "text": "The visibility array allows us to target individual traces, either by passing the index of a specific trace or passing an array of boolean values where the value at each index indicates whether the corresponding trace will be shown. For example, with 4 traces, passing the array [True, False, True, False] will display only the first and third trace." }, { "code": null, "e": 12787, "s": 12376, "text": "As you can imagine, relying on the order in which the traces were added to create permanent buttons is a brittle approach. If you add traces in a different order or add more traces, every mention of the visibility array would have to be checked and updated manually. This is why we added the meta attribute - this way, we don't need to rely on the order of the traces to identify which traces to switch on/off." }, { "code": null, "e": 12929, "s": 12787, "text": "A simple function create_visibility_array will create the visibility array by comparing the meta value of every trace to the passed in value." }, { "code": null, "e": 12987, "s": 12929, "text": "Finally, we will write a function for generating buttons." }, { "code": null, "e": 13282, "s": 12987, "text": "Let’s clarify the button description. method specifies the Plotly method that the button calls on clicking. restyle updates the data and the layout of the plot. The args argument takes a list of chart attributes that will be updated by clicking the button, in our case the visibility attribute." }, { "code": null, "e": 13351, "s": 13282, "text": "Lastly we will add the buttons to the figure and inspect the result." }, { "code": null, "e": 13666, "s": 13351, "text": "Great, the buttons work as expected. The only problem is that it is somewhat hard to see the actual reference date. We can solve this by adding a vertical line at the x-coordinate of every reference date. Naturally, we’ll need to be able to toggle the visibility of these reference lines with our existing buttons." }, { "code": null, "e": 14372, "s": 13666, "text": "There are two ways to do this in Plotly: The standard way is by adding a shape object to the figure. In our case we would simply add a line shape by calling figure.add_shape() and specifying the x and y coordinates. While this approach may seem straightforward, there are some difficulties specific to our case. Because shapes aren't traces, we can't change their visibility with our existing method. Rather, the visibility attribute of an individual shape object has to be set, doing which is somewhat obscure (this Stack Overflow question illustrates the process). Furthermore, there seems to be no concise way, similar to the trace visibility array, to change the visibility of multiple shapes at once." }, { "code": null, "e": 15089, "s": 14372, "text": "The second way to add reference lines is by adding a trace that will be drawn as a vertical line. To do this, two y-coordinates must be chosen that will set the boundaries of the line. However, we need to ensure that the line covers the entire plot heightwise and in addition to that, the reference line must not affect the scaling of the plot — this means that we can’t simply choose some value below and above the minimum and respectively maximum values in our dataframe as boundaries, as this would skew the scale of the remaining values. The solution is to add a secondary, invisible y-axis to the plot that will be independent of the values in the dataframe and scale the reference lines with respect to itself." }, { "code": null, "e": 15443, "s": 15089, "text": "Although the secondary y-axis somewhat increases the complexity of our figure, using traces as reference lines provides a significant benefit: We can toggle the visibility of the reference lines the same way as we do with all other traces. Thus, we only need to add the reference line trace and set its meta parameter to the reference date it refers to." }, { "code": null, "e": 15706, "s": 15443, "text": "As you can see, the second approach is a better fit for our situation, which is why we will utilize it. Before we add the reference lines, let’s first add the secondary y-axis to the plot. While we are at it, we might as well add some simple styling to the plot." }, { "code": null, "e": 16387, "s": 15706, "text": "The hovermode attribute specifies how the hoverlabels will be displayed in our plot. Setting this value to 'x' will display the values of every trace at the x-value the mouse is hovering over. We set the secondary y-axis to a fixed range. This way, the line will always extend throughout the entire height of the plot. Setting the overlaying attribute to 'y' is very important, as this will force the traces that are defined with respect to the secondary y-axis to behave as if they were defined on the first y-axis - concretely, the combination of this attribute and fixedrange is exactly what allows us to see the reference lines yet makes their scale independent of the y-axis." }, { "code": null, "e": 16663, "s": 16387, "text": "Now that the figure is prepared, we can write a create_reference_line() function that will generate the reference lines for us. One important thing to note is that as we specify two values for y-coordinates, symmetrically, we need to provide a list with two x-values as well." }, { "code": null, "e": 16729, "s": 16663, "text": "The only additions to our previous scatter trace definitions are:" }, { "code": null, "e": 16839, "s": 16729, "text": "mode=\"lines\" - specifies that the traces should be drawn as lines only, without marking the points in between" }, { "code": null, "e": 16916, "s": 16839, "text": "yaxis=\"y2\" - specifies that the secondary y-axis is to be used as the y-axis" }, { "code": null, "e": 16958, "s": 16916, "text": "line - determines the styling of the line" }, { "code": null, "e": 17085, "s": 16958, "text": "Finally, the last step consists of adding the reference line traces to the plot and regenerating the visibility buttons. Done!" }, { "code": null, "e": 17249, "s": 17085, "text": "The second chart we will look at is a dynamic index chart. This chart allows the user to quickly move between reference dates, creating a visually appealing chart." }, { "code": null, "e": 17567, "s": 17249, "text": "Because we are using only the Plotly graphing library, the best approach here is to create a frame for each reference date and then use a Plotly slider to move between them. By using a slider we can also add an animation effect for transitioning between reference dates, which will make the transitions much smoother." }, { "code": null, "e": 18037, "s": 17567, "text": "First off we need to index the data to every date and create traces for it. The resulting data will be stored in a frame which is simply a figure['data'] dictionary that with an identifying name. We will create the traces like in the previous example using the create_indexed_columns and create_reference_line functions. A frame will be identified by the date that the data in the frame is indexed to. The function create_traces_for_date will bundle this functionality." }, { "code": null, "e": 18150, "s": 18037, "text": "Next, we will create a slider dictionary that will define our slider. Some important attributes that we use are:" }, { "code": null, "e": 18216, "s": 18150, "text": "yanchor and xanchor - specify where the slider will be positioned" }, { "code": null, "e": 18245, "s": 18216, "text": "pad - padding for the slider" }, { "code": null, "e": 18368, "s": 18245, "text": "currentvalue - describes how the current value of the slider will be displayed including position, font size and a prefix." }, { "code": null, "e": 18503, "s": 18368, "text": "len - describes the length of the slider relative to the chart. 1 indicates that it matches the length exactly, which is what we want." }, { "code": null, "e": 18619, "s": 18503, "text": "steps - is a list of steps that the slider will cycle through. We will leave it empty at first and add to it later." }, { "code": null, "e": 19346, "s": 18619, "text": "The next thing to do is to create steps that we will add to our slider. A step is described by the attributes label, method and args. method specifies which Plotly function will be called when the slider value changes. By using animate we will get a smooth transition between frames. The args attribute describes the data that will be passed to the Plotly function specifed in method, consisting of a list of frames and a dictionary specifying how to transition between them. You can actually specify multiple frames for each slider step that will all be cycled through when the slider is moved to that step. In our case, we only want one frame and identify it by its name. After that we describe the transitioning properties:" }, { "code": null, "e": 19477, "s": 19346, "text": "frame - duration specifies the total time the frame will be displayed, redraw whether the chart should be redrawn after each step." }, { "code": null, "e": 19677, "s": 19477, "text": "mode - specifies how a new call to the animate function interacts with current animations. Setting it to \"next\" means that the current running frame will be finished before switching to the next one." }, { "code": null, "e": 19805, "s": 19677, "text": "transition - specifies the duration of the transitioning part of the total frame duration and the easing function that is used." }, { "code": null, "e": 20788, "s": 19805, "text": "There are a few important details to note here. First, setting redraw=False provides significant performance benefits in our case, as we have hundreds of frames, each with hundreds of points. Without that setting, the chart updates visibly lag behind, as you will see soon. However, there are some drawbacks to disabling redraw: For example, a rangeslider which allows you to set the view range will not be updated if redraw is deactivated. Another important drawback is that the range of the y-axis will not be automatically updated, which sometimes may not show all points on the chart. In the third part of this article we will see how to combine the best of both implementations, that is, fast updates and redrawing of the chart, at the cost of some dynamicity and requiring a Jupyter notebook. There is also a way to have it all (for a reasonable amount of data points) without compromising, but this solution requires the Dash server which is beyond the scope of this article." }, { "code": null, "e": 20969, "s": 20788, "text": "The other thing to remember is that the transition duration time is a part of the frame duration time, so setting it larger than the frame duration won’t change the total duration." }, { "code": null, "e": 21127, "s": 20969, "text": "Furthermore, Plotly will animate transitions between multiple frames during a slider step and the transition between frames of two neighbouring slider steps." }, { "code": null, "e": 21574, "s": 21127, "text": "Now, with all functions set, we can actually create frames and steps and populate our figure. For every date, we will create a frame with traces indexed to that date and a slider step for that frame. Note that we set the name of a frame to a iso-formatted string of the date it represents and immediately pass that string to our create_slider_step function. This is done because the slider uses the frame name to determine which frame to display." }, { "code": null, "e": 21757, "s": 21574, "text": "Lastly, we build our figure. We simply use the first frame as the data attribute of our figure. We use the style_plot function to configure the secondary y-axis, and we are finished!" }, { "code": null, "e": 21927, "s": 21757, "text": "I have warned you about enabling redraw, but let's actually see it in action. We will create the exact same index chart as before, but this time with redraw set to true." }, { "code": null, "e": 22275, "s": 21927, "text": "As you see, the chart is significantly slower than before. Personally, I find this amount of lag barely acceptable; however this is the limit: if you increase the amount of data points to above 5000, the chart will be to slow for anyone to enjoy using it. To keep the speed acceptable, you need to keep the amount of data points below this number." }, { "code": null, "e": 22762, "s": 22275, "text": "The third chart will allow a user to select a custom reference date. If you plan on presenting your work in a JupyterLab, don’t need fancy animations like in the dynamic index chart, yet still want to enbale the user to pick any date as the reference date, this chart is right for you. Note that this chart will work only in JupyterLab and not in Jupyter Notebooks! The chart will be implemented with the ipywidgets library that uses widgets. According to the official docs, widgets are" }, { "code": null, "e": 23057, "s": 22762, "text": "eventful Python objects that have a representation in the browser, often as a controller like a slider, textbox, etc. [..] You can use widgets to build interactive GUIs for your notebooks. You can also use widgets to synchronize stateful and stateless information between Python and JavaScript." }, { "code": null, "e": 23296, "s": 23057, "text": "(Source) The idea is to use widgets to provide input for our chart via GUI and to update the chart. This way, after a different reference date was selected, the chart data will be updated through a Jupyter callback and not a Plotly event." }, { "code": null, "e": 23537, "s": 23296, "text": "We will build two version of the chart, using two different widgets. One will be a DatePicker widget and the second will be a SelectionSlider widget. The second version will be a robust implementation of the dynamic index chart from part 2." }, { "code": null, "e": 23672, "s": 23537, "text": "First off we copy our initial dataframe and import additional libraries. Ipython.display is used to render the widgets in the browser." }, { "code": null, "e": 23759, "s": 23672, "text": "from IPython.display import displayfrom ipywidgets import widgets as wgdfs = df.copy()" }, { "code": null, "e": 23938, "s": 23759, "text": "Next, we create the chart object. Because we want our Plotly chart to be compatible with Jupyter widgets, our chart needs to be a FigureWidget object rather than a Figure object." }, { "code": null, "e": 24053, "s": 23938, "text": "The style function we defined before works on FigureWidget objects as well, so we can simply apply it to our plot." }, { "code": null, "e": 24434, "s": 24053, "text": "Before we can add interactivity, we need to populate our chart with initial data. We need to provide an initial state for our chart. In our case, state represents the selected reference date. We’ll use the starting date as our initial state, index the data to with respect to that date with create_indexed_columns and add all traces including the black reference line to the plot." }, { "code": null, "e": 25020, "s": 24434, "text": "We have the base, our initial state. The next step is to write the update_chart function, that will receive a date as an input and property of the widget, normalize our data to that date using create_indexed_columns and update the y-values of the traces with these new values. To update mulitple values at once, we will perform the updates using the figure.batch_update() context manager. Every change to the layout and data inside the with figure.batch_update() block will be sent to the chart in one message, instead of multiple messages like with update and thus prevent stuttering." }, { "code": null, "e": 25133, "s": 25020, "text": "Now we are set to implement both the date picker variant and the slider variant. We’ll start off with the first." }, { "code": null, "e": 25160, "s": 25133, "text": "There are four steps left:" }, { "code": null, "e": 25391, "s": 25160, "text": "Create a DatePicker widget.Define a callback function picker_response that listens to changes in the widget and calls update_chart.Connect the callback function to the widget.Put the widgets into containers and display everything." }, { "code": null, "e": 25419, "s": 25391, "text": "Create a DatePicker widget." }, { "code": null, "e": 25524, "s": 25419, "text": "Define a callback function picker_response that listens to changes in the widget and calls update_chart." }, { "code": null, "e": 25569, "s": 25524, "text": "Connect the callback function to the widget." }, { "code": null, "e": 25625, "s": 25569, "text": "Put the widgets into containers and display everything." }, { "code": null, "e": 25652, "s": 25625, "text": "Step 1 is straightforward." }, { "code": null, "e": 26326, "s": 25652, "text": "For step 2 and 3, a special handler function picker_response with the signature handler(change) must be used for the callback. change is a dictionary that holds the information about the change, such as the old and new values and the names of the widget's changed attributes. We'll use the new key to get the new value that was set on change. To bind the handler to the widget we use the observe method of the widget. By setting the names parameter of observe we specify on which attributes of the widget the callback function will be executed. In our case we need to set names='value' because we want to pass the value of the slider, i.e. the selected date to the handler." }, { "code": null, "e": 26567, "s": 26326, "text": "In step 4, we simply call the ipython.display function with a vertical box widget, that contains the date picker widget (wrapped in a horizontal box) and the figure widget. The boxes act like containers, similar to HTML divs. And that's it!" }, { "code": null, "e": 26596, "s": 26567, "text": "The chart works as expected." }, { "code": null, "e": 27017, "s": 26596, "text": "Now let’s reimplement the dynamic index chart with the slider using a slider widget. The procedure here is structurally identical to the previous chart. First, we define a selection slider widget, that stores a list of option values. We will use the dates in the index transformed to strings for our options. We use strings, because otherwise the current date will be formatted with zeroes for hours, which isn’t pretty." }, { "code": null, "e": 27562, "s": 27017, "text": "Here is the part that will allow us to make this chart a robust alternative for the dynamic index chart: By setting the continuous_update attribute of the widget to false, the callback function will be executed only on release events. This will produce a chart that is not as fancy as the dynamic index chart, but with the same date selection interface and all the benefits of redrawing on every date slider change. If you enable continuous_update, the chart will behave exactly like the dynamic index chart, with the same (if not worse) speed." }, { "code": null, "e": 27739, "s": 27562, "text": "Next, we write the callback function and connect it to the slider with observe. Finally, we wrap everything into a VBox widget and call display. Et voilà - the chart is ready!" }, { "code": null, "e": 27774, "s": 27739, "text": "I hope you liked my first article!" }, { "code": null, "e": 27895, "s": 27774, "text": "Follow me on Medium for more high-quality stuff and check out my GitHub to get the entire JupyterNotebook for this post." } ]
Probability - GeeksforGeeks
21 Jan, 2014 Solution set: { 6, (1,5), (1,6) ......} i.e. P(6 appeared on first throw) + P(1 appeared on first throw and 5 appeared on second throw) + P(1 appeared on first throw and 6 appeared on second throw) + .................... = 1/6 + (1/6)(1/6) + (1/6)(1/6) + ..... = 1/6 + 9/36 = 5/12.Viewpoint 2: P(......) = P(6 came on first throw) + P(sum>= 6 and 1,2,3 appeared in first throw) = 1/6 + ???? P(1,2,3 appeared in first throw) = 1/2 //P(E1) P(sum >= 6 | 1,2,3 appeared in first throw) = 9/18 //P(E2 | E1) // Our new sample space is: { (1,1), (1,2), (1,3), (1,4), (1,5), (1,6) (2,1), (2,2), (2,3), (2,4), (2,5), (2,6) (3,1), (3,2), (3,3), (3,4), (3,5), (3,6) } // 9 favorable cases: {(1,5), (1,6), (2,4), (2,5), (2,6), (3,3), (3,4), (3,5), (3,6) } P(sum>= 6 and 1,2,3 appeared in first throw) = (1/2)(9/18) //P(E2 ∩ E1) = P(E1)P(E2|E1) P(what we are looking for) = 1/6 + 9/36 = 5/12 Correct Answer: B A computer can be declared faulty in two cases 1) It is actually faulty and correctly declared so (p*q) 2) Not faulty and incorrectly declared (1-p)*(1-q). Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# Program to Check Given Directory Exists or not error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++ Show all columns of Pandas DataFrame in Jupyter Notebook How to split a Dataset into Train and Test Sets using Python How to check if a set contains an element in Python? Angular Material Toolbar Component How to write Pandas DataFrame as TSV using Python? How to Read Text Files with Pandas? Must Do Coding Questions for Product Based Companies How to Conditionally Remove Rows in R DataFrame?
[ { "code": null, "e": 29617, "s": 29589, "text": "\n21 Jan, 2014" }, { "code": null, "e": 29657, "s": 29617, "text": "Solution set: { 6, (1,5), (1,6) ......}" }, { "code": null, "e": 29711, "s": 29657, "text": " i.e. P(6 appeared on first throw) +" }, { "code": null, "e": 29796, "s": 29711, "text": " P(1 appeared on first throw and 5 appeared on second throw) +" }, { "code": null, "e": 29903, "s": 29796, "text": " P(1 appeared on first throw and 6 appeared on second throw) + ...................." }, { "code": null, "e": 29965, "s": 29903, "text": " = 1/6 + (1/6)(1/6) + (1/6)(1/6) + ....." }, { "code": null, "e": 30000, "s": 29965, "text": " = 1/6 + 9/36" }, { "code": null, "e": 30042, "s": 30000, "text": " = 5/12.Viewpoint 2:" }, { "code": null, "e": 30129, "s": 30042, "text": "P(......) = P(6 came on first throw) + P(sum>= 6 and 1,2,3 appeared in first throw)" }, { "code": null, "e": 30204, "s": 30129, "text": " = 1/6 + ????" }, { "code": null, "e": 30301, "s": 30204, "text": "P(1,2,3 appeared in first throw) = 1/2 //P(E1)" }, { "code": null, "e": 30393, "s": 30301, "text": "P(sum >= 6 | 1,2,3 appeared in first throw) = 9/18 //P(E2 | E1)" }, { "code": null, "e": 30465, "s": 30393, "text": "// Our new sample space is: { (1,1), (1,2), (1,3), (1,4), (1,5), (1,6)" }, { "code": null, "e": 30555, "s": 30465, "text": " (2,1), (2,2), (2,3), (2,4), (2,5), (2,6)" }, { "code": null, "e": 30646, "s": 30555, "text": " (3,1), (3,2), (3,3), (3,4), (3,5), (3,6) }" }, { "code": null, "e": 30733, "s": 30646, "text": "// 9 favorable cases: {(1,5), (1,6), (2,4), (2,5), (2,6), (3,3), (3,4), (3,5), (3,6) }" }, { "code": null, "e": 30834, "s": 30733, "text": "P(sum>= 6 and 1,2,3 appeared in first throw) = (1/2)(9/18) //P(E2 ∩ E1) = P(E1)P(E2|E1)" }, { "code": null, "e": 30885, "s": 30834, "text": "P(what we are looking for) = 1/6 + 9/36 = 5/12" }, { "code": null, "e": 30903, "s": 30885, "text": "Correct Answer: B" }, { "code": null, "e": 31061, "s": 30903, "text": "A computer can be declared faulty in two cases \n1) It is actually faulty and correctly declared so (p*q)\n2) Not faulty and incorrectly declared (1-p)*(1-q). " }, { "code": null, "e": 31159, "s": 31061, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 31169, "s": 31159, "text": "Comments\n" }, { "code": null, "e": 31183, "s": 31169, "text": "Old Comments\n" }, { "code": null, "e": 31233, "s": 31183, "text": "C# Program to Check Given Directory Exists or not" }, { "code": null, "e": 31329, "s": 31233, "text": "error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++" }, { "code": null, "e": 31386, "s": 31329, "text": "Show all columns of Pandas DataFrame in Jupyter Notebook" }, { "code": null, "e": 31447, "s": 31386, "text": "How to split a Dataset into Train and Test Sets using Python" }, { "code": null, "e": 31501, "s": 31447, "text": "How to check if a set contains an element in Python?\n" }, { "code": null, "e": 31536, "s": 31501, "text": "Angular Material Toolbar Component" }, { "code": null, "e": 31587, "s": 31536, "text": "How to write Pandas DataFrame as TSV using Python?" }, { "code": null, "e": 31623, "s": 31587, "text": "How to Read Text Files with Pandas?" }, { "code": null, "e": 31676, "s": 31623, "text": "Must Do Coding Questions for Product Based Companies" } ]
How to customize X-axis ticks in Matplotlib?
To customize X-axis ticks in Matplotlib, we can change the ticks length and width. Set the figure size and adjust the padding between and around the subplots. Create lists for height, bars and y_pos data points. Make a bar plot using bar() method. To customize X-axis ticks, we can use tick_params() method, with color=red, direction=outward, length=7, and width=2. To display the figure, use show() method. import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True height = [3, 12, 5, 18, 45] bars = ('A', 'B', 'C', 'D', 'E') y_pos = np.arange(len(bars)) plt.bar(y_pos, height, color='yellow') plt.tick_params(axis='x', colors='red', direction='out', length=7, width=2) plt.show()
[ { "code": null, "e": 1145, "s": 1062, "text": "To customize X-axis ticks in Matplotlib, we can change the ticks length and width." }, { "code": null, "e": 1221, "s": 1145, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1274, "s": 1221, "text": "Create lists for height, bars and y_pos data points." }, { "code": null, "e": 1310, "s": 1274, "text": "Make a bar plot using bar() method." }, { "code": null, "e": 1428, "s": 1310, "text": "To customize X-axis ticks, we can use tick_params() method, with color=red, direction=outward, length=7, and width=2." }, { "code": null, "e": 1470, "s": 1428, "text": "To display the figure, use show() method." }, { "code": null, "e": 1828, "s": 1470, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nheight = [3, 12, 5, 18, 45]\nbars = ('A', 'B', 'C', 'D', 'E')\ny_pos = np.arange(len(bars))\n\nplt.bar(y_pos, height, color='yellow')\nplt.tick_params(axis='x', colors='red', direction='out', length=7, width=2)\n\nplt.show()" } ]
From PDF to Excel. Using tabula and xlsxwriter | by Ednalyn C. De Dios | Towards Data Science
In the real world, we’ll often encounter data in all sorts of formats. Today, we’ll tackle the task of extracting tabular data from a PDF and exporting it to Excel. The only caveat is, the pdf file must be machine-generated. PDFs of scanned pages do not work. This is one limitation of tabula. With that said, let’s roll! First, let’s make sure that we have a good java environment. java -version You should see something like: Next, let’s install tabula-py with the following: pip install tabula-py If successful, And lastly, let’s install xlsxwriter: pip install xlsxwriter And we should see something like this: Now, let’s open a jupyter notebook and get to coding! Let us begin with importing the following: import pandas as pdimport tabulaimport xlsxwriter Then let’s get the data: data = tabula.read_pdf('../data/in/titanic.pdf', pages='all', stream=True) The code above results in a list of dataframes. Since there’s only one dataframe in the list, let’s go ahead and extract the dataframe by itself. We can do with df[0]. Next, we’ll need to convert the column headers to the first row by resetting the index and transposing the dataframe twice. df = data[0].reset_index().T.reset_index().T And rename the columns as such: df.columns=['x', 'passenger', 'pc_class', 'gender', 'age', 'parch', 'fare', 'cabin', 'embarked'] Let’s drop the first two columns with: clean_df = df.drop(columns=['x']).reset_index(drop=True) Now we are ready for prime time: Let’s begin by making a new Excel file: workbook = xlsxwriter.Workbook('../data/out/titanic.xlsx', {'nan_inf_to_errors': True}) And add a worksheet (tab) named “test”: worksheet = workbook.add_worksheet('test') Before writing the data into Excel, we need to convert our dataframe into a list first. data = list(clean_df.to_records(index=False)) Let’s initialize the first cell (A1) of the Excel file with: # Rows and columns are zero indexedrow = 0col = 0 Let’s examine the first row: We need to fix that by manually inserting the column headers. Let’s insert the column names into index 0 of the list. data.insert(0, ['passenger', 'pc_class', 'gender', 'age', 'parch', 'fare', 'cabin', 'embarked']) Now we can write row by row. # Iterate over the datafor passenger, pc_class, gender, age, parch, fare, cabin, embarked in data: worksheet.write(row, col, passenger) worksheet.write(row, col + 1, pc_class) worksheet.write(row, col + 2, gender) worksheet.write(row, col + 3, age) worksheet.write(row, col + 4, parch) worksheet.write(row, col + 5, fare) worksheet.write(row, col + 6, cabin) worksheet.write(row, col + 7, embarked) row += 1 And finally, let’s close the workbook. workbook.close() Voila! And that’s it! We got ourselves an Excel file. In this post, we learned how to use tabula and xlsxwriter. We took a pdf file, extracted it to a dataframe, and then wrote the contents into an Excel file. Combined with for loops, we could easily ingest many pdfs and have a flat file that could feed into a database like Redshift. And with a little bit of hackery, we’ve got ourselves a winning combination for automation. You can check out the repo on my Github for further examination. Here’s the whole code: Thanks for stopping by and reading my post. Stay tuned! If you want to learn more about my journey from slacker to data scientist, check out the article below: towardsdatascience.com And if you’re thinking about switching gears and venture into data science, start thinking about rebranding now: towardsdatascience.com You can reach me on Twitter or LinkedIn.
[ { "code": null, "e": 336, "s": 171, "text": "In the real world, we’ll often encounter data in all sorts of formats. Today, we’ll tackle the task of extracting tabular data from a PDF and exporting it to Excel." }, { "code": null, "e": 465, "s": 336, "text": "The only caveat is, the pdf file must be machine-generated. PDFs of scanned pages do not work. This is one limitation of tabula." }, { "code": null, "e": 493, "s": 465, "text": "With that said, let’s roll!" }, { "code": null, "e": 554, "s": 493, "text": "First, let’s make sure that we have a good java environment." }, { "code": null, "e": 568, "s": 554, "text": "java -version" }, { "code": null, "e": 599, "s": 568, "text": "You should see something like:" }, { "code": null, "e": 649, "s": 599, "text": "Next, let’s install tabula-py with the following:" }, { "code": null, "e": 671, "s": 649, "text": "pip install tabula-py" }, { "code": null, "e": 686, "s": 671, "text": "If successful," }, { "code": null, "e": 724, "s": 686, "text": "And lastly, let’s install xlsxwriter:" }, { "code": null, "e": 747, "s": 724, "text": "pip install xlsxwriter" }, { "code": null, "e": 786, "s": 747, "text": "And we should see something like this:" }, { "code": null, "e": 840, "s": 786, "text": "Now, let’s open a jupyter notebook and get to coding!" }, { "code": null, "e": 883, "s": 840, "text": "Let us begin with importing the following:" }, { "code": null, "e": 933, "s": 883, "text": "import pandas as pdimport tabulaimport xlsxwriter" }, { "code": null, "e": 958, "s": 933, "text": "Then let’s get the data:" }, { "code": null, "e": 1033, "s": 958, "text": "data = tabula.read_pdf('../data/in/titanic.pdf', pages='all', stream=True)" }, { "code": null, "e": 1201, "s": 1033, "text": "The code above results in a list of dataframes. Since there’s only one dataframe in the list, let’s go ahead and extract the dataframe by itself. We can do with df[0]." }, { "code": null, "e": 1325, "s": 1201, "text": "Next, we’ll need to convert the column headers to the first row by resetting the index and transposing the dataframe twice." }, { "code": null, "e": 1370, "s": 1325, "text": "df = data[0].reset_index().T.reset_index().T" }, { "code": null, "e": 1402, "s": 1370, "text": "And rename the columns as such:" }, { "code": null, "e": 1499, "s": 1402, "text": "df.columns=['x', 'passenger', 'pc_class', 'gender', 'age', 'parch', 'fare', 'cabin', 'embarked']" }, { "code": null, "e": 1538, "s": 1499, "text": "Let’s drop the first two columns with:" }, { "code": null, "e": 1595, "s": 1538, "text": "clean_df = df.drop(columns=['x']).reset_index(drop=True)" }, { "code": null, "e": 1628, "s": 1595, "text": "Now we are ready for prime time:" }, { "code": null, "e": 1668, "s": 1628, "text": "Let’s begin by making a new Excel file:" }, { "code": null, "e": 1756, "s": 1668, "text": "workbook = xlsxwriter.Workbook('../data/out/titanic.xlsx', {'nan_inf_to_errors': True})" }, { "code": null, "e": 1796, "s": 1756, "text": "And add a worksheet (tab) named “test”:" }, { "code": null, "e": 1839, "s": 1796, "text": "worksheet = workbook.add_worksheet('test')" }, { "code": null, "e": 1927, "s": 1839, "text": "Before writing the data into Excel, we need to convert our dataframe into a list first." }, { "code": null, "e": 1973, "s": 1927, "text": "data = list(clean_df.to_records(index=False))" }, { "code": null, "e": 2034, "s": 1973, "text": "Let’s initialize the first cell (A1) of the Excel file with:" }, { "code": null, "e": 2084, "s": 2034, "text": "# Rows and columns are zero indexedrow = 0col = 0" }, { "code": null, "e": 2113, "s": 2084, "text": "Let’s examine the first row:" }, { "code": null, "e": 2231, "s": 2113, "text": "We need to fix that by manually inserting the column headers. Let’s insert the column names into index 0 of the list." }, { "code": null, "e": 2328, "s": 2231, "text": "data.insert(0, ['passenger', 'pc_class', 'gender', 'age', 'parch', 'fare', 'cabin', 'embarked'])" }, { "code": null, "e": 2357, "s": 2328, "text": "Now we can write row by row." }, { "code": null, "e": 2792, "s": 2357, "text": "# Iterate over the datafor passenger, pc_class, gender, age, parch, fare, cabin, embarked in data: worksheet.write(row, col, passenger) worksheet.write(row, col + 1, pc_class) worksheet.write(row, col + 2, gender) worksheet.write(row, col + 3, age) worksheet.write(row, col + 4, parch) worksheet.write(row, col + 5, fare) worksheet.write(row, col + 6, cabin) worksheet.write(row, col + 7, embarked) row += 1" }, { "code": null, "e": 2831, "s": 2792, "text": "And finally, let’s close the workbook." }, { "code": null, "e": 2848, "s": 2831, "text": "workbook.close()" }, { "code": null, "e": 2855, "s": 2848, "text": "Voila!" }, { "code": null, "e": 2902, "s": 2855, "text": "And that’s it! We got ourselves an Excel file." }, { "code": null, "e": 3276, "s": 2902, "text": "In this post, we learned how to use tabula and xlsxwriter. We took a pdf file, extracted it to a dataframe, and then wrote the contents into an Excel file. Combined with for loops, we could easily ingest many pdfs and have a flat file that could feed into a database like Redshift. And with a little bit of hackery, we’ve got ourselves a winning combination for automation." }, { "code": null, "e": 3364, "s": 3276, "text": "You can check out the repo on my Github for further examination. Here’s the whole code:" }, { "code": null, "e": 3408, "s": 3364, "text": "Thanks for stopping by and reading my post." }, { "code": null, "e": 3420, "s": 3408, "text": "Stay tuned!" }, { "code": null, "e": 3524, "s": 3420, "text": "If you want to learn more about my journey from slacker to data scientist, check out the article below:" }, { "code": null, "e": 3547, "s": 3524, "text": "towardsdatascience.com" }, { "code": null, "e": 3660, "s": 3547, "text": "And if you’re thinking about switching gears and venture into data science, start thinking about rebranding now:" }, { "code": null, "e": 3683, "s": 3660, "text": "towardsdatascience.com" } ]
How to Change Background Color of a Div on Mouse Move Over using JavaScript ? - GeeksforGeeks
19 May, 2020 The background color of the div box can be easily changed using HTML, CSS, and Javascript. We will use the querySelector() and addEventListener() method to select the element and then apply some math logic to change its background color. The below sections will guide you on how to create the effect. HTML Code: In this section, we will create a basic structure of the body. The body section contains a <div> element that background color will be changed when mouse moves over the div element. <!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title> How to Change Background Color of a Div on Mouse Move Over using JavaScript ? </title></head> <body> <div class="first"></div></body> </html> CSS Code: In this section, we will use some CSS property to style the div element. <style> .first { position: absolute; background: #E73C49; width: 300px; height: 250px; top: 50%; left: 50%; transform: translate(-50%, -50%); }</style> Javascript Code:Step 1: The first step is to create an array consisting of different colours. Step 2: The second step is to use the querySelector() method to select the div element and then use addEvenListener() method to attach an event handler (mouseover) to it. Step 3: In the last step, we will style the background of the div element using some logic i.e. we will use Math.random() function on the array to return a floating-point number between the array range then use Math.floor() method to round the floating number downward to its nearest integer. <script type="text/javascript"> var color = [, "#3C9EE7", "#E7993C", "#E73C99", "#3CE746", "#E7993C"]; document.querySelector("div").addEventListener( "mouseover", function () { document.querySelector("div").style.background = color[Math.floor(Math.random() * color.length)]; })</script> Complete Code: In this section, we will combine the above three code sections. <!DOCTYPE html><html> <head> <meta charset="utf-8"> <title> How to Change Background Color of a Div on Mouse Move Over using JavaScript ? </title> <style> .first { position: absolute; background: #E73C49; width: 300px; height: 250px; top: 50%; left: 50%; transform: translate(-50%, -50%); } </style></head> <body> <div class="first"></div> <script type="text/javascript"> var color = [, "#3C9EE7", "#E7993C", "#E73C99", "#3CE746", "#E7993C"]; document.querySelector("div").addEventListener( "mouseover", function () { document.querySelector("div").style.background = color[Math.floor(Math.random() * color.length)]; }) </script></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc 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. Comments Old Comments Design a web page using HTML and CSS Create a Responsive Navbar using ReactJS Form validation using jQuery How to set fixed width for <td> in a table ? How to apply style to parent if it has child with CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? How to Insert Form Data into Database using PHP ? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 25070, "s": 25042, "text": "\n19 May, 2020" }, { "code": null, "e": 25371, "s": 25070, "text": "The background color of the div box can be easily changed using HTML, CSS, and Javascript. We will use the querySelector() and addEventListener() method to select the element and then apply some math logic to change its background color. The below sections will guide you on how to create the effect." }, { "code": null, "e": 25564, "s": 25371, "text": "HTML Code: In this section, we will create a basic structure of the body. The body section contains a <div> element that background color will be changed when mouse moves over the div element." }, { "code": "<!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <meta charset=\"utf-8\"> <title> How to Change Background Color of a Div on Mouse Move Over using JavaScript ? </title></head> <body> <div class=\"first\"></div></body> </html>", "e": 25822, "s": 25564, "text": null }, { "code": null, "e": 25905, "s": 25822, "text": "CSS Code: In this section, we will use some CSS property to style the div element." }, { "code": "<style> .first { position: absolute; background: #E73C49; width: 300px; height: 250px; top: 50%; left: 50%; transform: translate(-50%, -50%); }</style>", "e": 26112, "s": 25905, "text": null }, { "code": null, "e": 26206, "s": 26112, "text": "Javascript Code:Step 1: The first step is to create an array consisting of different colours." }, { "code": null, "e": 26377, "s": 26206, "text": "Step 2: The second step is to use the querySelector() method to select the div element and then use addEvenListener() method to attach an event handler (mouseover) to it." }, { "code": null, "e": 26670, "s": 26377, "text": "Step 3: In the last step, we will style the background of the div element using some logic i.e. we will use Math.random() function on the array to return a floating-point number between the array range then use Math.floor() method to round the floating number downward to its nearest integer." }, { "code": "<script type=\"text/javascript\"> var color = [, \"#3C9EE7\", \"#E7993C\", \"#E73C99\", \"#3CE746\", \"#E7993C\"]; document.querySelector(\"div\").addEventListener( \"mouseover\", function () { document.querySelector(\"div\").style.background = color[Math.floor(Math.random() * color.length)]; })</script>", "e": 27027, "s": 26670, "text": null }, { "code": null, "e": 27106, "s": 27027, "text": "Complete Code: In this section, we will combine the above three code sections." }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <title> How to Change Background Color of a Div on Mouse Move Over using JavaScript ? </title> <style> .first { position: absolute; background: #E73C49; width: 300px; height: 250px; top: 50%; left: 50%; transform: translate(-50%, -50%); } </style></head> <body> <div class=\"first\"></div> <script type=\"text/javascript\"> var color = [, \"#3C9EE7\", \"#E7993C\", \"#E73C99\", \"#3CE746\", \"#E7993C\"]; document.querySelector(\"div\").addEventListener( \"mouseover\", function () { document.querySelector(\"div\").style.background = color[Math.floor(Math.random() * color.length)]; }) </script></body> </html>", "e": 27975, "s": 27106, "text": null }, { "code": null, "e": 27983, "s": 27975, "text": "Output:" }, { "code": null, "e": 27992, "s": 27983, "text": "CSS-Misc" }, { "code": null, "e": 28002, "s": 27992, "text": "HTML-Misc" }, { "code": null, "e": 28018, "s": 28002, "text": "JavaScript-Misc" }, { "code": null, "e": 28022, "s": 28018, "text": "CSS" }, { "code": null, "e": 28027, "s": 28022, "text": "HTML" }, { "code": null, "e": 28038, "s": 28027, "text": "JavaScript" }, { "code": null, "e": 28055, "s": 28038, "text": "Web Technologies" }, { "code": null, "e": 28082, "s": 28055, "text": "Web technologies Questions" }, { "code": null, "e": 28087, "s": 28082, "text": "HTML" }, { "code": null, "e": 28185, "s": 28087, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28194, "s": 28185, "text": "Comments" }, { "code": null, "e": 28207, "s": 28194, "text": "Old Comments" }, { "code": null, "e": 28244, "s": 28207, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28285, "s": 28244, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 28314, "s": 28285, "text": "Form validation using jQuery" }, { "code": null, "e": 28359, "s": 28314, "text": "How to set fixed width for <td> in a table ?" }, { "code": null, "e": 28414, "s": 28359, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 28474, "s": 28414, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28535, "s": 28474, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28585, "s": 28535, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28609, "s": 28585, "text": "REST API (Introduction)" } ]
How To Set Up and Configure NFS on Ubuntu 16.04
In this article, we will learn how to install NFS on Ubuntu 16.04Network File System (NFS) protocol and a filesystem which allows you to access the shared folders from the remote system or server and also allows you to mount as a remote directory on the servers. This allows you to share the storage space between different clients in different locations. NFS has been always the easiest way to access the remote storages over a network. To accomplish this demo, we need two systems which Ubuntu installed and user with sudo permissions with a private network. We will install the ‘nfs-kernel’, which will be allowed us to share the directories on the server to share the files and folders. Below is the command to install the nfs package. $ sudo apt update $ sudo apt install nfs-kernel-server Reading package lists... Done Building dependency tree Reading state information... Done The following additional packages will be installed: keyutils libnfsidmap2 libpython-stdlib libpython2.7-minimal libpython2.7-stdlib libtirpc1 nfs-common python python-minimal python2.7 python2.7-minimal rpcbind Suggested packages: watchdog python-doc python-tk python2.7-doc binutils binfmt-support The following NEW packages will be installed: keyutils libnfsidmap2 libpython-stdlib libpython2.7-minimal libpython2.7-stdlib libtirpc1 nfs-common nfs-kernel-server python python-minimal python2.7 python2.7-minimal rpcbind 0 upgraded, 13 newly installed, 0 to remove and 98 not upgraded. Need to get 4,375 kB of archives. After this operation, 18.5 MB of additional disk s Selecting previously unselected package libnfsidmap2:amd64. (Reading database ... 56995 files and directories currently installed.) .. ... ... currently installed.) Processing triggers for ureadahead (0.100.0-19) ... Processing triggers for systemd (229-4ubuntu4) ... Setting up libnfsidmap2:amd64 (0.25-5) ... Setting up libpython2.7-stdlib:amd64 (2.7.12-1~16.04) ... Setting up python2.7 (2.7.12-1~16.04) ... Setting up libpython-stdlib:amd64 (2.7.11-1) ... Setting up python (2.7.11-1) ... Setting up libtirpc1:amd64 (0.2.5-1) ... Setting up keyutils (1.5.9-8ubuntu1) ... Setting up rpcbind (0.2.3-0.2) ... Setting up nfs-common (1:1.2.8-9ubuntu12) ... Creating config file /etc/idmapd.conf with new version Progress: [ 98%] [##########################################################] Adding system user `statd' (UID 110) ... Adding new user `statd' (UID 110) with group `nogroup' ... Not creating home directory `/var/lib/nfs'. nfs-utils.service is a disabled or a static unit, not starting it. Setting up nfs-kernel-server (1:1.2.8-9ubuntu12) ... Creating config file /etc/exports with new version Creating config file /etc/default/nfs-kernel-server with new version Processing triggers for libc-bin (2.23-0ubuntu3) ... Processing triggers for ureadahead (0.100.0-19) ...########################.] Processing triggers for systemd (229-4ubuntu4) ... We have to install the nfs packages on the client in general nfs-common ie., the package which provides the access to the NFS share folders from the server. $ sudo apt update $ sudo apt install nfs-common apt install nfs-common Reading package lists... Done Building dependency tree Reading state information... Done Suggested packages: watchdog The following NEW packages will be installed: nfs-common 0 upgraded, 1 newly installed, 0 to remove and 98 not upgraded. Need to get 185 kB of archives. After this operation, 734 kB of additional disk space will be used. Get:1 http://in.archive.ubuntu.com/ubuntu xenial/main amd64 nfs-common amd64 1:1 .2.8-9ubuntu12 [185 kB] Fetched 185 kB in 1s (126 kB/s) Selecting previously unselected package nfs-common. (Reading database ... 57864 files and directories currently installed.) Preparing to unpack .../nfs-common_1%3a1.2.8-9ubuntu12_amd64.deb ... Unpacking nfs-common (1:1.2.8-9ubuntu12) ... Processing triggers for ureadahead (0.100.0-19) ... Processing triggers for systemd (229-4ubuntu4) ... Setting up nfs-common (1:1.2.8-9ubuntu12) ... Here for demo purpose, we are going to share two folders to differentiate the configuration, setting, First one is with superuser permission and other with trusted users on the client system. In this example, we will create a general NFS mount that with the default configuration which is difficult for a user without any permissions on the client machine they can access and this can be used to create a shared space to store the project files in the folders. $ sudo mkdir /usr/nfs/common –p Change the folder permission, so that anybody can write in the folder $ sudo chown nobody:nogroup /usr/nfs/common And now try to access the folder from a client with the below command Before we mount any shared folder on the client, we needed to create a mount point on the client machine $ sudo mkdir /mnt/nfs/common $ sudo mount 192.168.1.25:/usr/nfs/common /mnt/nfs/common This will mount the NFS share on the server 192.168.1.25 on the client machine with /mnt/nfs/common is mounted at /mnt/nfs/common on the client machine and it can be accessed as a local folder. We will share user home directories stored on the server to access from the client, the access needed to conveniently manage the users. As we are seeing 2 types of NFS Share, let”s see how to configure the setting to match our requirements. Open /etc/exports file with an editor $ sudo vi /etc/exports # /etc/exports: the access control list for filesystems which may be exported # to NFS clients. See exports(5). # # Example for NFSv2 and NFSv3: # /srv/homes hostname1(rw,sync,no_subtree_check) hostname2(ro,sync,no_subtree_check) # # Example for NFSv4: # /srv/nfs4 gss/krb5i(rw,sync,fsid=0,crossmnt,no_subtree_check) # /srv/nfs4/homes gss/krb5i(rw,sync,no_subtree_check) Add below lines to the configuration file – /usr/nfs/common 192.168.1.100(rw,sync,no_subtree_check) /home 192.168.1.100(rw,sync,no_root_squash,no_subtree_check) Below is the explanation for each option we used in the above commands which we used. Rw -> This will allow client computers to read and write to the share. Sync -> This will allow the data to be written in the NFS before it applies to queries and It also increase consistent environment and will be stable. Nosubtreecheck -> This will prevent subtree checking, where if we enable this option, it will cause many problems if the client has opened the file. Norootsquash -> This will makes the NFS translation request from the root user for the client into a not –privileged users of the server, where it will also prevent the root account on the client from using the file system of the server as root. $ sudo systemctl restart nfs-kernel-server Before, we mount the share folders on the client, we needed to create a mount point and we will link the share folder from the NFS server to the local folders (mount points). $ mkdir /mnt/common $ mkdir /mnt/home $ sudo mount 192.168.1.100:/usr/nfs/common /mnt/common $ sudo mount 192.168.1.100:/home /mnt/home After we run the commands we will not verify that the NFS share folders are mounted correctly or not $ df –h Filesystem Size Used Avail Use% Mounted on udev 538M 0 538M 0% /dev tmpfs 249M 628K 249M 2% /run /dev/vda1 100G 10G 90G 10% / tmpfs 445M 0 445M 0% /dev/shm tmpfs 10.0M 0 10.0M 0% /run/lock tmpfs 245M 0 245M 0% /sys/fs/cgroup tmpfs 249M 0 249M 0% /run/user/0 192.168.1.100:/home 124G 11.28G 118.8G 9% /mnt/home 192.168.1.100:/usr/nfs/common 124G 11.28G 118.8G 9% /mnt/common As we can see that they both share are mounted and we can see them at the bottom, as they are mounted from the same server so we can see the same disk usage. We can mount the NFS share at the time of boot so that if we needed to connect the NFS share folders, we can directly access the folders at the mount points Open the /etc/fstab file and add the below lines. $ sudo vi /etc/fstab Add the below line at the bottom of the files . . . 192.168.1.100:/usr/nfs/common /mnt/general nfs auto,nofail,noatime,nolock,intr,tcp,actimeo=1800 0 0 192.168.1.100:/home /mnt/home nfs auto,nofail,noatime,nolock,intr,tcp,actimeo=1800 0 0 As if we do not want to use the folders, we can unmount the NFS share folders using the below commands $ sudo umount /mnt/common $ sudo umount /mnt/home In the above article setup and configure an NFS share on Ubuntu 16.04 with two different NFS mounts, one share is open anybody can read or write to the folder and other with restricted for users.
[ { "code": null, "e": 1500, "s": 1062, "text": "In this article, we will learn how to install NFS on Ubuntu 16.04Network File System (NFS) protocol and a filesystem which allows you to access the shared folders from the remote system or server and also allows you to mount as a remote directory on the servers. This allows you to share the storage space between different clients in different locations. NFS has been always the easiest way to access the remote storages over a network." }, { "code": null, "e": 1623, "s": 1500, "text": "To accomplish this demo, we need two systems which Ubuntu installed and user with sudo permissions with a private network." }, { "code": null, "e": 1802, "s": 1623, "text": "We will install the ‘nfs-kernel’, which will be allowed us to share the directories on the server to share the files and folders. Below is the command to install the nfs package." }, { "code": null, "e": 3974, "s": 1802, "text": "$ sudo apt update\n$ sudo apt install nfs-kernel-server\nReading package lists... Done\nBuilding dependency tree\nReading state information... Done\nThe following additional packages will be installed:\nkeyutils libnfsidmap2 libpython-stdlib libpython2.7-minimal\nlibpython2.7-stdlib libtirpc1 nfs-common python python-minimal python2.7\npython2.7-minimal rpcbind\nSuggested packages:\nwatchdog python-doc python-tk python2.7-doc binutils binfmt-support\nThe following NEW packages will be installed:\nkeyutils libnfsidmap2 libpython-stdlib libpython2.7-minimal\nlibpython2.7-stdlib libtirpc1 nfs-common nfs-kernel-server python\npython-minimal python2.7 python2.7-minimal rpcbind\n0 upgraded, 13 newly installed, 0 to remove and 98 not upgraded.\nNeed to get 4,375 kB of archives.\nAfter this operation, 18.5 MB of additional disk s\nSelecting previously unselected package libnfsidmap2:amd64.\n(Reading database ... 56995 files and directories currently installed.)\n..\n...\n...\ncurrently installed.)\nProcessing triggers for ureadahead (0.100.0-19) ...\nProcessing triggers for systemd (229-4ubuntu4) ...\nSetting up libnfsidmap2:amd64 (0.25-5) ...\nSetting up libpython2.7-stdlib:amd64 (2.7.12-1~16.04) ...\nSetting up python2.7 (2.7.12-1~16.04) ...\nSetting up libpython-stdlib:amd64 (2.7.11-1) ...\nSetting up python (2.7.11-1) ...\nSetting up libtirpc1:amd64 (0.2.5-1) ...\nSetting up keyutils (1.5.9-8ubuntu1) ...\nSetting up rpcbind (0.2.3-0.2) ...\nSetting up nfs-common (1:1.2.8-9ubuntu12) ...\nCreating config file /etc/idmapd.conf with new version\nProgress: [ 98%] [##########################################################]\nAdding system user `statd' (UID 110) ...\nAdding new user `statd' (UID 110) with group `nogroup' ...\nNot creating home directory `/var/lib/nfs'.\nnfs-utils.service is a disabled or a static unit, not starting it.\nSetting up nfs-kernel-server (1:1.2.8-9ubuntu12) ...\nCreating config file /etc/exports with new version\nCreating config file /etc/default/nfs-kernel-server with new version\nProcessing triggers for libc-bin (2.23-0ubuntu3) ...\nProcessing triggers for ureadahead (0.100.0-19) ...########################.]\nProcessing triggers for systemd (229-4ubuntu4) ..." }, { "code": null, "e": 4131, "s": 3974, "text": "We have to install the nfs packages on the client in general nfs-common ie., the package which provides the access to the NFS share folders from the server." }, { "code": null, "e": 5065, "s": 4131, "text": "$ sudo apt update\n$ sudo apt install nfs-common\napt install nfs-common\nReading package lists... Done\nBuilding dependency tree\nReading state information... Done\nSuggested packages:\nwatchdog\nThe following NEW packages will be installed:\nnfs-common\n0 upgraded, 1 newly installed, 0 to remove and 98 not upgraded.\nNeed to get 185 kB of archives.\nAfter this operation, 734 kB of additional disk space will be used.\nGet:1 http://in.archive.ubuntu.com/ubuntu xenial/main amd64 nfs-common amd64 1:1 .2.8-9ubuntu12 [185 kB]\nFetched 185 kB in 1s (126 kB/s)\nSelecting previously unselected package nfs-common.\n(Reading database ... 57864 files and directories currently installed.)\nPreparing to unpack .../nfs-common_1%3a1.2.8-9ubuntu12_amd64.deb ...\nUnpacking nfs-common (1:1.2.8-9ubuntu12) ...\nProcessing triggers for ureadahead (0.100.0-19) ...\nProcessing triggers for systemd (229-4ubuntu4) ...\nSetting up nfs-common (1:1.2.8-9ubuntu12) ..." }, { "code": null, "e": 5257, "s": 5065, "text": "Here for demo purpose, we are going to share two folders to differentiate the configuration, setting, First one is with superuser permission and other with trusted users on the client system." }, { "code": null, "e": 5526, "s": 5257, "text": "In this example, we will create a general NFS mount that with the default configuration which is difficult for a user without any permissions on the client machine they can access and this can be used to create a shared space to store the project files in the folders." }, { "code": null, "e": 5558, "s": 5526, "text": "$ sudo mkdir /usr/nfs/common –p" }, { "code": null, "e": 5628, "s": 5558, "text": "Change the folder permission, so that anybody can write in the folder" }, { "code": null, "e": 5672, "s": 5628, "text": "$ sudo chown nobody:nogroup /usr/nfs/common" }, { "code": null, "e": 5742, "s": 5672, "text": "And now try to access the folder from a client with the below command" }, { "code": null, "e": 5847, "s": 5742, "text": "Before we mount any shared folder on the client, we needed to create a mount point on the client machine" }, { "code": null, "e": 5934, "s": 5847, "text": "$ sudo mkdir /mnt/nfs/common\n$ sudo mount 192.168.1.25:/usr/nfs/common /mnt/nfs/common" }, { "code": null, "e": 6128, "s": 5934, "text": "This will mount the NFS share on the server 192.168.1.25 on the client machine with /mnt/nfs/common is mounted at /mnt/nfs/common on the client machine and it can be accessed as a local folder." }, { "code": null, "e": 6264, "s": 6128, "text": "We will share user home directories stored on the server to access from the client, the access needed to conveniently manage the users." }, { "code": null, "e": 6369, "s": 6264, "text": "As we are seeing 2 types of NFS Share, let”s see how to configure the setting to match our requirements." }, { "code": null, "e": 6407, "s": 6369, "text": "Open /etc/exports file with an editor" }, { "code": null, "e": 6802, "s": 6407, "text": "$ sudo vi /etc/exports\n# /etc/exports: the access control list for filesystems which may be exported\n# to NFS clients. See exports(5).\n#\n# Example for NFSv2 and NFSv3:\n# /srv/homes hostname1(rw,sync,no_subtree_check) hostname2(ro,sync,no_subtree_check)\n#\n# Example for NFSv4:\n# /srv/nfs4 gss/krb5i(rw,sync,fsid=0,crossmnt,no_subtree_check)\n# /srv/nfs4/homes gss/krb5i(rw,sync,no_subtree_check)\n" }, { "code": null, "e": 6846, "s": 6802, "text": "Add below lines to the configuration file –" }, { "code": null, "e": 6963, "s": 6846, "text": "/usr/nfs/common 192.168.1.100(rw,sync,no_subtree_check)\n/home 192.168.1.100(rw,sync,no_root_squash,no_subtree_check)" }, { "code": null, "e": 7049, "s": 6963, "text": "Below is the explanation for each option we used in the above commands which we used." }, { "code": null, "e": 7120, "s": 7049, "text": "Rw -> This will allow client computers to read and write to the share." }, { "code": null, "e": 7271, "s": 7120, "text": "Sync -> This will allow the data to be written in the NFS before it applies to queries and It also increase consistent environment and will be stable." }, { "code": null, "e": 7420, "s": 7271, "text": "Nosubtreecheck -> This will prevent subtree checking, where if we enable this option, it will cause many problems if the client has opened the file." }, { "code": null, "e": 7666, "s": 7420, "text": "Norootsquash -> This will makes the NFS translation request from the root user for the client into a not –privileged users of the server, where it will also prevent the root account on the client from using the file system of the server as root." }, { "code": null, "e": 7709, "s": 7666, "text": "$ sudo systemctl restart nfs-kernel-server" }, { "code": null, "e": 7884, "s": 7709, "text": "Before, we mount the share folders on the client, we needed to create a mount point and we will link the share folder from the NFS server to the local folders (mount points)." }, { "code": null, "e": 8020, "s": 7884, "text": "$ mkdir /mnt/common\n$ mkdir /mnt/home\n$ sudo mount 192.168.1.100:/usr/nfs/common /mnt/common\n$ sudo mount 192.168.1.100:/home /mnt/home" }, { "code": null, "e": 8121, "s": 8020, "text": "After we run the commands we will not verify that the NFS share folders are mounted correctly or not" }, { "code": null, "e": 8503, "s": 8121, "text": "$ df –h\nFilesystem Size Used Avail Use% Mounted on\nudev 538M 0 538M 0% /dev\ntmpfs 249M 628K 249M 2% /run\n/dev/vda1 100G 10G 90G 10% /\ntmpfs 445M 0 445M 0% /dev/shm\ntmpfs 10.0M 0 10.0M 0% /run/lock\ntmpfs 245M 0 245M 0% /sys/fs/cgroup\ntmpfs 249M 0 249M 0% /run/user/0\n192.168.1.100:/home 124G 11.28G 118.8G 9% /mnt/home\n192.168.1.100:/usr/nfs/common 124G 11.28G 118.8G 9% /mnt/common" }, { "code": null, "e": 8661, "s": 8503, "text": "As we can see that they both share are mounted and we can see them at the bottom, as they are mounted from the same server so we can see the same disk usage." }, { "code": null, "e": 8818, "s": 8661, "text": "We can mount the NFS share at the time of boot so that if we needed to connect the NFS share folders, we can directly access the folders at the mount points" }, { "code": null, "e": 8868, "s": 8818, "text": "Open the /etc/fstab file and add the below lines." }, { "code": null, "e": 8889, "s": 8868, "text": "$ sudo vi /etc/fstab" }, { "code": null, "e": 8935, "s": 8889, "text": "Add the below line at the bottom of the files" }, { "code": null, "e": 9128, "s": 8935, "text": ". . .\n192.168.1.100:/usr/nfs/common /mnt/general nfs auto,nofail,noatime,nolock,intr,tcp,actimeo=1800 0 0\n192.168.1.100:/home /mnt/home nfs auto,nofail,noatime,nolock,intr,tcp,actimeo=1800 0 0" }, { "code": null, "e": 9231, "s": 9128, "text": "As if we do not want to use the folders, we can unmount the NFS share folders using the below commands" }, { "code": null, "e": 9281, "s": 9231, "text": "$ sudo umount /mnt/common\n$ sudo umount /mnt/home" }, { "code": null, "e": 9477, "s": 9281, "text": "In the above article setup and configure an NFS share on Ubuntu 16.04 with two different NFS mounts, one share is open anybody can read or write to the folder and other with restricted for users." } ]