title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to display a float with two decimal places in Python?
You can use string formatting to format floating point numbers to a fixed width in Python.For example, if you want the decimal points to be aligned with width of 12 characters and 2 digits on the right of the decimal, you can use the following: >>>x = 12.35874 >>>print "{:12.2f}".format(x) 12.36 You can also achieve this result using string interpolation and formatting. For example: >>>x = 12.35874 >>>print "% 12.2f" % x 12.36
[ { "code": null, "e": 1307, "s": 1062, "text": "You can use string formatting to format floating point numbers to a fixed width in Python.For example, if you want the decimal points to be aligned with width of 12 characters and 2 digits on the right of the decimal, you can use the following:" }, { "code": null, "e": 1365, "s": 1307, "text": " >>>x = 12.35874\n>>>print \"{:12.2f}\".format(x)\n 12.36" }, { "code": null, "e": 1455, "s": 1365, "text": " You can also achieve this result using string interpolation and formatting. For example:" }, { "code": null, "e": 1505, "s": 1455, "text": ">>>x = 12.35874\n>>>print \"% 12.2f\" % x\n 12.36" } ]
How to get the size of a JavaScript object?
21 Jun, 2019 We can get size of java script object with the help of Object.keys() method. Syntax: Object.keys(object_name) object_name Return Value: an array of all the object’s own enumerable property keys. Approach-1:Create an object variable and assign values to itCreate an variable which shows the sizeCall the Object.keys(object-name).length and assign it to the variable (in step 2). Create an object variable and assign values to it Create an variable which shows the size Call the Object.keys(object-name).length and assign it to the variable (in step 2). Example-1: To get size of javascript object by Object.keys() method. <script>var object1= { "rajnish":"singh", "sanjeev":"sharma", "suraj":"agrahari", "yash":"khandelwal" };var count= Object.keys(object1).length;document.write(count);</script> Output: 4 Another way to get the size of the javascript object is: Approach-2:Create an object variable and assign values to itCreate an variable which shows the sizePass the object-name to Object.objsize which further enters to the function which calculates and returns the size and assign it to the variable. Create an object variable and assign values to it Create an variable which shows the size Pass the object-name to Object.objsize which further enters to the function which calculates and returns the size and assign it to the variable. <script>Object.objsize = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; var object1 = { "rajnish":"singh", "sanjeev":"sharma", "suraj":"agrahari", "yash":"khandelwal" }; var count = Object.objsize(object1);document.write(count); </script> Output: 4 JavaScript-Misc Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to append HTML code to a div using JavaScript ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jun, 2019" }, { "code": null, "e": 105, "s": 28, "text": "We can get size of java script object with the help of Object.keys() method." }, { "code": null, "e": 113, "s": 105, "text": "Syntax:" }, { "code": null, "e": 138, "s": 113, "text": "Object.keys(object_name)" }, { "code": null, "e": 150, "s": 138, "text": "object_name" }, { "code": null, "e": 223, "s": 150, "text": "Return Value: an array of all the object’s own enumerable property keys." }, { "code": null, "e": 406, "s": 223, "text": "Approach-1:Create an object variable and assign values to itCreate an variable which shows the sizeCall the Object.keys(object-name).length and assign it to the variable (in step 2)." }, { "code": null, "e": 456, "s": 406, "text": "Create an object variable and assign values to it" }, { "code": null, "e": 496, "s": 456, "text": "Create an variable which shows the size" }, { "code": null, "e": 580, "s": 496, "text": "Call the Object.keys(object-name).length and assign it to the variable (in step 2)." }, { "code": null, "e": 649, "s": 580, "text": "Example-1: To get size of javascript object by Object.keys() method." }, { "code": "<script>var object1= { \"rajnish\":\"singh\", \"sanjeev\":\"sharma\", \"suraj\":\"agrahari\", \"yash\":\"khandelwal\" };var count= Object.keys(object1).length;document.write(count);</script>", "e": 878, "s": 649, "text": null }, { "code": null, "e": 888, "s": 878, "text": "Output: 4" }, { "code": null, "e": 945, "s": 888, "text": "Another way to get the size of the javascript object is:" }, { "code": null, "e": 1189, "s": 945, "text": "Approach-2:Create an object variable and assign values to itCreate an variable which shows the sizePass the object-name to Object.objsize which further enters to the function which calculates and returns the size and assign it to the variable." }, { "code": null, "e": 1239, "s": 1189, "text": "Create an object variable and assign values to it" }, { "code": null, "e": 1279, "s": 1239, "text": "Create an variable which shows the size" }, { "code": null, "e": 1424, "s": 1279, "text": "Pass the object-name to Object.objsize which further enters to the function which calculates and returns the size and assign it to the variable." }, { "code": "<script>Object.objsize = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; var object1 = { \"rajnish\":\"singh\", \"sanjeev\":\"sharma\", \"suraj\":\"agrahari\", \"yash\":\"khandelwal\" }; var count = Object.objsize(object1);document.write(count); </script>", "e": 1834, "s": 1424, "text": null }, { "code": null, "e": 1844, "s": 1834, "text": "Output: 4" }, { "code": null, "e": 1860, "s": 1844, "text": "JavaScript-Misc" }, { "code": null, "e": 1867, "s": 1860, "text": "Picked" }, { "code": null, "e": 1878, "s": 1867, "text": "JavaScript" }, { "code": null, "e": 1895, "s": 1878, "text": "Web Technologies" }, { "code": null, "e": 1993, "s": 1895, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2054, "s": 1993, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2126, "s": 2054, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2166, "s": 2126, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2207, "s": 2166, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2259, "s": 2207, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 2292, "s": 2259, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2354, "s": 2292, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2415, "s": 2354, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2465, "s": 2415, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Matplotlib.axes.Axes.add_line() in Python
21 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.add_line() function in axes module of matplotlib library is used to add a Line2D to the axes’ lines; return the line. Syntax: Axes.add_line(self, line) Parameters: This method accepts the following parameters. line: This parameter is the Line2D. Return value: This method returns the line. Below examples illustrate the matplotlib.axes.Axes.add_line() function in matplotlib.axes: Example 1: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.lines as linesimport matplotlib.transforms as mtransformsimport matplotlib.text as mtext class GFGfun(lines.Line2D): def __init__(self, *args, **kwargs): self.text = mtext.Text(0, 0, '') lines.Line2D.__init__(self, *args, **kwargs) self.text.set_text(self.get_label()) def set_figure(self, figure): self.text.set_figure(figure) lines.Line2D.set_figure(self, figure) def set_axes(self, axes): self.text.set_axes(axes) lines.Line2D.set_axes(self, axes) def set_transform(self, transform): # 2 pixel offset texttrans = transform + mtransforms.Affine2D().translate(2, 2) self.text.set_transform(texttrans) lines.Line2D.set_transform(self, transform) def set_data(self, x, y): if len(x): self.text.set_position((x[-1], y[-1])) lines.Line2D.set_data(self, x, y) def draw(self, renderer): lines.Line2D.draw(self, renderer) self.text.draw(renderer) np.random.seed(10**7) fig, ax = plt.subplots()x, y = np.random.rand(2, 20)line = GFGfun(x, y, mfc ='green', ms = 12, label ='Label') line.text.set_color('green')line.text.set_fontsize(16) ax.add_line(line) fig.suptitle('matplotlib.axes.Axes.add_line()\ function Example\n\n', fontweight ="bold")plt.show() Output: Example 2: # Implementation of matplotlib functionimport randomimport matplotlib.lines as linesimport matplotlib.patches as patchesimport matplotlib.text as textimport matplotlib.collections as collectionsfrom basic_units import cm, inchimport numpy as npimport matplotlib.pyplot as plt fig, ax = plt.subplots()ax.xaxis.set_units(cm)ax.yaxis.set_units(cm) # Fixing random state for reproducibilitynp.random.seed(19680801) if 0: # test a line collection # Not supported at present. verts = [] for i in range(10): # a random line segment in inches verts.append(zip(*inch * 10 * np.random.rand(2, random.randint(2, 15)))) lc = collections.LineCollection(verts, axes = ax) ax.add_collection(lc) # test a plain-ol-lineline = lines.Line2D([0 * cm, 1.5 * cm], [0 * cm, 2.5 * cm], lw = 2, color ='green', axes = ax, alpha = 0.7) ax.add_line(line) ax.grid(True) fig.suptitle('matplotlib.axes.Axes.add_line() \function Example\n\n', fontweight ="bold")plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2020" }, { "code": null, "e": 328, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 455, "s": 328, "text": "The Axes.add_line() function in axes module of matplotlib library is used to add a Line2D to the axes’ lines; return the line." }, { "code": null, "e": 489, "s": 455, "text": "Syntax: Axes.add_line(self, line)" }, { "code": null, "e": 547, "s": 489, "text": "Parameters: This method accepts the following parameters." }, { "code": null, "e": 583, "s": 547, "text": "line: This parameter is the Line2D." }, { "code": null, "e": 627, "s": 583, "text": "Return value: This method returns the line." }, { "code": null, "e": 718, "s": 627, "text": "Below examples illustrate the matplotlib.axes.Axes.add_line() function in matplotlib.axes:" }, { "code": null, "e": 729, "s": 718, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.lines as linesimport matplotlib.transforms as mtransformsimport matplotlib.text as mtext class GFGfun(lines.Line2D): def __init__(self, *args, **kwargs): self.text = mtext.Text(0, 0, '') lines.Line2D.__init__(self, *args, **kwargs) self.text.set_text(self.get_label()) def set_figure(self, figure): self.text.set_figure(figure) lines.Line2D.set_figure(self, figure) def set_axes(self, axes): self.text.set_axes(axes) lines.Line2D.set_axes(self, axes) def set_transform(self, transform): # 2 pixel offset texttrans = transform + mtransforms.Affine2D().translate(2, 2) self.text.set_transform(texttrans) lines.Line2D.set_transform(self, transform) def set_data(self, x, y): if len(x): self.text.set_position((x[-1], y[-1])) lines.Line2D.set_data(self, x, y) def draw(self, renderer): lines.Line2D.draw(self, renderer) self.text.draw(renderer) np.random.seed(10**7) fig, ax = plt.subplots()x, y = np.random.rand(2, 20)line = GFGfun(x, y, mfc ='green', ms = 12, label ='Label') line.text.set_color('green')line.text.set_fontsize(16) ax.add_line(line) fig.suptitle('matplotlib.axes.Axes.add_line()\\ function Example\\n\\n', fontweight =\"bold\")plt.show()", "e": 2154, "s": 729, "text": null }, { "code": null, "e": 2162, "s": 2154, "text": "Output:" }, { "code": null, "e": 2173, "s": 2162, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport randomimport matplotlib.lines as linesimport matplotlib.patches as patchesimport matplotlib.text as textimport matplotlib.collections as collectionsfrom basic_units import cm, inchimport numpy as npimport matplotlib.pyplot as plt fig, ax = plt.subplots()ax.xaxis.set_units(cm)ax.yaxis.set_units(cm) # Fixing random state for reproducibilitynp.random.seed(19680801) if 0: # test a line collection # Not supported at present. verts = [] for i in range(10): # a random line segment in inches verts.append(zip(*inch * 10 * np.random.rand(2, random.randint(2, 15)))) lc = collections.LineCollection(verts, axes = ax) ax.add_collection(lc) # test a plain-ol-lineline = lines.Line2D([0 * cm, 1.5 * cm], [0 * cm, 2.5 * cm], lw = 2, color ='green', axes = ax, alpha = 0.7) ax.add_line(line) ax.grid(True) fig.suptitle('matplotlib.axes.Axes.add_line() \\function Example\\n\\n', fontweight =\"bold\")plt.show()", "e": 3263, "s": 2173, "text": null }, { "code": null, "e": 3271, "s": 3263, "text": "Output:" }, { "code": null, "e": 3289, "s": 3271, "text": "Python-matplotlib" }, { "code": null, "e": 3296, "s": 3289, "text": "Python" } ]
SQL | Join (Inner, Left, Right and Full Joins)
17 May, 2022 SQL Join statement is used to combine data or rows from two or more tables based on a common field between them. Different types of Joins are as follows: INNER JOIN LEFT JOIN RIGHT JOIN FULL JOIN Consider the two tables below: Student StudentCourse Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. The simplest Join is INNER JOIN. The INNER JOIN keyword selects all rows from both the tables as long as the condition is satisfied. This keyword will create the result-set by combining all rows from both the tables where the condition satisfies i.e value of the common field will be the same. Syntax: SELECT table1.column1,table1.column2,table2.column1,.... FROM table1 INNER JOIN table2 ON table1.matching_column = table2.matching_column; table1: First table. table2: Second table matching_column: Column common to both the tables. Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER JOIN. Example Queries(INNER JOIN) This query will show the names and age of students enrolled in different courses. SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student INNER JOIN StudentCourse ON Student.ROLL_NO = StudentCourse.ROLL_NO; Output: This join returns all the rows of the table on the left side of the join and matches rows for the table on the right side of the join. For the rows for which there is no matching row on the right side, the result-set will contain null. LEFT JOIN is also known as LEFT OUTER JOIN. Syntax: SELECT table1.column1,table1.column2,table2.column1,.... FROM table1 LEFT JOIN table2 ON table1.matching_column = table2.matching_column; table1: First table. table2: Second table matching_column: Column common to both the tables. Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are the same. Example Queries(LEFT JOIN): SELECT Student.NAME,StudentCourse.COURSE_ID FROM Student LEFT JOIN StudentCourse ON StudentCourse.ROLL_NO = Student.ROLL_NO; Output: RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the right side of the join and matching rows for the table on the left side of the join. For the rows for which there is no matching row on the left side, the result-set will contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN. Syntax: SELECT table1.column1,table1.column2,table2.column1,.... FROM table1 RIGHT JOIN table2 ON table1.matching_column = table2.matching_column; table1: First table. table2: Second table matching_column: Column common to both the tables. Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN, both are the same. Example Queries(RIGHT JOIN): SELECT Student.NAME,StudentCourse.COURSE_ID FROM Student RIGHT JOIN StudentCourse ON StudentCourse.ROLL_NO = Student.ROLL_NO; Output: FULL JOIN creates the result-set by combining results of both LEFT JOIN and RIGHT JOIN. The result-set will contain all the rows from both tables. For the rows for which there is no matching, the result-set will contain NULL values. Syntax: SELECT table1.column1,table1.column2,table2.column1,.... FROM table1 FULL JOIN table2 ON table1.matching_column = table2.matching_column; table1: First table. table2: Second table matching_column: Column common to both the tables. Example Queries(FULL JOIN): SELECT Student.NAME,StudentCourse.COURSE_ID FROM Student FULL JOIN StudentCourse ON StudentCourse.ROLL_NO = Student.ROLL_NO; Output: NAME COURSE_ID HARSH 1 PRATIK 2 RIYANKA 2 DEEP 3 SAPTARHI 1 DHANRAJ NULL ROHIT NULL NIRAJ NULL NULL 4 NULL 5 NULL 4 Inner Join (Top 50 SQL Interview Questions)| GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersInner Join (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 / 6:52•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=zGYLUogRe-M" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Left JOIN (Video) Right JOIN (Video) Full JOIN (Video) SQL | JOIN (Cartesian Join, Self Join) This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. dt_kanha navinpatnacitynav DBMS-Join SQL-Clauses-Operators Articles DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Group Communication in distributed Systems Recursive Practice Problems with Solutions Little and Big Endian Mystery How to write a Pseudo Code? SQL | Views Normal Forms in DBMS ACID Properties in DBMS SQL query to find second highest salary? Introduction of DBMS (Database Management System) | Set 1 Introduction of B-Tree
[ { "code": null, "e": 52, "s": 24, "text": "\n17 May, 2022" }, { "code": null, "e": 207, "s": 52, "text": "SQL Join statement is used to combine data or rows from two or more tables based on a common field between them. Different types of Joins are as follows: " }, { "code": null, "e": 218, "s": 207, "text": "INNER JOIN" }, { "code": null, "e": 228, "s": 218, "text": "LEFT JOIN" }, { "code": null, "e": 239, "s": 228, "text": "RIGHT JOIN" }, { "code": null, "e": 249, "s": 239, "text": "FULL JOIN" }, { "code": null, "e": 281, "s": 249, "text": "Consider the two tables below: " }, { "code": null, "e": 289, "s": 281, "text": "Student" }, { "code": null, "e": 306, "s": 291, "text": "StudentCourse " }, { "code": null, "e": 315, "s": 306, "text": "Chapters" }, { "code": null, "e": 342, "s": 315, "text": "descriptions off, selected" }, { "code": null, "e": 392, "s": 342, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 415, "s": 392, "text": "captions off, selected" }, { "code": null, "e": 423, "s": 415, "text": "English" }, { "code": null, "e": 447, "s": 423, "text": "This is a modal window." }, { "code": null, "e": 516, "s": 447, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 538, "s": 516, "text": "End of dialog window." }, { "code": null, "e": 572, "s": 538, "text": "The simplest Join is INNER JOIN. " }, { "code": null, "e": 834, "s": 572, "text": "The INNER JOIN keyword selects all rows from both the tables as long as the condition is satisfied. This keyword will create the result-set by combining all rows from both the tables where the condition satisfies i.e value of the common field will be the same. " }, { "code": null, "e": 843, "s": 834, "text": "Syntax: " }, { "code": null, "e": 1078, "s": 843, "text": "SELECT table1.column1,table1.column2,table2.column1,....\nFROM table1 \nINNER JOIN table2\nON table1.matching_column = table2.matching_column;\n\n\ntable1: First table.\ntable2: Second table\nmatching_column: Column common to both the tables." }, { "code": null, "e": 1159, "s": 1078, "text": "Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER JOIN. " }, { "code": null, "e": 1187, "s": 1159, "text": "Example Queries(INNER JOIN)" }, { "code": null, "e": 1271, "s": 1187, "text": "This query will show the names and age of students enrolled in different courses. " }, { "code": null, "e": 1411, "s": 1271, "text": "SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student\nINNER JOIN StudentCourse\nON Student.ROLL_NO = StudentCourse.ROLL_NO;" }, { "code": null, "e": 1421, "s": 1411, "text": "Output: " }, { "code": null, "e": 1701, "s": 1421, "text": "This join returns all the rows of the table on the left side of the join and matches rows for the table on the right side of the join. For the rows for which there is no matching row on the right side, the result-set will contain null. LEFT JOIN is also known as LEFT OUTER JOIN." }, { "code": null, "e": 1710, "s": 1701, "text": "Syntax: " }, { "code": null, "e": 1944, "s": 1710, "text": "SELECT table1.column1,table1.column2,table2.column1,....\nFROM table1 \nLEFT JOIN table2\nON table1.matching_column = table2.matching_column;\n\n\ntable1: First table.\ntable2: Second table\nmatching_column: Column common to both the tables." }, { "code": null, "e": 2023, "s": 1944, "text": "Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are the same." }, { "code": null, "e": 2052, "s": 2023, "text": "Example Queries(LEFT JOIN): " }, { "code": null, "e": 2179, "s": 2052, "text": "SELECT Student.NAME,StudentCourse.COURSE_ID \nFROM Student\nLEFT JOIN StudentCourse \nON StudentCourse.ROLL_NO = Student.ROLL_NO;" }, { "code": null, "e": 2188, "s": 2179, "text": "Output: " }, { "code": null, "e": 2507, "s": 2188, "text": "RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the right side of the join and matching rows for the table on the left side of the join. For the rows for which there is no matching row on the left side, the result-set will contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN. " }, { "code": null, "e": 2516, "s": 2507, "text": "Syntax: " }, { "code": null, "e": 2751, "s": 2516, "text": "SELECT table1.column1,table1.column2,table2.column1,....\nFROM table1 \nRIGHT JOIN table2\nON table1.matching_column = table2.matching_column;\n\n\ntable1: First table.\ntable2: Second table\nmatching_column: Column common to both the tables." }, { "code": null, "e": 2833, "s": 2751, "text": "Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN, both are the same. " }, { "code": null, "e": 2864, "s": 2835, "text": "Example Queries(RIGHT JOIN):" }, { "code": null, "e": 2992, "s": 2864, "text": "SELECT Student.NAME,StudentCourse.COURSE_ID \nFROM Student\nRIGHT JOIN StudentCourse \nON StudentCourse.ROLL_NO = Student.ROLL_NO;" }, { "code": null, "e": 3001, "s": 2992, "text": "Output: " }, { "code": null, "e": 3234, "s": 3001, "text": "FULL JOIN creates the result-set by combining results of both LEFT JOIN and RIGHT JOIN. The result-set will contain all the rows from both tables. For the rows for which there is no matching, the result-set will contain NULL values." }, { "code": null, "e": 3244, "s": 3234, "text": "Syntax: " }, { "code": null, "e": 3479, "s": 3244, "text": "SELECT table1.column1,table1.column2,table2.column1,....\nFROM table1 \nFULL JOIN table2\nON table1.matching_column = table2.matching_column;\n\n\ntable1: First table.\ntable2: Second table\nmatching_column: Column common to both the tables. " }, { "code": null, "e": 3508, "s": 3479, "text": "Example Queries(FULL JOIN): " }, { "code": null, "e": 3635, "s": 3508, "text": "SELECT Student.NAME,StudentCourse.COURSE_ID \nFROM Student\nFULL JOIN StudentCourse \nON StudentCourse.ROLL_NO = Student.ROLL_NO;" }, { "code": null, "e": 3645, "s": 3635, "text": "Output: " }, { "code": null, "e": 3650, "s": 3645, "text": "NAME" }, { "code": null, "e": 3660, "s": 3650, "text": "COURSE_ID" }, { "code": null, "e": 3666, "s": 3660, "text": "HARSH" }, { "code": null, "e": 3668, "s": 3666, "text": "1" }, { "code": null, "e": 3675, "s": 3668, "text": "PRATIK" }, { "code": null, "e": 3677, "s": 3675, "text": "2" }, { "code": null, "e": 3685, "s": 3677, "text": "RIYANKA" }, { "code": null, "e": 3687, "s": 3685, "text": "2" }, { "code": null, "e": 3692, "s": 3687, "text": "DEEP" }, { "code": null, "e": 3694, "s": 3692, "text": "3" }, { "code": null, "e": 3703, "s": 3694, "text": "SAPTARHI" }, { "code": null, "e": 3705, "s": 3703, "text": "1" }, { "code": null, "e": 3713, "s": 3705, "text": "DHANRAJ" }, { "code": null, "e": 3718, "s": 3713, "text": "NULL" }, { "code": null, "e": 3724, "s": 3718, "text": "ROHIT" }, { "code": null, "e": 3729, "s": 3724, "text": "NULL" }, { "code": null, "e": 3735, "s": 3729, "text": "NIRAJ" }, { "code": null, "e": 3740, "s": 3735, "text": "NULL" }, { "code": null, "e": 3745, "s": 3740, "text": "NULL" }, { "code": null, "e": 3747, "s": 3745, "text": "4" }, { "code": null, "e": 3752, "s": 3747, "text": "NULL" }, { "code": null, "e": 3754, "s": 3752, "text": "5" }, { "code": null, "e": 3759, "s": 3754, "text": "NULL" }, { "code": null, "e": 3761, "s": 3759, "text": "4" }, { "code": null, "e": 4663, "s": 3761, "text": "Inner Join (Top 50 SQL Interview Questions)| GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersInner Join (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 / 6:52•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=zGYLUogRe-M\" 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": 4758, "s": 4663, "text": "Left JOIN (Video) Right JOIN (Video) Full JOIN (Video) SQL | JOIN (Cartesian Join, Self Join) " }, { "code": null, "e": 5055, "s": 4758, "text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 5183, "s": 5055, "text": "Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above." }, { "code": null, "e": 5192, "s": 5183, "text": "dt_kanha" }, { "code": null, "e": 5210, "s": 5192, "text": "navinpatnacitynav" }, { "code": null, "e": 5220, "s": 5210, "text": "DBMS-Join" }, { "code": null, "e": 5242, "s": 5220, "text": "SQL-Clauses-Operators" }, { "code": null, "e": 5251, "s": 5242, "text": "Articles" }, { "code": null, "e": 5256, "s": 5251, "text": "DBMS" }, { "code": null, "e": 5260, "s": 5256, "text": "SQL" }, { "code": null, "e": 5265, "s": 5260, "text": "DBMS" }, { "code": null, "e": 5269, "s": 5265, "text": "SQL" }, { "code": null, "e": 5367, "s": 5269, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5410, "s": 5367, "text": "Group Communication in distributed Systems" }, { "code": null, "e": 5453, "s": 5410, "text": "Recursive Practice Problems with Solutions" }, { "code": null, "e": 5483, "s": 5453, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 5511, "s": 5483, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 5523, "s": 5511, "text": "SQL | Views" }, { "code": null, "e": 5544, "s": 5523, "text": "Normal Forms in DBMS" }, { "code": null, "e": 5568, "s": 5544, "text": "ACID Properties in DBMS" }, { "code": null, "e": 5609, "s": 5568, "text": "SQL query to find second highest salary?" }, { "code": null, "e": 5667, "s": 5609, "text": "Introduction of DBMS (Database Management System) | Set 1" } ]
Check if linked list is sorted (Iterative and Recursive)
08 Nov, 2021 Given a Linked List, task is to check whether the Linked List is sorted in Descending order or not? Examples : Input : 8 -> 7 -> 5 -> 2 -> 1 Output : Yes Explanation : In given linked list, starting from head, 8 > 7 > 5 > 2 > 1. So, it is sorted in reverse order Input : 24 -> 12 -> 9 -> 11 -> 8 -> 2 Output : No Iterative Approach : Traverse the linked list from head to end. For every newly encountered element, check node -> data > node -> next -> data. If True, do same for each node else return 0 and Print “No”. C++ Java Python3 C# Javascript // C++ program to check Linked List is sorted// in descending order or not#include <bits/stdc++.h>using namespace std; /* Linked list node */struct Node{ int data; struct Node* next;}; // function to Check Linked List is// sorted in descending order or notbool isSortedDesc(struct Node *head){ if (head == NULL) return true; // Traverse the list till last node and return // false if a node is smaller than or equal // its next. for (Node *t=head; t->next != NULL; t=t->next) if (t->data <= t->next->data) return false; return true;} Node *newNode(int data){ Node *temp = new Node; temp->next = NULL; temp->data = data;} // Driver program to test aboveint main(){ struct Node *head = newNode(7); head->next = newNode(5); head->next->next = newNode(4); head->next->next->next = newNode(3); isSortedDesc(head) ? cout << "Yes" : cout << "No"; return 0;} // Java program to check Linked List is sorted// in descending order or notclass GFG{ /* Linked list node */static class Node{ int data; Node next;}; // function to Check Linked List is// sorted in descending order or notstatic boolean isSortedDesc(Node head){ if (head == null) return true; // Traverse the list till last node and return // false if a node is smaller than or equal // its next. for (Node t = head; t.next != null; t = t.next) if (t.data <= t.next.data) return false; return true;} static Node newNode(int data){ Node temp = new Node(); temp.next = null; temp.data = data; return temp;} // Driver Codepublic static void main(String[] args){ Node head = newNode(7); head.next = newNode(5); head.next.next = newNode(4); head.next.next.next = newNode(3); if(isSortedDesc(head)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed by 29AjayKumar # Python3 program to check Linked List is sorted# in descending order or not''' Linked list Node ''' class Node: def __init__(self, data): self.data = data; self.next = next; # function to Check Linked List is# sorted in descending order or notdef isSortedDesc(head): if (head == None): return True; # Traverse the list till last Node and return # False if a Node is smaller than or equal # its next. while(head.next != None): t = head; if (t.data <= t.next.data): return False; head = head.next return True; def newNode(data): temp = Node(0); temp.next = None; temp.data = data; return temp; # Driver Codeif __name__ == '__main__': head = newNode(7); head.next = newNode(5); head.next.next = newNode(4); head.next.next.next = newNode(3); if (isSortedDesc(head)): print("Yes"); else: print("No"); # This code is contributed by 29AjayKumar // C# program to check Linked List is sorted// in descending order or notusing System; class GFG{ /* Linked list node */public class Node{ public int data; public Node next;}; // function to Check Linked List is// sorted in descending order or notstatic bool isSortedDesc(Node head){ if (head == null) return true; // Traverse the list till last node and // return false if a node is smaller than // or equal to its next. for (Node t = head; t.next != null; t = t.next) if (t.data <= t.next.data) return false; return true;} static Node newNode(int data){ Node temp = new Node(); temp.next = null; temp.data = data; return temp;} // Driver Codepublic static void Main(String[] args){ Node head = newNode(7); head.next = newNode(5); head.next.next = newNode(4); head.next.next.next = newNode(3); if(isSortedDesc(head)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by Rajput-Ji <script> // JavaScript program to recursively check Linked List // is sorted in descending order or not /* Linked list node */ class Node { constructor() { this.data = 0; this.next = null; } } // function to Check Linked List is // sorted in descending order or not function isSortedDesc(head) { // Base cases if (head == null || head.next == null) return true; // Check first two nodes and recursively // check remaining. return head.data > head.next.data && isSortedDesc(head.next); } function newNode(data) { var temp = new Node(); temp.next = null; temp.data = data; return temp; } // Driver code var head = newNode(7); head.next = newNode(5); head.next.next = newNode(4); head.next.next.next = newNode(3); if (isSortedDesc(head) == true) document.write("Yes"); else document.write("No"); </script> Yes Time Complexity : O(N), where N is the length of linked list. Recursive Approach : Check Recursively that node -> data > node -> next -> data, If not, return 0 that is our terminated condition to come out from recursion else Call Check_List Function Recursively for next node. C++ Java Python3 C# Javascript // C++ program to recursively check Linked List// is sorted in descending order or not#include <bits/stdc++.h>using namespace std; /* Linked list node */struct Node{ int data; struct Node* next;}; // function to Check Linked List is// sorted in descending order or notbool isSortedDesc(struct Node *head){ // Base cases if (head == NULL || head->next == NULL) return true; // Check first two nodes and recursively // check remaining. return (head->data > head->next->data && isSortedDesc(head->next));} Node *newNode(int data){ Node *temp = new Node; temp->next = NULL; temp->data = data;} // Driver program to test aboveint main(){ struct Node *head = newNode(7); head->next = newNode(5); head->next->next = newNode(4); head->next->next->next = newNode(3); isSortedDesc(head) ? cout << "Yes" : cout << "No"; return 0;} // Java program to recursively check Linked List// is sorted in descending order or notclass GfG { /* Linked list node */static class Node{ int data; Node next;} // function to Check Linked List is// sorted in descending order or notstatic boolean isSortedDesc(Node head){ // Base cases if (head == null || head.next == null) return true; // Check first two nodes and recursively // check remaining. return (head.data > head.next.data && isSortedDesc(head.next));} static Node newNode(int data){Node temp = new Node();temp.next = null;temp.data = data;return temp;} // Driver program to test abovepublic static void main(String[] args){ Node head = newNode(7); head.next = newNode(5); head.next.next = newNode(4); head.next.next.next = newNode(3); if(isSortedDesc(head) == true) System.out.println("Yes"); else System.out.println("No"); }} # Python3 program to recursively check# Linked List is sorted in descending# order or not # Linked list nodeclass Node: def __init__(self, data): self.data = data self.next = None # Function to Check Linked List is# sorted in descending order or notdef isSortedDesc(head): # Base cases if (head == None or head.next == None): return True # Check first two nodes and recursively # check remaining. return (head.data > head.next.data and isSortedDesc(head.next)) def newNode(data): temp = Node(data) return temp # Driver codeif __name__=="__main__": head = newNode(7) head.next = newNode(5) head.next.next = newNode(4) head.next.next.next = newNode(3) if isSortedDesc(head): print("Yes") else: print("No") # This code is contributed by rutvik_56 // C# program to recursively check Linked List// is sorted in descending order or notusing System; class GfG{ /* Linked list node */public class Node{ public int data; public Node next;} // function to Check Linked List is// sorted in descending order or notstatic bool isSortedDesc(Node head){ // Base cases if (head == null || head.next == null) return true; // Check first two nodes and recursively // check remaining. return (head.data > head.next.data && isSortedDesc(head.next));} static Node newNode(int data){ Node temp = new Node(); temp.next = null; temp.data = data; return temp;} // Driver codepublic static void Main(String[] args){ Node head = newNode(7); head.next = newNode(5); head.next.next = newNode(4); head.next.next.next = newNode(3); if(isSortedDesc(head) == true) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code contributed by Rajput-Ji <script> // Javascript program to recursively check Linked List // is sorted in descending order or not class Node { constructor(data) { this.next = null; this.data = data; } } // function to Check Linked List is // sorted in descending order or not function isSortedDesc(head) { // Base cases if (head == null || head.next == null) return true; // Check first two nodes and recursively // check remaining. return (head.data > head.next.data && isSortedDesc(head.next)); } function newNode(data) { let temp = new Node(data); return temp; } let head = newNode(7); head.next = newNode(5); head.next.next = newNode(4); head.next.next.next = newNode(3); if(isSortedDesc(head) == true) document.write("Yes"); else document.write("No"); // This code is contributed by divyeshrabadiya07.</script> Yes prerna saini Rajput-Ji 29AjayKumar rutvik_56 rdtank divyeshrabadiya07 Linked-List-Sorting C++ Linked List Recursion Sorting Technical Scripter Linked List Recursion Sorting CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Set in C++ Standard Template Library (STL) Priority Queue in C++ Standard Template Library (STL) vector erase() and clear() in C++ Substring in C++ Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node)
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Nov, 2021" }, { "code": null, "e": 155, "s": 54, "text": "Given a Linked List, task is to check whether the Linked List is sorted in Descending order or not? " }, { "code": null, "e": 168, "s": 155, "text": "Examples : " }, { "code": null, "e": 373, "s": 168, "text": "Input : 8 -> 7 -> 5 -> 2 -> 1\nOutput : Yes\nExplanation :\nIn given linked list, starting from head,\n8 > 7 > 5 > 2 > 1. So, it is sorted in reverse order\n\nInput : 24 -> 12 -> 9 -> 11 -> 8 -> 2\nOutput : No" }, { "code": null, "e": 580, "s": 373, "text": "Iterative Approach : Traverse the linked list from head to end. For every newly encountered element, check node -> data > node -> next -> data. If True, do same for each node else return 0 and Print “No”. " }, { "code": null, "e": 584, "s": 580, "text": "C++" }, { "code": null, "e": 589, "s": 584, "text": "Java" }, { "code": null, "e": 597, "s": 589, "text": "Python3" }, { "code": null, "e": 600, "s": 597, "text": "C#" }, { "code": null, "e": 611, "s": 600, "text": "Javascript" }, { "code": "// C++ program to check Linked List is sorted// in descending order or not#include <bits/stdc++.h>using namespace std; /* Linked list node */struct Node{ int data; struct Node* next;}; // function to Check Linked List is// sorted in descending order or notbool isSortedDesc(struct Node *head){ if (head == NULL) return true; // Traverse the list till last node and return // false if a node is smaller than or equal // its next. for (Node *t=head; t->next != NULL; t=t->next) if (t->data <= t->next->data) return false; return true;} Node *newNode(int data){ Node *temp = new Node; temp->next = NULL; temp->data = data;} // Driver program to test aboveint main(){ struct Node *head = newNode(7); head->next = newNode(5); head->next->next = newNode(4); head->next->next->next = newNode(3); isSortedDesc(head) ? cout << \"Yes\" : cout << \"No\"; return 0;}", "e": 1572, "s": 611, "text": null }, { "code": "// Java program to check Linked List is sorted// in descending order or notclass GFG{ /* Linked list node */static class Node{ int data; Node next;}; // function to Check Linked List is// sorted in descending order or notstatic boolean isSortedDesc(Node head){ if (head == null) return true; // Traverse the list till last node and return // false if a node is smaller than or equal // its next. for (Node t = head; t.next != null; t = t.next) if (t.data <= t.next.data) return false; return true;} static Node newNode(int data){ Node temp = new Node(); temp.next = null; temp.data = data; return temp;} // Driver Codepublic static void main(String[] args){ Node head = newNode(7); head.next = newNode(5); head.next.next = newNode(4); head.next.next.next = newNode(3); if(isSortedDesc(head)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is contributed by 29AjayKumar", "e": 2566, "s": 1572, "text": null }, { "code": "# Python3 program to check Linked List is sorted# in descending order or not''' Linked list Node ''' class Node: def __init__(self, data): self.data = data; self.next = next; # function to Check Linked List is# sorted in descending order or notdef isSortedDesc(head): if (head == None): return True; # Traverse the list till last Node and return # False if a Node is smaller than or equal # its next. while(head.next != None): t = head; if (t.data <= t.next.data): return False; head = head.next return True; def newNode(data): temp = Node(0); temp.next = None; temp.data = data; return temp; # Driver Codeif __name__ == '__main__': head = newNode(7); head.next = newNode(5); head.next.next = newNode(4); head.next.next.next = newNode(3); if (isSortedDesc(head)): print(\"Yes\"); else: print(\"No\"); # This code is contributed by 29AjayKumar", "e": 3525, "s": 2566, "text": null }, { "code": "// C# program to check Linked List is sorted// in descending order or notusing System; class GFG{ /* Linked list node */public class Node{ public int data; public Node next;}; // function to Check Linked List is// sorted in descending order or notstatic bool isSortedDesc(Node head){ if (head == null) return true; // Traverse the list till last node and // return false if a node is smaller than // or equal to its next. for (Node t = head; t.next != null; t = t.next) if (t.data <= t.next.data) return false; return true;} static Node newNode(int data){ Node temp = new Node(); temp.next = null; temp.data = data; return temp;} // Driver Codepublic static void Main(String[] args){ Node head = newNode(7); head.next = newNode(5); head.next.next = newNode(4); head.next.next.next = newNode(3); if(isSortedDesc(head)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by Rajput-Ji", "e": 4558, "s": 3525, "text": null }, { "code": "<script> // JavaScript program to recursively check Linked List // is sorted in descending order or not /* Linked list node */ class Node { constructor() { this.data = 0; this.next = null; } } // function to Check Linked List is // sorted in descending order or not function isSortedDesc(head) { // Base cases if (head == null || head.next == null) return true; // Check first two nodes and recursively // check remaining. return head.data > head.next.data && isSortedDesc(head.next); } function newNode(data) { var temp = new Node(); temp.next = null; temp.data = data; return temp; } // Driver code var head = newNode(7); head.next = newNode(5); head.next.next = newNode(4); head.next.next.next = newNode(3); if (isSortedDesc(head) == true) document.write(\"Yes\"); else document.write(\"No\"); </script>", "e": 5558, "s": 4558, "text": null }, { "code": null, "e": 5562, "s": 5558, "text": "Yes" }, { "code": null, "e": 5626, "s": 5564, "text": "Time Complexity : O(N), where N is the length of linked list." }, { "code": null, "e": 5842, "s": 5626, "text": "Recursive Approach : Check Recursively that node -> data > node -> next -> data, If not, return 0 that is our terminated condition to come out from recursion else Call Check_List Function Recursively for next node. " }, { "code": null, "e": 5846, "s": 5842, "text": "C++" }, { "code": null, "e": 5851, "s": 5846, "text": "Java" }, { "code": null, "e": 5859, "s": 5851, "text": "Python3" }, { "code": null, "e": 5862, "s": 5859, "text": "C#" }, { "code": null, "e": 5873, "s": 5862, "text": "Javascript" }, { "code": "// C++ program to recursively check Linked List// is sorted in descending order or not#include <bits/stdc++.h>using namespace std; /* Linked list node */struct Node{ int data; struct Node* next;}; // function to Check Linked List is// sorted in descending order or notbool isSortedDesc(struct Node *head){ // Base cases if (head == NULL || head->next == NULL) return true; // Check first two nodes and recursively // check remaining. return (head->data > head->next->data && isSortedDesc(head->next));} Node *newNode(int data){ Node *temp = new Node; temp->next = NULL; temp->data = data;} // Driver program to test aboveint main(){ struct Node *head = newNode(7); head->next = newNode(5); head->next->next = newNode(4); head->next->next->next = newNode(3); isSortedDesc(head) ? cout << \"Yes\" : cout << \"No\"; return 0;}", "e": 6796, "s": 5873, "text": null }, { "code": "// Java program to recursively check Linked List// is sorted in descending order or notclass GfG { /* Linked list node */static class Node{ int data; Node next;} // function to Check Linked List is// sorted in descending order or notstatic boolean isSortedDesc(Node head){ // Base cases if (head == null || head.next == null) return true; // Check first two nodes and recursively // check remaining. return (head.data > head.next.data && isSortedDesc(head.next));} static Node newNode(int data){Node temp = new Node();temp.next = null;temp.data = data;return temp;} // Driver program to test abovepublic static void main(String[] args){ Node head = newNode(7); head.next = newNode(5); head.next.next = newNode(4); head.next.next.next = newNode(3); if(isSortedDesc(head) == true) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}", "e": 7706, "s": 6796, "text": null }, { "code": "# Python3 program to recursively check# Linked List is sorted in descending# order or not # Linked list nodeclass Node: def __init__(self, data): self.data = data self.next = None # Function to Check Linked List is# sorted in descending order or notdef isSortedDesc(head): # Base cases if (head == None or head.next == None): return True # Check first two nodes and recursively # check remaining. return (head.data > head.next.data and isSortedDesc(head.next)) def newNode(data): temp = Node(data) return temp # Driver codeif __name__==\"__main__\": head = newNode(7) head.next = newNode(5) head.next.next = newNode(4) head.next.next.next = newNode(3) if isSortedDesc(head): print(\"Yes\") else: print(\"No\") # This code is contributed by rutvik_56", "e": 8581, "s": 7706, "text": null }, { "code": "// C# program to recursively check Linked List// is sorted in descending order or notusing System; class GfG{ /* Linked list node */public class Node{ public int data; public Node next;} // function to Check Linked List is// sorted in descending order or notstatic bool isSortedDesc(Node head){ // Base cases if (head == null || head.next == null) return true; // Check first two nodes and recursively // check remaining. return (head.data > head.next.data && isSortedDesc(head.next));} static Node newNode(int data){ Node temp = new Node(); temp.next = null; temp.data = data; return temp;} // Driver codepublic static void Main(String[] args){ Node head = newNode(7); head.next = newNode(5); head.next.next = newNode(4); head.next.next.next = newNode(3); if(isSortedDesc(head) == true) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code contributed by Rajput-Ji", "e": 9567, "s": 8581, "text": null }, { "code": "<script> // Javascript program to recursively check Linked List // is sorted in descending order or not class Node { constructor(data) { this.next = null; this.data = data; } } // function to Check Linked List is // sorted in descending order or not function isSortedDesc(head) { // Base cases if (head == null || head.next == null) return true; // Check first two nodes and recursively // check remaining. return (head.data > head.next.data && isSortedDesc(head.next)); } function newNode(data) { let temp = new Node(data); return temp; } let head = newNode(7); head.next = newNode(5); head.next.next = newNode(4); head.next.next.next = newNode(3); if(isSortedDesc(head) == true) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by divyeshrabadiya07.</script>", "e": 10575, "s": 9567, "text": null }, { "code": null, "e": 10579, "s": 10575, "text": "Yes" }, { "code": null, "e": 10594, "s": 10581, "text": "prerna saini" }, { "code": null, "e": 10604, "s": 10594, "text": "Rajput-Ji" }, { "code": null, "e": 10616, "s": 10604, "text": "29AjayKumar" }, { "code": null, "e": 10626, "s": 10616, "text": "rutvik_56" }, { "code": null, "e": 10633, "s": 10626, "text": "rdtank" }, { "code": null, "e": 10651, "s": 10633, "text": "divyeshrabadiya07" }, { "code": null, "e": 10671, "s": 10651, "text": "Linked-List-Sorting" }, { "code": null, "e": 10675, "s": 10671, "text": "C++" }, { "code": null, "e": 10687, "s": 10675, "text": "Linked List" }, { "code": null, "e": 10697, "s": 10687, "text": "Recursion" }, { "code": null, "e": 10705, "s": 10697, "text": "Sorting" }, { "code": null, "e": 10724, "s": 10705, "text": "Technical Scripter" }, { "code": null, "e": 10736, "s": 10724, "text": "Linked List" }, { "code": null, "e": 10746, "s": 10736, "text": "Recursion" }, { "code": null, "e": 10754, "s": 10746, "text": "Sorting" }, { "code": null, "e": 10758, "s": 10754, "text": "CPP" }, { "code": null, "e": 10856, "s": 10758, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10883, "s": 10856, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 10926, "s": 10883, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 10980, "s": 10926, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 11014, "s": 10980, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 11031, "s": 11014, "text": "Substring in C++" }, { "code": null, "e": 11066, "s": 11031, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 11105, "s": 11066, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 11127, "s": 11105, "text": "Reverse a linked list" }, { "code": null, "e": 11175, "s": 11127, "text": "Stack Data Structure (Introduction and Program)" } ]
Hadoop – mrjob Python Library For MapReduce With Example
17 Mar, 2021 mrjob is the famous python library for MapReduce developed by YELP. The library helps developers to write MapReduce code using a Python Programming language. Developers can test the MapReduce Python code written with mrjob locally on their system or on the cloud using Amazon EMR(Elastic MapReduce). Amazon EMR is a cloud-based web service provided by Amazon Web Services for Big Data purposes. mrjob is currently an active Framework for MapReduce programming or Hadoop Streaming jobs and has good document support for Hadoop with python than any other library or framework currently available. With mrjob, we can write code for Mapper and Reducer in a single class. In case we don’t have Hadoop installed then also we can test the mrjob program in our local system environment. mrjob supports Python 2.7/3.4+. Install mrjob in your system pip install mrjob # for python3 use pip3 So let’s solve one demo problem to understand how to use this library with Hadoop. Aim: Count the number of occurrence of words from a text file using python mrjob Step 1: Create a text file with the name data.txt and add some content to it. touch data.txt //used to create file in linux nano data.txt // nano is a command line editor in linux cat data.txt // used to see the inner content of file Step 2: Create a file with the name CountWord.py at the location where your data.txt file is available. touch CountWord.py // create the python file with name CountWord Step 3: Add the below code to this python file. Python3 from mrjob.job import MRJobclass Count(MRJob): """ The below mapper() function defines the mapper for MapReduce and takes key value argument and generates the output in tuple format . The mapper below is splitting the line and generating a word with its own count i.e. 1 """ def mapper(self, _, line): for word in line.split(): yield(word, 1) """ The below reducer() is aggregating the result according to their key and producing the output in a key-value format with its total count""" def reducer(self, word, counts): yield(word, sum(counts)) """the below 2 lines are ensuring the execution of mrjob, the program will notexecute without them""" if __name__ == '__main__': Count.run() Below is the image Of My CountWord.py file. Step 4: Run the python File in your local machine as shown below to test it is working fine or not(Note: I am using python3). python CountWord.py data.txt We can observe that it is working fine. By default, mrjob produces the output to the STDOUT i.e. on the terminal. Now once we have verified that the Mapper and Reducer are working fine. Then we can deploy this code to the Hadoop cluster or Amazon EMR and can use it. When we want to run the mrjob code on Hadoop or Amazon EMR we have to specify the -r/–runner option with the command. The different choices available to run mrjob are explained below. Syntax: python <mrjob-pythonfile> -r hadoop <hdfs-path> Command: Send your data.txt to HDFS with the help of the below command (NOTE: I have already sent data.txt to the Countcontent folder on HDFS). hdfs dfs -put /home/dikshant/Desktop/data.txt / Run the below command to run mrjob on Hadoop. python CountWord.py -r hadoop hdfs:///content/data.txt From the above image, we can clearly see that we have successfully executed mrjob on the text file available on our HDFS. Hadoop Hadoop Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create Table in Hive? What is Hadoop Streaming? What is Schema On Read and Schema On Write in Hadoop? MapReduce - Understanding With Real-Life Example Apache Hive Import and Export Data using SQOOP Hadoop - HDFS (Hadoop Distributed File System) How to Install Single Node Cluster Hadoop on Windows? Hive - Alter Table Difference Between Hadoop 2.x vs Hadoop 3.x
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Mar, 2021" }, { "code": null, "e": 840, "s": 28, "text": "mrjob is the famous python library for MapReduce developed by YELP. The library helps developers to write MapReduce code using a Python Programming language. Developers can test the MapReduce Python code written with mrjob locally on their system or on the cloud using Amazon EMR(Elastic MapReduce). Amazon EMR is a cloud-based web service provided by Amazon Web Services for Big Data purposes. mrjob is currently an active Framework for MapReduce programming or Hadoop Streaming jobs and has good document support for Hadoop with python than any other library or framework currently available. With mrjob, we can write code for Mapper and Reducer in a single class. In case we don’t have Hadoop installed then also we can test the mrjob program in our local system environment. mrjob supports Python 2.7/3.4+." }, { "code": null, "e": 869, "s": 840, "text": "Install mrjob in your system" }, { "code": null, "e": 922, "s": 869, "text": "pip install mrjob # for python3 use pip3\n" }, { "code": null, "e": 1005, "s": 922, "text": "So let’s solve one demo problem to understand how to use this library with Hadoop." }, { "code": null, "e": 1086, "s": 1005, "text": "Aim: Count the number of occurrence of words from a text file using python mrjob" }, { "code": null, "e": 1164, "s": 1086, "text": "Step 1: Create a text file with the name data.txt and add some content to it." }, { "code": null, "e": 1389, "s": 1164, "text": "touch data.txt //used to create file in linux\n\nnano data.txt // nano is a command line editor in linux\n\ncat data.txt // used to see the inner content of file \n" }, { "code": null, "e": 1493, "s": 1389, "text": "Step 2: Create a file with the name CountWord.py at the location where your data.txt file is available." }, { "code": null, "e": 1576, "s": 1493, "text": "touch CountWord.py // create the python file with name CountWord \n" }, { "code": null, "e": 1624, "s": 1576, "text": "Step 3: Add the below code to this python file." }, { "code": null, "e": 1632, "s": 1624, "text": "Python3" }, { "code": "from mrjob.job import MRJobclass Count(MRJob): \"\"\" The below mapper() function defines the mapper for MapReduce and takes key value argument and generates the output in tuple format . The mapper below is splitting the line and generating a word with its own count i.e. 1 \"\"\" def mapper(self, _, line): for word in line.split(): yield(word, 1) \"\"\" The below reducer() is aggregating the result according to their key and producing the output in a key-value format with its total count\"\"\" def reducer(self, word, counts): yield(word, sum(counts)) \"\"\"the below 2 lines are ensuring the execution of mrjob, the program will notexecute without them\"\"\" if __name__ == '__main__': Count.run()", "e": 2394, "s": 1632, "text": null }, { "code": null, "e": 2438, "s": 2394, "text": "Below is the image Of My CountWord.py file." }, { "code": null, "e": 2564, "s": 2438, "text": "Step 4: Run the python File in your local machine as shown below to test it is working fine or not(Note: I am using python3)." }, { "code": null, "e": 2594, "s": 2564, "text": "python CountWord.py data.txt\n" }, { "code": null, "e": 2708, "s": 2594, "text": "We can observe that it is working fine. By default, mrjob produces the output to the STDOUT i.e. on the terminal." }, { "code": null, "e": 3046, "s": 2708, "text": "Now once we have verified that the Mapper and Reducer are working fine. Then we can deploy this code to the Hadoop cluster or Amazon EMR and can use it. When we want to run the mrjob code on Hadoop or Amazon EMR we have to specify the -r/–runner option with the command. The different choices available to run mrjob are explained below." }, { "code": null, "e": 3056, "s": 3046, "text": "Syntax: " }, { "code": null, "e": 3105, "s": 3056, "text": "python <mrjob-pythonfile> -r hadoop <hdfs-path>\n" }, { "code": null, "e": 3114, "s": 3105, "text": "Command:" }, { "code": null, "e": 3249, "s": 3114, "text": "Send your data.txt to HDFS with the help of the below command (NOTE: I have already sent data.txt to the Countcontent folder on HDFS)." }, { "code": null, "e": 3298, "s": 3249, "text": "hdfs dfs -put /home/dikshant/Desktop/data.txt /\n" }, { "code": null, "e": 3344, "s": 3298, "text": "Run the below command to run mrjob on Hadoop." }, { "code": null, "e": 3400, "s": 3344, "text": "python CountWord.py -r hadoop hdfs:///content/data.txt\n" }, { "code": null, "e": 3523, "s": 3400, "text": "From the above image, we can clearly see that we have successfully executed mrjob on the text file available on our HDFS. " }, { "code": null, "e": 3530, "s": 3523, "text": "Hadoop" }, { "code": null, "e": 3537, "s": 3530, "text": "Hadoop" }, { "code": null, "e": 3635, "s": 3537, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3664, "s": 3635, "text": "How to Create Table in Hive?" }, { "code": null, "e": 3690, "s": 3664, "text": "What is Hadoop Streaming?" }, { "code": null, "e": 3744, "s": 3690, "text": "What is Schema On Read and Schema On Write in Hadoop?" }, { "code": null, "e": 3793, "s": 3744, "text": "MapReduce - Understanding With Real-Life Example" }, { "code": null, "e": 3805, "s": 3793, "text": "Apache Hive" }, { "code": null, "e": 3840, "s": 3805, "text": "Import and Export Data using SQOOP" }, { "code": null, "e": 3887, "s": 3840, "text": "Hadoop - HDFS (Hadoop Distributed File System)" }, { "code": null, "e": 3941, "s": 3887, "text": "How to Install Single Node Cluster Hadoop on Windows?" }, { "code": null, "e": 3960, "s": 3941, "text": "Hive - Alter Table" } ]
Program to convert centimeter into meter and kilometer
28 Apr, 2021 Given length in centimeter, the task is to convert it into meter and kilometer. Examples : Input: Length in centimeter = 1000 Output: Length in meter = 10 m Length in kilometer = 0.01 km Input: Length in centimeter =6540 Output: Length in meter = 65.4 m Length in kilometer = 0.0654 km Formula to be used: 1m = 100cm 1km = 100000cm C++ Java Python3 C# PHP Javascript // C++ program to convert centimeter// into meter and kilometer#include <bits/stdc++.h>using namespace std;int main(){ float cm, meter, kilometer; cm = 1000; // Converting centimeter into meter // and kilometer meter = cm / 100.0; kilometer = cm / 100000.0; cout << "Length in meter = " << meter << "m" << "\n"; cout << "Length in Kilometer = " << kilometer << "km" << "\n"; return 0;} // Java program to convert// centimeter into meter// and kilometerimport java.io.*; class GFG{ public static void main (String[] args) { double cm, meter, kilometer; cm = 1000; // Converting centimeter // into meter and kilometer meter = cm / 100.0; kilometer = cm / 100000.0; System.out.println("Length in meter = " + meter + "m"); System.out.println("Length in Kilometer = " + kilometer + "km"); }} // This code is contributed by anuj_67. # Python3 program to convert# centimeter into meter# and kilometercm = 1000; # Converting centimeter# into meter and kilometermeter = cm / 100.0;kilometer = cm / 100000.0; # Driver Codeprint("Length in meter = " , meter , "m");print("Length in Kilometer = ", kilometer , "km"); # This code is contributed# by mits // C# program to convert// centimeter into meter// and kilometerusing System; class GFG{ // Driver Codestatic public void Main (){ double cm, meter, kilometer; cm = 1000; // Converting centimeter // into meter and kilometer meter = cm / 100.0; kilometer = cm / 100000.0; Console.WriteLine("Length in " + "meter = " + meter + "m"); Console.WriteLine("Length in " + "Kilometer = " + kilometer + "km");}} // This code is contributed// by ajit. <?php// PHP program to convert// centimeter into meter// and kilometer $cm; $meter; $kilometer;$cm = 1000; // Converting centimeter into// meter and kilometer$meter = $cm / 100.0;$kilometer = $cm / 100000.0; echo "Length in meter = " , $meter ,"m" , "\n"; echo "Length in Kilometer = " , $kilometer , "km" ,"\n"; // This code is contributed by anuj_67.?> <script> // Javascript program to convert centimeter// into meter and kilometerlet cm, meter, kilometer;cm = 1000; // Converting centimeter into meter// and kilometermeter = cm / 100.0;kilometer = cm / 100000.0; document.write("Length in meter = " + meter + "m" + "</br>"); document.write("Length in Kilometer = " + kilometer + "km" + "</br>"); // This code is contributed by jana_sayantan </script> Output: Length in meter = 10 m Length in kilometer = 0.01 km vt_m jit_t Mithun Kumar jana_sayantan Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Apr, 2021" }, { "code": null, "e": 108, "s": 28, "text": "Given length in centimeter, the task is to convert it into meter and kilometer." }, { "code": null, "e": 121, "s": 108, "text": "Examples : " }, { "code": null, "e": 217, "s": 121, "text": "Input: Length in centimeter = 1000 Output: Length in meter = 10 m Length in kilometer = 0.01 km" }, { "code": null, "e": 318, "s": 217, "text": "Input: Length in centimeter =6540 Output: Length in meter = 65.4 m Length in kilometer = 0.0654 km " }, { "code": null, "e": 340, "s": 318, "text": "Formula to be used: " }, { "code": null, "e": 366, "s": 340, "text": "1m = 100cm\n1km = 100000cm" }, { "code": null, "e": 370, "s": 366, "text": "C++" }, { "code": null, "e": 375, "s": 370, "text": "Java" }, { "code": null, "e": 383, "s": 375, "text": "Python3" }, { "code": null, "e": 386, "s": 383, "text": "C#" }, { "code": null, "e": 390, "s": 386, "text": "PHP" }, { "code": null, "e": 401, "s": 390, "text": "Javascript" }, { "code": "// C++ program to convert centimeter// into meter and kilometer#include <bits/stdc++.h>using namespace std;int main(){ float cm, meter, kilometer; cm = 1000; // Converting centimeter into meter // and kilometer meter = cm / 100.0; kilometer = cm / 100000.0; cout << \"Length in meter = \" << meter << \"m\" << \"\\n\"; cout << \"Length in Kilometer = \" << kilometer << \"km\" << \"\\n\"; return 0;}", "e": 834, "s": 401, "text": null }, { "code": "// Java program to convert// centimeter into meter// and kilometerimport java.io.*; class GFG{ public static void main (String[] args) { double cm, meter, kilometer; cm = 1000; // Converting centimeter // into meter and kilometer meter = cm / 100.0; kilometer = cm / 100000.0; System.out.println(\"Length in meter = \" + meter + \"m\"); System.out.println(\"Length in Kilometer = \" + kilometer + \"km\"); }} // This code is contributed by anuj_67.", "e": 1433, "s": 834, "text": null }, { "code": "# Python3 program to convert# centimeter into meter# and kilometercm = 1000; # Converting centimeter# into meter and kilometermeter = cm / 100.0;kilometer = cm / 100000.0; # Driver Codeprint(\"Length in meter = \" , meter , \"m\");print(\"Length in Kilometer = \", kilometer , \"km\"); # This code is contributed# by mits", "e": 1773, "s": 1433, "text": null }, { "code": "// C# program to convert// centimeter into meter// and kilometerusing System; class GFG{ // Driver Codestatic public void Main (){ double cm, meter, kilometer; cm = 1000; // Converting centimeter // into meter and kilometer meter = cm / 100.0; kilometer = cm / 100000.0; Console.WriteLine(\"Length in \" + \"meter = \" + meter + \"m\"); Console.WriteLine(\"Length in \" + \"Kilometer = \" + kilometer + \"km\");}} // This code is contributed// by ajit.", "e": 2327, "s": 1773, "text": null }, { "code": "<?php// PHP program to convert// centimeter into meter// and kilometer $cm; $meter; $kilometer;$cm = 1000; // Converting centimeter into// meter and kilometer$meter = $cm / 100.0;$kilometer = $cm / 100000.0; echo \"Length in meter = \" , $meter ,\"m\" , \"\\n\"; echo \"Length in Kilometer = \" , $kilometer , \"km\" ,\"\\n\"; // This code is contributed by anuj_67.?>", "e": 2695, "s": 2327, "text": null }, { "code": "<script> // Javascript program to convert centimeter// into meter and kilometerlet cm, meter, kilometer;cm = 1000; // Converting centimeter into meter// and kilometermeter = cm / 100.0;kilometer = cm / 100000.0; document.write(\"Length in meter = \" + meter + \"m\" + \"</br>\"); document.write(\"Length in Kilometer = \" + kilometer + \"km\" + \"</br>\"); // This code is contributed by jana_sayantan </script>", "e": 3123, "s": 2695, "text": null }, { "code": null, "e": 3132, "s": 3123, "text": "Output: " }, { "code": null, "e": 3187, "s": 3132, "text": " Length in meter = 10 m\n Length in kilometer = 0.01 km" }, { "code": null, "e": 3194, "s": 3189, "text": "vt_m" }, { "code": null, "e": 3200, "s": 3194, "text": "jit_t" }, { "code": null, "e": 3213, "s": 3200, "text": "Mithun Kumar" }, { "code": null, "e": 3227, "s": 3213, "text": "jana_sayantan" }, { "code": null, "e": 3240, "s": 3227, "text": "Mathematical" }, { "code": null, "e": 3259, "s": 3240, "text": "School Programming" }, { "code": null, "e": 3272, "s": 3259, "text": "Mathematical" } ]
How to customize a button to set text and color in Android?
This example demonstrates how do I customize a button to set text and color 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"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:background="#c0c0c0" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/customBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:padding="4dp" android:textStyle="bold" android:textSize="24sp"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Button; public class MainActivity extends AppCompatActivity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.customBtn); button.setText("Red Color Button"); button.setTextColor(Color.parseColor("#ff0000")); } } 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.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from 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": 1275, "s": 1187, "text": "This example demonstrates how do I customize a button to set text and color in android." }, { "code": null, "e": 1404, "s": 1275, "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": 1469, "s": 1404, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2063, "s": 1469, "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:background=\"#c0c0c0\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/customBtn\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:padding=\"4dp\"\n android:textStyle=\"bold\"\n android:textSize=\"24sp\"/>\n </RelativeLayout>" }, { "code": null, "e": 2120, "s": 2063, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2635, "s": 2120, "text": "import android.graphics.Color;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.Button;\npublic class MainActivity extends AppCompatActivity {\n Button button;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n button = findViewById(R.id.customBtn);\n button.setText(\"Red Color Button\");\n button.setTextColor(Color.parseColor(\"#ff0000\"));\n }\n}" }, { "code": null, "e": 2690, "s": 2635, "text": "Step 4 - Add the following code to androidManifest.xml" }, { "code": null, "e": 3360, "s": 2690, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3707, "s": 3360, "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 –" } ]
How to recursively iterate a nested Python dictionary?
Given below is a nested directory object D1={1: {2: {3: 4, 5: 6}, 3: {4: 5, 6: 7}}, 2: {3: {4: 5}, 4: {6: 7}}} Following recursive function is called repetitively if the value component of each item in directory is a directory itself. def iterdict(d): for k,v in d.items(): if isinstance(v, dict): iterdict(v) else: print (k,":",v) iterdict(D1) When the initial dictionary object is passed to this function, all the key-value pairs are traversed. The output is: 3 4 5 6 4 5 6 7 4 5 6 7
[ { "code": null, "e": 1228, "s": 1187, "text": "Given below is a nested directory object" }, { "code": null, "e": 1298, "s": 1228, "text": "D1={1: {2: {3: 4, 5: 6}, 3: {4: 5, 6: 7}}, 2: {3: {4: 5}, 4: {6: 7}}}" }, { "code": null, "e": 1422, "s": 1298, "text": "Following recursive function is called repetitively if the value component of each item in directory is a directory itself." }, { "code": null, "e": 1583, "s": 1422, "text": "def iterdict(d):\n for k,v in d.items(): \n if isinstance(v, dict):\n iterdict(v)\n else: \n print (k,\":\",v)\n\niterdict(D1)" }, { "code": null, "e": 1700, "s": 1583, "text": "When the initial dictionary object is passed to this function, all the key-value pairs are traversed. The output is:" }, { "code": null, "e": 1724, "s": 1700, "text": "3 4\n5 6\n4 5\n6 7\n4 5\n6 7" } ]
How to Set Java SDK Path in Android Studio?
16 Jun, 2021 The Java SDK for Android is a sophisticated suite of tools for managing, monitoring, profiling, and debugging Java code written in Android Studio. But sometimes as software is unpredictable you might be caught in an error that Android Studio stopped compiling projects and says that it can’t locate the 1.7.0_21 folder. Well, this is exactly what is referred to as a missing Java SDK Path. There are several methods that can help you resolve this issue, the ones which have the highest score in fixing this problem are mentioned below: Navigate to File > Project Structure > SDK Location. Upon navigating there you will find that a tab named “JDK Location”, select that and then you can set the JDK path for the current project on which you’re working. Image I. Setting Project SDK location in 4.2 & + Chances are that you might be rocking an older version of Android Studio, if yes then Navigate to File > Project Structure > [Platform Settings] > SDKs You’ll then need to either update your current SDK setup to make use of the new directory or create a new directory and then adjust the settings in your project to make use of the new directory. This will make it applicable to the present project. Sometimes only updating your SDKs won’t allow you to compile projects just because the SDK has lived its life and requires an update to itself. In that scenario, you’ll need to recreate the configurations from 0. Navigate to Project Structure > Platform Settings > SDKs and click the “+” button.Go to your Android SDK folder and select “Choose” on the pop-up.A new pop-up window will open, asking which SDK and JDK you’d want to use. Select any Android SDK and the JDK 1.7. Navigate to Project Structure > Platform Settings > SDKs and click the “+” button. Go to your Android SDK folder and select “Choose” on the pop-up. A new pop-up window will open, asking which SDK and JDK you’d want to use. Select any Android SDK and the JDK 1.7. Note: Change your Project SDK to the one you just established under Project Structure > Project Settings > Project. The name of the SDK should now include the new Java version that you installed. If you want to be a Geek and the above methods are just too much GUI for you, you might want to handle the SDK path using the terminal. In order to achieve that using the command line, follow the below commands in the Android Studio’s Terminal C:\Program Files\Android\Android Studio\jre\bin>java -version openjdk version "1.8.0_76-release" OpenJDK Runtime Environment (build 1.8.0_76-release-b03) OpenJDK 64-Bit Server VM (build 25.76-b03, mixed mode) then C:\Program Files\Android\Android Studio\jre\oldjre\ and just like that, you’ve achieved the desired result Note: the ‘oldjre‘ here refers to your old JRE path If you are on Android Version 3.2 or older then you’ll be having the option of using the embedded JDK & SDK for your project and that is one of the optimal ways you can fix this issue as Android Studio will handle the management of the services in the Backend! Navigate to File > Project Structure > JDK Location and Checkmark the box saying “Use embedded JDK (recommended)”. Image II. Checking the Recommended JDK Location If all the above-mentioned ways didn’t work out for you, the best you can do is to get the SDK path of another Android Studio Project and then providing that path to your particular project (as in Method #1) Press Ctrl (Command on Mac) + Alt + Shift + S Then in the SDK Location tab, you will find your SDK Location, just copy it and paste it in the SDK Location as mentioned in Method #1. Android-Studio Picked Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components How to Communicate Between Fragments in Android? Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Flutter - Stack Widget Activity Lifecycle in Android with Demo App Introduction to Android Development Fragment Lifecycle in Android
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jun, 2021" }, { "code": null, "e": 419, "s": 28, "text": "The Java SDK for Android is a sophisticated suite of tools for managing, monitoring, profiling, and debugging Java code written in Android Studio. But sometimes as software is unpredictable you might be caught in an error that Android Studio stopped compiling projects and says that it can’t locate the 1.7.0_21 folder. Well, this is exactly what is referred to as a missing Java SDK Path. " }, { "code": null, "e": 565, "s": 419, "text": "There are several methods that can help you resolve this issue, the ones which have the highest score in fixing this problem are mentioned below:" }, { "code": null, "e": 782, "s": 565, "text": "Navigate to File > Project Structure > SDK Location. Upon navigating there you will find that a tab named “JDK Location”, select that and then you can set the JDK path for the current project on which you’re working." }, { "code": null, "e": 831, "s": 782, "text": "Image I. Setting Project SDK location in 4.2 & +" }, { "code": null, "e": 917, "s": 831, "text": "Chances are that you might be rocking an older version of Android Studio, if yes then" }, { "code": null, "e": 983, "s": 917, "text": "Navigate to File > Project Structure > [Platform Settings] > SDKs" }, { "code": null, "e": 1231, "s": 983, "text": "You’ll then need to either update your current SDK setup to make use of the new directory or create a new directory and then adjust the settings in your project to make use of the new directory. This will make it applicable to the present project." }, { "code": null, "e": 1444, "s": 1231, "text": "Sometimes only updating your SDKs won’t allow you to compile projects just because the SDK has lived its life and requires an update to itself. In that scenario, you’ll need to recreate the configurations from 0." }, { "code": null, "e": 1705, "s": 1444, "text": "Navigate to Project Structure > Platform Settings > SDKs and click the “+” button.Go to your Android SDK folder and select “Choose” on the pop-up.A new pop-up window will open, asking which SDK and JDK you’d want to use. Select any Android SDK and the JDK 1.7." }, { "code": null, "e": 1788, "s": 1705, "text": "Navigate to Project Structure > Platform Settings > SDKs and click the “+” button." }, { "code": null, "e": 1853, "s": 1788, "text": "Go to your Android SDK folder and select “Choose” on the pop-up." }, { "code": null, "e": 1968, "s": 1853, "text": "A new pop-up window will open, asking which SDK and JDK you’d want to use. Select any Android SDK and the JDK 1.7." }, { "code": null, "e": 2164, "s": 1968, "text": "Note: Change your Project SDK to the one you just established under Project Structure > Project Settings > Project. The name of the SDK should now include the new Java version that you installed." }, { "code": null, "e": 2408, "s": 2164, "text": "If you want to be a Geek and the above methods are just too much GUI for you, you might want to handle the SDK path using the terminal. In order to achieve that using the command line, follow the below commands in the Android Studio’s Terminal" }, { "code": null, "e": 2617, "s": 2408, "text": "C:\\Program Files\\Android\\Android Studio\\jre\\bin>java -version\nopenjdk version \"1.8.0_76-release\"\nOpenJDK Runtime Environment (build 1.8.0_76-release-b03)\nOpenJDK 64-Bit Server VM (build 25.76-b03, mixed mode)" }, { "code": null, "e": 2622, "s": 2617, "text": "then" }, { "code": null, "e": 2674, "s": 2622, "text": "C:\\Program Files\\Android\\Android Studio\\jre\\oldjre\\" }, { "code": null, "e": 2729, "s": 2674, "text": "and just like that, you’ve achieved the desired result" }, { "code": null, "e": 2781, "s": 2729, "text": "Note: the ‘oldjre‘ here refers to your old JRE path" }, { "code": null, "e": 3042, "s": 2781, "text": "If you are on Android Version 3.2 or older then you’ll be having the option of using the embedded JDK & SDK for your project and that is one of the optimal ways you can fix this issue as Android Studio will handle the management of the services in the Backend!" }, { "code": null, "e": 3157, "s": 3042, "text": "Navigate to File > Project Structure > JDK Location and Checkmark the box saying “Use embedded JDK (recommended)”." }, { "code": null, "e": 3205, "s": 3157, "text": "Image II. Checking the Recommended JDK Location" }, { "code": null, "e": 3413, "s": 3205, "text": "If all the above-mentioned ways didn’t work out for you, the best you can do is to get the SDK path of another Android Studio Project and then providing that path to your particular project (as in Method #1)" }, { "code": null, "e": 3459, "s": 3413, "text": "Press Ctrl (Command on Mac) + Alt + Shift + S" }, { "code": null, "e": 3595, "s": 3459, "text": "Then in the SDK Location tab, you will find your SDK Location, just copy it and paste it in the SDK Location as mentioned in Method #1." }, { "code": null, "e": 3610, "s": 3595, "text": "Android-Studio" }, { "code": null, "e": 3617, "s": 3610, "text": "Picked" }, { "code": null, "e": 3625, "s": 3617, "text": "Android" }, { "code": null, "e": 3633, "s": 3625, "text": "Android" }, { "code": null, "e": 3731, "s": 3633, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3800, "s": 3731, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 3832, "s": 3800, "text": "Android SDK and it's Components" }, { "code": null, "e": 3881, "s": 3832, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 3920, "s": 3881, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 3962, "s": 3920, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 4013, "s": 3962, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 4036, "s": 4013, "text": "Flutter - Stack Widget" }, { "code": null, "e": 4080, "s": 4036, "text": "Activity Lifecycle in Android with Demo App" }, { "code": null, "e": 4116, "s": 4080, "text": "Introduction to Android Development" } ]
SpiderFoot – A Automate OSINT Framework in Kali Linux
20 Apr, 2021 Spiderfoot is a free and open-source tool available on Github. This tool is a framework written in the python programming language. You must have python installed in your Kali Linux operating system to use this framework. Spiderfoot is used for reconnaissance. Spiderfoot uses different modules for information gathering. Spiderfoot is capable enough to gather information about the target host through active and passive scanning options available on the Spiderfoot framework. In the Spiderfoot framework different scanning options and modules available to set and scan the target host. Spiderfoot is an Open Source Intelligence and Information Gathering Tool. Spiderfoot is capable of doing everything almost you need for reconnaissance as per your need. Spiderfoot works as an open-source tool intelligence tool. It integrates with just about every data source available and utilizes a range of methods for data analysis, making that data easy to navigate. Spiderfoot has an embedded web server for providing an intuitive web-based interface, but you can also do the same using a command-line interface. Features of Spiderfoot: Spiderfoot is a free and open-source tool available on Github. Spiderfoot works as a framework cum tool. Spiderfoot framework is written in python language. Spiderfoot can be used for reconnaissance. Spiderfoot contains many modules. As it’s a framework that uses modules for information gathering. Spiderfoot works on the principles of OSINT. Spiderfoot is an automated OSINT Framework. Spiderfoot automates the reconnaissance processes. Uses of Spiderfoot: Spiderfoot is used for reconnaissance. Spiderfoot is used for information gathering. Spiderfoot is working as a scanner for active and passive scanning on target. Spiderfoot can be used for domain footprinting. Spiderfoot can be used to find the phone numbers, email addresses of the target. Spiderfoot can be used to find bitcoin addresses. Spiderfoot can be used to save all the information gathering summary. Spiderfoot can be used to create graphs of scanning done by Spiderfoot. Spiderfoot can be used to automateGitHub all the information gathering processes. Reference of the tool : You can clone the tool from GitHub using the link. This is a reference to the tool. This tool is available on Github you can download it free of cost. 1. Open your Kali Linux operating system. Move to the desktop using the following command. You have to move to Desktop because on desktop you have to create a directory into which you have to clone the tool. Use the following command to move to Desktop. cd Desktop 2. Now you are on the desktop. Here you have to create a new directory called spiderfoot. In this directory, you have to clone the tool from Github. Use the following command to create a new directory. mkdir spiderfoot 3. Now use the following command to move in the directory that you have created. cd spiderfoot 4. Now you are in spiderfoot directory. In this directory, you have to clone the tool from GitHub. Use the following command to clone the tool from GitHub. git clone https://github.com/smicallef/spiderfoot 5. The tool has been downloaded and cloned successfully. Now to list out the contents of the tool use the following command. ls 6. You can see a new directory has been created i.e spiderfoot. You have to install the spiderfoot tool using the following command. cd spiderfoot 7. Now you are under the directory of the tool. To list out the contents of the directory using the following command. ls 8. All the files of the tool have been listed here. You can have to install requirements for the tool. Use the following command to install requirements. pip install –r requirements.txt 9. All the requirements have been downloaded. Now it’s time to run the tool. Use following command to run the tool. python3 sf.py 10. The tool is asking to start the web server. Use following command to start the web server and also the tool. python3 ./sf.py -l 127.0.0.1:5001 11. The server has started on the IP address 127.0.0.1:5001. Search this IP address on any URL bar. You can see a web page has been opened. This is a tool that is running on port 127.0.0.1:5001. There is a dashboard of the tool. The dashboard contains scan history, new scan, and setting options. For fresh installation, there is no previous scan history. If we click the new scan tab, we see option to start the new scan along with the target seed field. The target seed field can be a target IP address, a domain name, or a sub-domain name. There are 3 types of configuration settings to define the scanning process. These are scan-by-use cases, required data, or modules. Each configuration setting has a number of options to choose from. For example, scan by use cases allows both, active and passive scanning of the target. It also gives the option to scan for all possible information or a range of information about the target. Example 1: 1. Scan a website and get the details of the website. 2. You can see here Scan Name is Domain Name and Scan Target is scanme.org. 3. You got all the information here. This is how you can use this tool for scanning. Example 2: 1. Using Spiderfoot tool to get information about an email address. 2. As you can see here email address is set to E-mail address bob@example.com 3. You can see in this meta-information we got all the details related to the email address. Conclusion : This is how you can set the target and can perform reconnaissance using Spiderfoot tool. You can get different pieces of information using this framework. Spiderfoot is open source intelligence tool. Spiderfoot is capable of doing everything almost you need for reconnaissance as per your need. Spiderfoot works as open-source tool intelligence tool. It integrates with just about every data source available and utilizes a range of methods for data analysis, making that data easy to navigate. Spiderfoot has an embedded web server for providing an intuitive web-based interface but you can also do the same using the command-line interface. Cyber-security Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples tar command in Linux with examples curl command in Linux with Examples SORT command in Linux/Unix with examples Conditional Statements | Shell Script 'crontab' in Linux with Examples TCP Server-Client implementation in C Tail command in Linux with examples scp command in Linux with Examples Docker - COPY Instruction
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Apr, 2021" }, { "code": null, "e": 1135, "s": 28, "text": "Spiderfoot is a free and open-source tool available on Github. This tool is a framework written in the python programming language. You must have python installed in your Kali Linux operating system to use this framework. Spiderfoot is used for reconnaissance. Spiderfoot uses different modules for information gathering. Spiderfoot is capable enough to gather information about the target host through active and passive scanning options available on the Spiderfoot framework. In the Spiderfoot framework different scanning options and modules available to set and scan the target host. Spiderfoot is an Open Source Intelligence and Information Gathering Tool. Spiderfoot is capable of doing everything almost you need for reconnaissance as per your need. Spiderfoot works as an open-source tool intelligence tool. It integrates with just about every data source available and utilizes a range of methods for data analysis, making that data easy to navigate. Spiderfoot has an embedded web server for providing an intuitive web-based interface, but you can also do the same using a command-line interface." }, { "code": null, "e": 1159, "s": 1135, "text": "Features of Spiderfoot:" }, { "code": null, "e": 1222, "s": 1159, "text": "Spiderfoot is a free and open-source tool available on Github." }, { "code": null, "e": 1264, "s": 1222, "text": "Spiderfoot works as a framework cum tool." }, { "code": null, "e": 1316, "s": 1264, "text": "Spiderfoot framework is written in python language." }, { "code": null, "e": 1359, "s": 1316, "text": "Spiderfoot can be used for reconnaissance." }, { "code": null, "e": 1458, "s": 1359, "text": "Spiderfoot contains many modules. As it’s a framework that uses modules for information gathering." }, { "code": null, "e": 1503, "s": 1458, "text": "Spiderfoot works on the principles of OSINT." }, { "code": null, "e": 1547, "s": 1503, "text": "Spiderfoot is an automated OSINT Framework." }, { "code": null, "e": 1598, "s": 1547, "text": "Spiderfoot automates the reconnaissance processes." }, { "code": null, "e": 1618, "s": 1598, "text": "Uses of Spiderfoot:" }, { "code": null, "e": 1657, "s": 1618, "text": "Spiderfoot is used for reconnaissance." }, { "code": null, "e": 1703, "s": 1657, "text": "Spiderfoot is used for information gathering." }, { "code": null, "e": 1781, "s": 1703, "text": "Spiderfoot is working as a scanner for active and passive scanning on target." }, { "code": null, "e": 1829, "s": 1781, "text": "Spiderfoot can be used for domain footprinting." }, { "code": null, "e": 1910, "s": 1829, "text": "Spiderfoot can be used to find the phone numbers, email addresses of the target." }, { "code": null, "e": 1960, "s": 1910, "text": "Spiderfoot can be used to find bitcoin addresses." }, { "code": null, "e": 2030, "s": 1960, "text": "Spiderfoot can be used to save all the information gathering summary." }, { "code": null, "e": 2102, "s": 2030, "text": "Spiderfoot can be used to create graphs of scanning done by Spiderfoot." }, { "code": null, "e": 2184, "s": 2102, "text": "Spiderfoot can be used to automateGitHub all the information gathering processes." }, { "code": null, "e": 2208, "s": 2184, "text": "Reference of the tool :" }, { "code": null, "e": 2359, "s": 2208, "text": "You can clone the tool from GitHub using the link. This is a reference to the tool. This tool is available on Github you can download it free of cost." }, { "code": null, "e": 2613, "s": 2359, "text": "1. Open your Kali Linux operating system. Move to the desktop using the following command. You have to move to Desktop because on desktop you have to create a directory into which you have to clone the tool. Use the following command to move to Desktop." }, { "code": null, "e": 2624, "s": 2613, "text": "cd Desktop" }, { "code": null, "e": 2826, "s": 2624, "text": "2. Now you are on the desktop. Here you have to create a new directory called spiderfoot. In this directory, you have to clone the tool from Github. Use the following command to create a new directory." }, { "code": null, "e": 2843, "s": 2826, "text": "mkdir spiderfoot" }, { "code": null, "e": 2924, "s": 2843, "text": "3. Now use the following command to move in the directory that you have created." }, { "code": null, "e": 2938, "s": 2924, "text": "cd spiderfoot" }, { "code": null, "e": 3094, "s": 2938, "text": "4. Now you are in spiderfoot directory. In this directory, you have to clone the tool from GitHub. Use the following command to clone the tool from GitHub." }, { "code": null, "e": 3144, "s": 3094, "text": "git clone https://github.com/smicallef/spiderfoot" }, { "code": null, "e": 3269, "s": 3144, "text": "5. The tool has been downloaded and cloned successfully. Now to list out the contents of the tool use the following command." }, { "code": null, "e": 3272, "s": 3269, "text": "ls" }, { "code": null, "e": 3406, "s": 3272, "text": "6. You can see a new directory has been created i.e spiderfoot. You have to install the spiderfoot tool using the following command. " }, { "code": null, "e": 3420, "s": 3406, "text": "cd spiderfoot" }, { "code": null, "e": 3539, "s": 3420, "text": "7. Now you are under the directory of the tool. To list out the contents of the directory using the following command." }, { "code": null, "e": 3542, "s": 3539, "text": "ls" }, { "code": null, "e": 3696, "s": 3542, "text": "8. All the files of the tool have been listed here. You can have to install requirements for the tool. Use the following command to install requirements." }, { "code": null, "e": 3728, "s": 3696, "text": "pip install –r requirements.txt" }, { "code": null, "e": 3844, "s": 3728, "text": "9. All the requirements have been downloaded. Now it’s time to run the tool. Use following command to run the tool." }, { "code": null, "e": 3858, "s": 3844, "text": "python3 sf.py" }, { "code": null, "e": 3971, "s": 3858, "text": "10. The tool is asking to start the web server. Use following command to start the web server and also the tool." }, { "code": null, "e": 4006, "s": 3971, "text": "python3 ./sf.py -l 127.0.0.1:5001" }, { "code": null, "e": 4106, "s": 4006, "text": "11. The server has started on the IP address 127.0.0.1:5001. Search this IP address on any URL bar." }, { "code": null, "e": 4942, "s": 4106, "text": "You can see a web page has been opened. This is a tool that is running on port 127.0.0.1:5001. There is a dashboard of the tool. The dashboard contains scan history, new scan, and setting options. For fresh installation, there is no previous scan history. If we click the new scan tab, we see option to start the new scan along with the target seed field. The target seed field can be a target IP address, a domain name, or a sub-domain name. There are 3 types of configuration settings to define the scanning process. These are scan-by-use cases, required data, or modules. Each configuration setting has a number of options to choose from. For example, scan by use cases allows both, active and passive scanning of the target. It also gives the option to scan for all possible information or a range of information about the target." }, { "code": null, "e": 4953, "s": 4942, "text": "Example 1:" }, { "code": null, "e": 5007, "s": 4953, "text": "1. Scan a website and get the details of the website." }, { "code": null, "e": 5083, "s": 5007, "text": "2. You can see here Scan Name is Domain Name and Scan Target is scanme.org." }, { "code": null, "e": 5168, "s": 5083, "text": "3. You got all the information here. This is how you can use this tool for scanning." }, { "code": null, "e": 5179, "s": 5168, "text": "Example 2:" }, { "code": null, "e": 5247, "s": 5179, "text": "1. Using Spiderfoot tool to get information about an email address." }, { "code": null, "e": 5325, "s": 5247, "text": "2. As you can see here email address is set to E-mail address bob@example.com" }, { "code": null, "e": 5418, "s": 5325, "text": "3. You can see in this meta-information we got all the details related to the email address." }, { "code": null, "e": 5431, "s": 5418, "text": "Conclusion :" }, { "code": null, "e": 6075, "s": 5431, "text": "This is how you can set the target and can perform reconnaissance using Spiderfoot tool. You can get different pieces of information using this framework. Spiderfoot is open source intelligence tool. Spiderfoot is capable of doing everything almost you need for reconnaissance as per your need. Spiderfoot works as open-source tool intelligence tool. It integrates with just about every data source available and utilizes a range of methods for data analysis, making that data easy to navigate. Spiderfoot has an embedded web server for providing an intuitive web-based interface but you can also do the same using the command-line interface. " }, { "code": null, "e": 6090, "s": 6075, "text": "Cyber-security" }, { "code": null, "e": 6101, "s": 6090, "text": "Kali-Linux" }, { "code": null, "e": 6113, "s": 6101, "text": "Linux-Tools" }, { "code": null, "e": 6124, "s": 6113, "text": "Linux-Unix" }, { "code": null, "e": 6222, "s": 6124, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6257, "s": 6222, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 6292, "s": 6257, "text": "tar command in Linux with examples" }, { "code": null, "e": 6328, "s": 6292, "text": "curl command in Linux with Examples" }, { "code": null, "e": 6369, "s": 6328, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 6407, "s": 6369, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 6440, "s": 6407, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 6478, "s": 6440, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 6514, "s": 6478, "text": "Tail command in Linux with examples" }, { "code": null, "e": 6549, "s": 6514, "text": "scp command in Linux with Examples" } ]
Winsorization
30 May, 2021 Winsorization is the process of replacing the extreme values of statistical data in order to limit the effect of the outliers on the calculations or the results obtained by using that data. The mean value calculated after such replacement of the extreme values is called winsorized mean. For example, 90% winsorization means the replacement of the top 5% and bottom 5% of the data. The top 5% of the data is replaced by the value of the data at the 95th percentile and the value of the bottom 5% of the data is replaced by the value of the data at the 5th percentile. Input: A numeric array whose values at the upper end and the lower end are to be winsorized. The first argument of the tuple is the percentage of values at the lower end which are to be winsorized. The second argument of the tuple is the percentage of values at the upper end which are to be winsorized. Output: A numeric array whose values at the upper end and at the lower end are winsorized as defined by the user. Example #1: Python3 # Libraries to be importedimport numpy as npimport matplotlib.pyplot as pltimport randomfrom scipy.stats.mstats import winsorize Let us see an example where outliers are present on both the upper end and the lower end of the data. Python3 # Creating an array with 100 random valuesarray = [np.random.randint(100) for i in range(100)] # Creating outliers# Here, the values which are selected for creating outliers # are appended so that same outliers are not created again.AlreadySelected = []i = 0 # Creating 5 outliers on the lower endwhile (i < 5): x = np.random.choice(array) # Randomly selecting a value from the array y = x - mean*3 array = np.append(array, y) if (x not in already_selected): AlreadySelected.append(y) i += 1 else: continue # Creating 5 outliers on the upper endi = 0while (i < 5): x = np.random.choice(array) # Randomly selecting a value from the array y = x + mean*4 array = np.append(array, y) if (x not in already_selected): AlreadySelected.append(y) i += 1 else: continue std = np.std(array) # Storing the standard deviation of the arraymean = np.mean(array) # Storing the mean of the array plt.boxplot(array)plt.title('Array with Outliers')plt.show() Output: Python3 print(mean) # mean of the numeric array with outliers Output: Now, we winsorize the array by 10% i.e. we winsorize 5% of the highest values and 5% of the lowest value of the array: Python3 WinsorizedArray = winsorize(array,(0.05,0.05)) plt.boxplot(WinsorizedArray)plt.title('Winsorized array')plt.show() Output: Python3 WinsorizedMean = np.mean(WinsorizedArray)print(WinsorizedMean) Output: In this case, there is only a slight change in the mean value of the data. Now, let us see an example where outliers are present only at one end of the data. Python3 # Creating another array with 100 random valuesarray2 = [np.random.randint(100) for i in range(100)] std = np.std(array2)mean = np.mean(array2)AlreadySelected = []# Creating outliers on the upper endi = 0 while (i<5): x = np.random.choice(array2) # Randomly selecting a value from the array y = x + mean*4 array2 = np.append(array2,y) if (x not in AlreadySelected): AlreadySelected.append(y) i+=1 else: continue plt.boxplot(array2)plt.title('Array with outliers')plt.show() Output: Python3 OutlierArray2Mean = np.mean(array2)print(OutlierArray2Mean) Output: Python3 WinsorizedArray2 = winsorize(array2,(0.1,0.1))# In this case, the lower 10% values of # the data will have their values set equal to the value of the data point at #the 10th percentile. plt.boxplot(WinsorizedArray2)plt.show() WinsorizedArray2Mean = np.mean(WinsorizedArray2) Output: Python3 WinsorizedArray2Mean = np.mean(WinsorizedArray2)print(WinsorizedArray2Mean) Output: In this case, there is a significant difference in the mean value. Python numpy-Statistics Functions Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 May, 2021" }, { "code": null, "e": 316, "s": 28, "text": "Winsorization is the process of replacing the extreme values of statistical data in order to limit the effect of the outliers on the calculations or the results obtained by using that data. The mean value calculated after such replacement of the extreme values is called winsorized mean." }, { "code": null, "e": 598, "s": 316, "text": " For example, 90% winsorization means the replacement of the top 5% and bottom 5% of the data. The top 5% of the data is replaced by the value of the data at the 95th percentile and the value of the bottom 5% of the data is replaced by the value of the data at the 5th percentile. " }, { "code": null, "e": 605, "s": 598, "text": "Input:" }, { "code": null, "e": 691, "s": 605, "text": "A numeric array whose values at the upper end and the lower end are to be winsorized." }, { "code": null, "e": 796, "s": 691, "text": "The first argument of the tuple is the percentage of values at the lower end which are to be winsorized." }, { "code": null, "e": 902, "s": 796, "text": "The second argument of the tuple is the percentage of values at the upper end which are to be winsorized." }, { "code": null, "e": 910, "s": 902, "text": "Output:" }, { "code": null, "e": 1016, "s": 910, "text": "A numeric array whose values at the upper end and at the lower end are winsorized as defined by the user." }, { "code": null, "e": 1028, "s": 1016, "text": "Example #1:" }, { "code": null, "e": 1036, "s": 1028, "text": "Python3" }, { "code": "# Libraries to be importedimport numpy as npimport matplotlib.pyplot as pltimport randomfrom scipy.stats.mstats import winsorize", "e": 1165, "s": 1036, "text": null }, { "code": null, "e": 1267, "s": 1165, "text": "Let us see an example where outliers are present on both the upper end and the lower end of the data." }, { "code": null, "e": 1275, "s": 1267, "text": "Python3" }, { "code": "# Creating an array with 100 random valuesarray = [np.random.randint(100) for i in range(100)] # Creating outliers# Here, the values which are selected for creating outliers # are appended so that same outliers are not created again.AlreadySelected = []i = 0 # Creating 5 outliers on the lower endwhile (i < 5): x = np.random.choice(array) # Randomly selecting a value from the array y = x - mean*3 array = np.append(array, y) if (x not in already_selected): AlreadySelected.append(y) i += 1 else: continue # Creating 5 outliers on the upper endi = 0while (i < 5): x = np.random.choice(array) # Randomly selecting a value from the array y = x + mean*4 array = np.append(array, y) if (x not in already_selected): AlreadySelected.append(y) i += 1 else: continue std = np.std(array) # Storing the standard deviation of the arraymean = np.mean(array) # Storing the mean of the array plt.boxplot(array)plt.title('Array with Outliers')plt.show()", "e": 2304, "s": 1275, "text": null }, { "code": null, "e": 2312, "s": 2304, "text": "Output:" }, { "code": null, "e": 2320, "s": 2312, "text": "Python3" }, { "code": "print(mean) # mean of the numeric array with outliers", "e": 2374, "s": 2320, "text": null }, { "code": null, "e": 2382, "s": 2374, "text": "Output:" }, { "code": null, "e": 2501, "s": 2382, "text": "Now, we winsorize the array by 10% i.e. we winsorize 5% of the highest values and 5% of the lowest value of the array:" }, { "code": null, "e": 2509, "s": 2501, "text": "Python3" }, { "code": "WinsorizedArray = winsorize(array,(0.05,0.05)) plt.boxplot(WinsorizedArray)plt.title('Winsorized array')plt.show()", "e": 2625, "s": 2509, "text": null }, { "code": null, "e": 2633, "s": 2625, "text": "Output:" }, { "code": null, "e": 2641, "s": 2633, "text": "Python3" }, { "code": "WinsorizedMean = np.mean(WinsorizedArray)print(WinsorizedMean)", "e": 2704, "s": 2641, "text": null }, { "code": null, "e": 2712, "s": 2704, "text": "Output:" }, { "code": null, "e": 2787, "s": 2712, "text": "In this case, there is only a slight change in the mean value of the data." }, { "code": null, "e": 2870, "s": 2787, "text": "Now, let us see an example where outliers are present only at one end of the data." }, { "code": null, "e": 2878, "s": 2870, "text": "Python3" }, { "code": "# Creating another array with 100 random valuesarray2 = [np.random.randint(100) for i in range(100)] std = np.std(array2)mean = np.mean(array2)AlreadySelected = []# Creating outliers on the upper endi = 0 while (i<5): x = np.random.choice(array2) # Randomly selecting a value from the array y = x + mean*4 array2 = np.append(array2,y) if (x not in AlreadySelected): AlreadySelected.append(y) i+=1 else: continue plt.boxplot(array2)plt.title('Array with outliers')plt.show()", "e": 3409, "s": 2878, "text": null }, { "code": null, "e": 3417, "s": 3409, "text": "Output:" }, { "code": null, "e": 3425, "s": 3417, "text": "Python3" }, { "code": "OutlierArray2Mean = np.mean(array2)print(OutlierArray2Mean)", "e": 3485, "s": 3425, "text": null }, { "code": null, "e": 3493, "s": 3485, "text": "Output:" }, { "code": null, "e": 3501, "s": 3493, "text": "Python3" }, { "code": "WinsorizedArray2 = winsorize(array2,(0.1,0.1))# In this case, the lower 10% values of # the data will have their values set equal to the value of the data point at #the 10th percentile. plt.boxplot(WinsorizedArray2)plt.show() WinsorizedArray2Mean = np.mean(WinsorizedArray2)", "e": 3778, "s": 3501, "text": null }, { "code": null, "e": 3786, "s": 3778, "text": "Output:" }, { "code": null, "e": 3794, "s": 3786, "text": "Python3" }, { "code": "WinsorizedArray2Mean = np.mean(WinsorizedArray2)print(WinsorizedArray2Mean)", "e": 3870, "s": 3794, "text": null }, { "code": null, "e": 3878, "s": 3870, "text": "Output:" }, { "code": null, "e": 3945, "s": 3878, "text": "In this case, there is a significant difference in the mean value." }, { "code": null, "e": 3979, "s": 3945, "text": "Python numpy-Statistics Functions" }, { "code": null, "e": 3984, "s": 3979, "text": "Misc" }, { "code": null, "e": 3989, "s": 3984, "text": "Misc" }, { "code": null, "e": 3994, "s": 3989, "text": "Misc" } ]
Python program to print all negative numbers in a range
01 Jun, 2022 Given the start and end of a range, write a Python program to print all negative numbers in a given range. Examples: Input: a = -4, b = 5 Output: -4, -3, -2, -1 Input: a = -3, b= 4 Output: -3, -2, -1 Method: Print all the negative numbers using a single-line solution. Print all negative numbers using for loop. Define the start and end limits of the range. Iterate from start range to end range using for loop and check if num is less than 0. If the condition satisfies, then only print the number. Python3 # Python code# To print all negative numbers in a given range def negativenumbers(a,b): # Checking condition for negative numbers # single line solution out=[i for i in range(a,b+1) if i<0] # print the all negative numbers print(*out) # driver code# a -> start rangea=-4# b -> end rangeb=5negativenumbers(a,b) -4 -3 -2 -1 Example #1: Print all negative numbers from given list using for loop Define start and end limit of range. Iterate from start till the range in the list using for loop and check if num is less than 0. If the condition satisfies, then only print the number. Python3 # Python program to print negative Numbers in given range start, end = -4, 19 # iterating each number in listfor num in range(start, end + 1): # checking condition if num < 0: print(num, end = " ") -4 -3 -2 -1 Example #2: Taking range limit from user input Python3 # Python program to print negative Numbers in given range start = int(input("Enter the start of range: "))end = int(input("Enter the end of range: ")) # iterating each number in listfor num in range(start, end + 1): # checking condition if num < 0: print(num, end = " ") Output: Enter the start of range: -15 Enter the end of range: 5 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 laxmigangarajula03 Python list-programs python-list Python Python Programs School Programming python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Jun, 2022" }, { "code": null, "e": 159, "s": 52, "text": "Given the start and end of a range, write a Python program to print all negative numbers in a given range." }, { "code": null, "e": 170, "s": 159, "text": " Examples:" }, { "code": null, "e": 254, "s": 170, "text": "Input: a = -4, b = 5\nOutput: -4, -3, -2, -1\n\nInput: a = -3, b= 4\nOutput: -3, -2, -1" }, { "code": null, "e": 323, "s": 254, "text": "Method: Print all the negative numbers using a single-line solution." }, { "code": null, "e": 555, "s": 323, "text": "Print all negative numbers using for loop. Define the start and end limits of the range. Iterate from start range to end range using for loop and check if num is less than 0. If the condition satisfies, then only print the number. " }, { "code": null, "e": 563, "s": 555, "text": "Python3" }, { "code": "# Python code# To print all negative numbers in a given range def negativenumbers(a,b): # Checking condition for negative numbers # single line solution out=[i for i in range(a,b+1) if i<0] # print the all negative numbers print(*out) # driver code# a -> start rangea=-4# b -> end rangeb=5negativenumbers(a,b)", "e": 879, "s": 563, "text": null }, { "code": null, "e": 891, "s": 879, "text": "-4 -3 -2 -1" }, { "code": null, "e": 1149, "s": 891, "text": "Example #1: Print all negative numbers from given list using for loop Define start and end limit of range. Iterate from start till the range in the list using for loop and check if num is less than 0. If the condition satisfies, then only print the number. " }, { "code": null, "e": 1157, "s": 1149, "text": "Python3" }, { "code": "# Python program to print negative Numbers in given range start, end = -4, 19 # iterating each number in listfor num in range(start, end + 1): # checking condition if num < 0: print(num, end = \" \")", "e": 1373, "s": 1157, "text": null }, { "code": null, "e": 1386, "s": 1373, "text": "-4 -3 -2 -1 " }, { "code": null, "e": 1436, "s": 1386, "text": " Example #2: Taking range limit from user input " }, { "code": null, "e": 1444, "s": 1436, "text": "Python3" }, { "code": "# Python program to print negative Numbers in given range start = int(input(\"Enter the start of range: \"))end = int(input(\"Enter the end of range: \")) # iterating each number in listfor num in range(start, end + 1): # checking condition if num < 0: print(num, end = \" \")", "e": 1733, "s": 1444, "text": null }, { "code": null, "e": 1741, "s": 1733, "text": "Output:" }, { "code": null, "e": 1849, "s": 1741, "text": "Enter the start of range: -15\nEnter the end of range: 5\n-15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 " }, { "code": null, "e": 1868, "s": 1849, "text": "laxmigangarajula03" }, { "code": null, "e": 1889, "s": 1868, "text": "Python list-programs" }, { "code": null, "e": 1901, "s": 1889, "text": "python-list" }, { "code": null, "e": 1908, "s": 1901, "text": "Python" }, { "code": null, "e": 1924, "s": 1908, "text": "Python Programs" }, { "code": null, "e": 1943, "s": 1924, "text": "School Programming" }, { "code": null, "e": 1955, "s": 1943, "text": "python-list" }, { "code": null, "e": 2053, "s": 1955, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2095, "s": 2053, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2117, "s": 2095, "text": "Enumerate() in Python" }, { "code": null, "e": 2143, "s": 2117, "text": "Python String | replace()" }, { "code": null, "e": 2175, "s": 2143, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2204, "s": 2175, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2226, "s": 2204, "text": "Defaultdict in Python" }, { "code": null, "e": 2265, "s": 2226, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2303, "s": 2265, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2340, "s": 2303, "text": "Python Program for Fibonacci numbers" } ]
GATE | GATE-CS-2000 | Question 45
28 Jun, 2021 Suppose the time to service a page fault is on the average 10 milliseconds, while a memory access takes 1 microsecond. Then a 99.99% hit ratio results in average memory access time of (GATE CS 2000) (A) 1.9999 milliseconds(B) 1 millisecond(C) 9.999 microseconds(D) 1.9999 microsecondsAnswer: (D)Explanation: If any page request comes it will first search into page table, if present, then it will directly fetch the page from memory, thus in this case time requires will be only memory access time. But if required page will not be found, first we have to bring it out and then go for memory access. This extra time is called page fault service time. Let hit ratio be p , memory access time be t1 , and page fault service time be t2. Hence, average memory access time = p*t1 + (1-p)*t2 =(99.99*1 + 0.01*(10*1000 + 1))/100 =1.9999 *10^-6 sec This explanation is contributed by Abhishek Kumar. Also, see question 1 of https://www.geeksforgeeks.org/operating-systems-set-3/Quiz of this Question GATE-CS-2000 GATE-GATE-CS-2000 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE CS 2008 | Question 46 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE CS 2011 | Question 49 GATE | GATE CS 1996 | Question 38 GATE | GATE-CS-2004 | Question 31 GATE | GATE IT 2006 | Question 20 GATE | GATE-CS-2016 (Set 1) | Question 45
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jun, 2021" }, { "code": null, "e": 227, "s": 28, "text": "Suppose the time to service a page fault is on the average 10 milliseconds, while a memory access takes 1 microsecond. Then a 99.99% hit ratio results in average memory access time of (GATE CS 2000)" }, { "code": null, "e": 527, "s": 227, "text": "(A) 1.9999 milliseconds(B) 1 millisecond(C) 9.999 microseconds(D) 1.9999 microsecondsAnswer: (D)Explanation: If any page request comes it will first search into page table, if present, then it will directly fetch the page from memory, thus in this case time requires will be only memory access time." }, { "code": null, "e": 679, "s": 527, "text": "But if required page will not be found, first we have to bring it out and then go for memory access. This extra time is called page fault service time." }, { "code": null, "e": 762, "s": 679, "text": "Let hit ratio be p , memory access time be t1 , and page fault service time be t2." }, { "code": null, "e": 953, "s": 762, "text": "Hence, average memory access time = p*t1 + (1-p)*t2\n =(99.99*1 + 0.01*(10*1000 + 1))/100\n =1.9999 *10^-6 sec\n\n" }, { "code": null, "e": 1004, "s": 953, "text": "This explanation is contributed by Abhishek Kumar." }, { "code": null, "e": 1104, "s": 1004, "text": "Also, see question 1 of https://www.geeksforgeeks.org/operating-systems-set-3/Quiz of this Question" }, { "code": null, "e": 1117, "s": 1104, "text": "GATE-CS-2000" }, { "code": null, "e": 1135, "s": 1117, "text": "GATE-GATE-CS-2000" }, { "code": null, "e": 1140, "s": 1135, "text": "GATE" }, { "code": null, "e": 1238, "s": 1140, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1280, "s": 1238, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 1342, "s": 1280, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 1376, "s": 1342, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 1418, "s": 1376, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 1460, "s": 1418, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 1494, "s": 1460, "text": "GATE | GATE CS 2011 | Question 49" }, { "code": null, "e": 1528, "s": 1494, "text": "GATE | GATE CS 1996 | Question 38" }, { "code": null, "e": 1562, "s": 1528, "text": "GATE | GATE-CS-2004 | Question 31" }, { "code": null, "e": 1596, "s": 1562, "text": "GATE | GATE IT 2006 | Question 20" } ]
Maximum subarray sum in O(n) using prefix sum
08 Apr, 2021 Given an Array of Positive and Negative Integers, find out the Maximum Subarray Sum in that Array. Examples: Input1 : arr = {-2, -3, 4, -1, -2, 1, 5, -3} Output1 : 7 Input2 : arr = {4, -8, 9, -4, 1, -8, -1, 6} Output2 : 9 Kadane’s Algorithm solves this problem using Dynamic Programming approach in linear time. Here is another approach using Dynamic Programming and Prefix Sum to find out maximum subarray sum in Linear time.Prerequisite: Prefix Sum Array 1. First calculate the prefix sum (prefix_sum) of the input array. 2. Sum of a subarray from index x to y can be presented as, 3. Now maximum of these subarrays is, That is, we keep track of minimum prefix sum for x <= y and maximum subarray sum so far. Implementation: 1. Calculate the prefix sum of the input array. 2. Initialize : min_prefix_sum = 0, res = -infinite 3. Maintain a loop for i = 0 to n. (n is the size of the input array). a) cand = prefix_sum[i] – mini b) If cand is greater than res (maximum subarray sum so far), then update res by cand. c) If prefix_sum[i] is less than min_prefix_sum (minimum prefix sum so far), then update min_prefix_sum by prefix_sum[i].4. Return res.Reference: Algorithms for the problem of k maximum sums and a VLSI algorithm for the k maximum subarrays problem C++ Java Python3 C# PHP Javascript // C++ program to find out maximum subarray// sum in linear time using prefix sum.#include <iostream>#include <limits>using namespace std; // Function to compute maximum subarray// sum in linear time.int maximumSumSubarray(int arr[], int n){ // Initialize minimum prefix sum to 0. int min_prefix_sum = 0; // Initialize maximum subarray sum so // far to -infinity. int res = numeric_limits<int>::min(); // Initialize and compute the prefix // sum array. int prefix_sum[n]; prefix_sum[0] = arr[0]; for (int i = 1; i < n; i++) prefix_sum[i] = prefix_sum[i - 1] + arr[i]; // loop through the array, keep track // of minimum prefix sum so far and // maximum subarray sum. for (int i = 0; i < n; i++) { res = max(res, prefix_sum[i] - min_prefix_sum); min_prefix_sum = min(min_prefix_sum, prefix_sum[i]); } return res;} // Driver Programint main(){ // Test case 1 int arr1[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; int n1 = sizeof(arr1) / sizeof(arr1[0]); cout << maximumSumSubarray(arr1, n1) << endl; // Test case 2 int arr2[] = { 4, -8, 9, -4, 1, -8, -1, 6 }; int n2 = sizeof(arr2) / sizeof(arr2[0]); cout << maximumSumSubarray(arr2, n2); return 0;} // Java program to find// out maximum subarray// sum in linear time// using prefix sum. class GFG{ // Function to compute maximum // subarray sum in linear time. static int maximumSumSubarray(int arr[], int n) { // Initialize minimum // prefix sum to 0. int min_prefix_sum = 0; // Initialize maximum subarray // sum so far to -infinity. int res = Integer.MIN_VALUE; // Initialize and compute // the prefix sum array. int prefix_sum[] = new int[n]; prefix_sum[0] = arr[0]; for (int i = 1; i < n; i++) prefix_sum[i] = prefix_sum[i - 1] + arr[i]; // loop through the array, keep // track of minimum prefix sum so // far and maximum subarray sum. for (int i = 0; i < n; i++) { res = Math.max(res, prefix_sum[i] - min_prefix_sum); min_prefix_sum = Math.min(min_prefix_sum, prefix_sum[i]); } return res; } // Driver Program public static void main (String[] args) { // Test case 1 int arr1[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; int n1 = arr1.length; System.out.println(maximumSumSubarray(arr1, n1)); // Test case 2 int arr2[] = { 4, -8, 9, -4, 1, -8, -1, 6 }; int n2 = arr2.length; System.out.println(maximumSumSubarray(arr2, n2)); }} // This code is contributed by Ansu Kumari. # Python3 program to find out# maximum subarray sum in# linear time using prefix# sum.import math # Function to compute maximum# subarray sum in linear time.def maximumSumSubarray(arr, n): # Initialize minimum prefix # sum to 0. min_prefix_sum = 0 # Initialize maximum subarray # sum so far to -infinity. res = -math.inf # Initialize and compute the # prefix sum array. prefix_sum = [] prefix_sum.append(arr[0]) for i in range(1, n): prefix_sum.append(prefix_sum[i - 1] + arr[i]) # loop through the array keep # track of minimum prefix sum # so far and maximum subarray # sum. for i in range(n): res = max(res, prefix_sum[i] - min_prefix_sum) min_prefix_sum = min(min_prefix_sum, prefix_sum[i]) return res # Driver Program # Test case 1arr1 = [ -2, -3, 4, -1, -2, 1, 5, -3 ]n1 = len(arr1)print(maximumSumSubarray(arr1, n1)) # Test case 2arr2 = [ 4, -8, 9, -4, 1, -8, -1, 6 ]n2 = len(arr2)print(maximumSumSubarray(arr2, n2)) # This code is contributed by Ansu Kuamri. // C# program to find// out maximum subarray// sum in linear time// using prefix sum.using System; class GFG{ // Function to compute maximum // subarray sum in linear time. static int maximumSumSubarray(int []arr, int n) { // Initialize minimum // prefix sum to 0. int min_prefix_sum = 0; // Initialize maximum subarray // sum so far to -infinity. int res = int.MinValue; // Initialize and compute // the prefix sum array. int []prefix_sum = new int[n]; prefix_sum[0] = arr[0]; for (int i = 1; i < n; i++) prefix_sum[i] = prefix_sum[i - 1] + arr[i]; // loop through the array, keep // track of minimum prefix sum so // far and maximum subarray sum. for (int i = 0; i < n; i++) { res = Math.Max(res, prefix_sum[i] - min_prefix_sum); min_prefix_sum = Math.Min(min_prefix_sum, prefix_sum[i]); } return res; } // Driver Program public static void Main () { // Test case 1 int []arr1 = { -2, -3, 4, -1, -2, 1, 5, -3 }; int n1 = arr1.Length; Console.WriteLine(maximumSumSubarray(arr1, n1)); // Test case 2 int []arr2 = { 4, -8, 9, -4, 1, -8, -1, 6 }; int n2 = arr2.Length; Console.WriteLine(maximumSumSubarray(arr2, n2)); }} // This code is contributed by vt_m. <?php// PHP program to find out// maximum subarray sum in// linear time using prefix sum. // Function to compute maximum// subarray sum in linear time.function maximumSumSubarray($arr, $n){ // Initialize minimum // prefix sum to 0. $min_prefix_sum = 0; // Initialize maximum subarray // sum so far to -infinity. $res = PHP_INT_MIN; // Initialize and compute // the prefix sum array. $prefix_sum = array(); $prefix_sum[0] = $arr[0]; for ($i = 1; $i < $n; $i++) $prefix_sum[$i] = $prefix_sum[$i - 1] + $arr[$i]; // loop through the array, // keep track of minimum // prefix sum so far and // maximum subarray sum. for ($i = 0; $i < $n; $i++) { $res = max($res, $prefix_sum[$i] - $min_prefix_sum); $min_prefix_sum = min($min_prefix_sum, $prefix_sum[$i]); } return $res;} // Driver Code // Test case 1$arr1 = array(-2, -3, 4, -1, -2, 1, 5, -3);$n1 = count($arr1);echo maximumSumSubarray($arr1, $n1), " \n" ; // Test case 2$arr2 = array(4, -8, 9, -4, 1, -8, -1, 6); $n2 = count($arr2);echo maximumSumSubarray($arr2, $n2); // This code is contributed by anuj_67.?> <script> // JavaScript program to find// out maximum subarray// sum in linear time// using prefix sum. // Function to compute maximum// subarray sum in linear time. function maximumSumSubarray(arr, n) { // Initialize minimum // prefix sum to 0. let min_prefix_sum = 0; // Initialize maximum subarray // sum so far to -infinity. let res = Number.MIN_VALUE; // Initialize and compute // the prefix sum array. let prefix_sum = []; prefix_sum[0] = arr[0]; for (let i = 1; i < n; i++) prefix_sum[i] = prefix_sum[i - 1] + arr[i]; // loop through the array, keep // track of minimum prefix sum so // far and maximum subarray sum. for (let i = 0; i < n; i++) { res = Math.max(res, prefix_sum[i] - min_prefix_sum); min_prefix_sum = Math.min(min_prefix_sum, prefix_sum[i]); } return res; } // Driver code // Test case 1 let arr1 = [ -2, -3, 4, -1, -2, 1, 5, -3 ]; let n1 = arr1.length; document.write(maximumSumSubarray(arr1, n1) + "<br/>"); // Test case 2 let arr2 = [ 4, -8, 9, -4, 1, -8, -1, 6 ]; let n2 = arr2.length; document.write(maximumSumSubarray(arr2, n2)); </script> Output : 7 9 Simpler and Efficient Solution Time Complexity: O(n). It takes linear time to compute the prefix sum and takes constant time in each iteration of the for loop. Hence overall complexity is O(n).Please note that the above problem can be solved in O(n) time and O(1) extra space using Kadane’s algorithm vt_m AnshulAggarwal susmitakundugoaldanga prefix-sum subarray subarray-sum Arrays Dynamic Programming prefix-sum Arrays Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray Largest Sum Contiguous Subarray Program for Fibonacci numbers Longest Palindromic Substring | Set 1 Longest Increasing Subsequence | DP-3 Find if there is a path between two vertices in an undirected graph
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Apr, 2021" }, { "code": null, "e": 154, "s": 54, "text": "Given an Array of Positive and Negative Integers, find out the Maximum Subarray Sum in that Array. " }, { "code": null, "e": 166, "s": 154, "text": "Examples: " }, { "code": null, "e": 280, "s": 166, "text": "Input1 : arr = {-2, -3, 4, -1, -2, 1, 5, -3}\nOutput1 : 7\n\nInput2 : arr = {4, -8, 9, -4, 1, -8, -1, 6}\nOutput2 : 9" }, { "code": null, "e": 518, "s": 282, "text": "Kadane’s Algorithm solves this problem using Dynamic Programming approach in linear time. Here is another approach using Dynamic Programming and Prefix Sum to find out maximum subarray sum in Linear time.Prerequisite: Prefix Sum Array " }, { "code": null, "e": 646, "s": 518, "text": "1. First calculate the prefix sum (prefix_sum) of the input array. 2. Sum of a subarray from index x to y can be presented as, " }, { "code": null, "e": 690, "s": 651, "text": "3. Now maximum of these subarrays is, " }, { "code": null, "e": 786, "s": 695, "text": "That is, we keep track of minimum prefix sum for x <= y and maximum subarray sum so far. " }, { "code": null, "e": 1353, "s": 786, "text": "Implementation: 1. Calculate the prefix sum of the input array. 2. Initialize : min_prefix_sum = 0, res = -infinite 3. Maintain a loop for i = 0 to n. (n is the size of the input array). a) cand = prefix_sum[i] – mini b) If cand is greater than res (maximum subarray sum so far), then update res by cand. c) If prefix_sum[i] is less than min_prefix_sum (minimum prefix sum so far), then update min_prefix_sum by prefix_sum[i].4. Return res.Reference: Algorithms for the problem of k maximum sums and a VLSI algorithm for the k maximum subarrays problem " }, { "code": null, "e": 1357, "s": 1353, "text": "C++" }, { "code": null, "e": 1362, "s": 1357, "text": "Java" }, { "code": null, "e": 1370, "s": 1362, "text": "Python3" }, { "code": null, "e": 1373, "s": 1370, "text": "C#" }, { "code": null, "e": 1377, "s": 1373, "text": "PHP" }, { "code": null, "e": 1388, "s": 1377, "text": "Javascript" }, { "code": "// C++ program to find out maximum subarray// sum in linear time using prefix sum.#include <iostream>#include <limits>using namespace std; // Function to compute maximum subarray// sum in linear time.int maximumSumSubarray(int arr[], int n){ // Initialize minimum prefix sum to 0. int min_prefix_sum = 0; // Initialize maximum subarray sum so // far to -infinity. int res = numeric_limits<int>::min(); // Initialize and compute the prefix // sum array. int prefix_sum[n]; prefix_sum[0] = arr[0]; for (int i = 1; i < n; i++) prefix_sum[i] = prefix_sum[i - 1] + arr[i]; // loop through the array, keep track // of minimum prefix sum so far and // maximum subarray sum. for (int i = 0; i < n; i++) { res = max(res, prefix_sum[i] - min_prefix_sum); min_prefix_sum = min(min_prefix_sum, prefix_sum[i]); } return res;} // Driver Programint main(){ // Test case 1 int arr1[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; int n1 = sizeof(arr1) / sizeof(arr1[0]); cout << maximumSumSubarray(arr1, n1) << endl; // Test case 2 int arr2[] = { 4, -8, 9, -4, 1, -8, -1, 6 }; int n2 = sizeof(arr2) / sizeof(arr2[0]); cout << maximumSumSubarray(arr2, n2); return 0;}", "e": 2691, "s": 1388, "text": null }, { "code": "// Java program to find// out maximum subarray// sum in linear time// using prefix sum. class GFG{ // Function to compute maximum // subarray sum in linear time. static int maximumSumSubarray(int arr[], int n) { // Initialize minimum // prefix sum to 0. int min_prefix_sum = 0; // Initialize maximum subarray // sum so far to -infinity. int res = Integer.MIN_VALUE; // Initialize and compute // the prefix sum array. int prefix_sum[] = new int[n]; prefix_sum[0] = arr[0]; for (int i = 1; i < n; i++) prefix_sum[i] = prefix_sum[i - 1] + arr[i]; // loop through the array, keep // track of minimum prefix sum so // far and maximum subarray sum. for (int i = 0; i < n; i++) { res = Math.max(res, prefix_sum[i] - min_prefix_sum); min_prefix_sum = Math.min(min_prefix_sum, prefix_sum[i]); } return res; } // Driver Program public static void main (String[] args) { // Test case 1 int arr1[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; int n1 = arr1.length; System.out.println(maximumSumSubarray(arr1, n1)); // Test case 2 int arr2[] = { 4, -8, 9, -4, 1, -8, -1, 6 }; int n2 = arr2.length; System.out.println(maximumSumSubarray(arr2, n2)); }} // This code is contributed by Ansu Kumari.", "e": 4232, "s": 2691, "text": null }, { "code": "# Python3 program to find out# maximum subarray sum in# linear time using prefix# sum.import math # Function to compute maximum# subarray sum in linear time.def maximumSumSubarray(arr, n): # Initialize minimum prefix # sum to 0. min_prefix_sum = 0 # Initialize maximum subarray # sum so far to -infinity. res = -math.inf # Initialize and compute the # prefix sum array. prefix_sum = [] prefix_sum.append(arr[0]) for i in range(1, n): prefix_sum.append(prefix_sum[i - 1] + arr[i]) # loop through the array keep # track of minimum prefix sum # so far and maximum subarray # sum. for i in range(n): res = max(res, prefix_sum[i] - min_prefix_sum) min_prefix_sum = min(min_prefix_sum, prefix_sum[i]) return res # Driver Program # Test case 1arr1 = [ -2, -3, 4, -1, -2, 1, 5, -3 ]n1 = len(arr1)print(maximumSumSubarray(arr1, n1)) # Test case 2arr2 = [ 4, -8, 9, -4, 1, -8, -1, 6 ]n2 = len(arr2)print(maximumSumSubarray(arr2, n2)) # This code is contributed by Ansu Kuamri.", "e": 5302, "s": 4232, "text": null }, { "code": "// C# program to find// out maximum subarray// sum in linear time// using prefix sum.using System; class GFG{ // Function to compute maximum // subarray sum in linear time. static int maximumSumSubarray(int []arr, int n) { // Initialize minimum // prefix sum to 0. int min_prefix_sum = 0; // Initialize maximum subarray // sum so far to -infinity. int res = int.MinValue; // Initialize and compute // the prefix sum array. int []prefix_sum = new int[n]; prefix_sum[0] = arr[0]; for (int i = 1; i < n; i++) prefix_sum[i] = prefix_sum[i - 1] + arr[i]; // loop through the array, keep // track of minimum prefix sum so // far and maximum subarray sum. for (int i = 0; i < n; i++) { res = Math.Max(res, prefix_sum[i] - min_prefix_sum); min_prefix_sum = Math.Min(min_prefix_sum, prefix_sum[i]); } return res; } // Driver Program public static void Main () { // Test case 1 int []arr1 = { -2, -3, 4, -1, -2, 1, 5, -3 }; int n1 = arr1.Length; Console.WriteLine(maximumSumSubarray(arr1, n1)); // Test case 2 int []arr2 = { 4, -8, 9, -4, 1, -8, -1, 6 }; int n2 = arr2.Length; Console.WriteLine(maximumSumSubarray(arr2, n2)); }} // This code is contributed by vt_m.", "e": 6819, "s": 5302, "text": null }, { "code": "<?php// PHP program to find out// maximum subarray sum in// linear time using prefix sum. // Function to compute maximum// subarray sum in linear time.function maximumSumSubarray($arr, $n){ // Initialize minimum // prefix sum to 0. $min_prefix_sum = 0; // Initialize maximum subarray // sum so far to -infinity. $res = PHP_INT_MIN; // Initialize and compute // the prefix sum array. $prefix_sum = array(); $prefix_sum[0] = $arr[0]; for ($i = 1; $i < $n; $i++) $prefix_sum[$i] = $prefix_sum[$i - 1] + $arr[$i]; // loop through the array, // keep track of minimum // prefix sum so far and // maximum subarray sum. for ($i = 0; $i < $n; $i++) { $res = max($res, $prefix_sum[$i] - $min_prefix_sum); $min_prefix_sum = min($min_prefix_sum, $prefix_sum[$i]); } return $res;} // Driver Code // Test case 1$arr1 = array(-2, -3, 4, -1, -2, 1, 5, -3);$n1 = count($arr1);echo maximumSumSubarray($arr1, $n1), \" \\n\" ; // Test case 2$arr2 = array(4, -8, 9, -4, 1, -8, -1, 6); $n2 = count($arr2);echo maximumSumSubarray($arr2, $n2); // This code is contributed by anuj_67.?>", "e": 8094, "s": 6819, "text": null }, { "code": "<script> // JavaScript program to find// out maximum subarray// sum in linear time// using prefix sum. // Function to compute maximum// subarray sum in linear time. function maximumSumSubarray(arr, n) { // Initialize minimum // prefix sum to 0. let min_prefix_sum = 0; // Initialize maximum subarray // sum so far to -infinity. let res = Number.MIN_VALUE; // Initialize and compute // the prefix sum array. let prefix_sum = []; prefix_sum[0] = arr[0]; for (let i = 1; i < n; i++) prefix_sum[i] = prefix_sum[i - 1] + arr[i]; // loop through the array, keep // track of minimum prefix sum so // far and maximum subarray sum. for (let i = 0; i < n; i++) { res = Math.max(res, prefix_sum[i] - min_prefix_sum); min_prefix_sum = Math.min(min_prefix_sum, prefix_sum[i]); } return res; } // Driver code // Test case 1 let arr1 = [ -2, -3, 4, -1, -2, 1, 5, -3 ]; let n1 = arr1.length; document.write(maximumSumSubarray(arr1, n1) + \"<br/>\"); // Test case 2 let arr2 = [ 4, -8, 9, -4, 1, -8, -1, 6 ]; let n2 = arr2.length; document.write(maximumSumSubarray(arr2, n2)); </script>", "e": 9530, "s": 8094, "text": null }, { "code": null, "e": 9540, "s": 9530, "text": "Output : " }, { "code": null, "e": 9544, "s": 9540, "text": "7\n9" }, { "code": null, "e": 9846, "s": 9544, "text": "Simpler and Efficient Solution Time Complexity: O(n). It takes linear time to compute the prefix sum and takes constant time in each iteration of the for loop. Hence overall complexity is O(n).Please note that the above problem can be solved in O(n) time and O(1) extra space using Kadane’s algorithm " }, { "code": null, "e": 9851, "s": 9846, "text": "vt_m" }, { "code": null, "e": 9866, "s": 9851, "text": "AnshulAggarwal" }, { "code": null, "e": 9888, "s": 9866, "text": "susmitakundugoaldanga" }, { "code": null, "e": 9899, "s": 9888, "text": "prefix-sum" }, { "code": null, "e": 9908, "s": 9899, "text": "subarray" }, { "code": null, "e": 9921, "s": 9908, "text": "subarray-sum" }, { "code": null, "e": 9928, "s": 9921, "text": "Arrays" }, { "code": null, "e": 9948, "s": 9928, "text": "Dynamic Programming" }, { "code": null, "e": 9959, "s": 9948, "text": "prefix-sum" }, { "code": null, "e": 9966, "s": 9959, "text": "Arrays" }, { "code": null, "e": 9986, "s": 9966, "text": "Dynamic Programming" }, { "code": null, "e": 10084, "s": 9986, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10099, "s": 10084, "text": "Arrays in Java" }, { "code": null, "e": 10145, "s": 10099, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 10213, "s": 10145, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 10257, "s": 10213, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 10289, "s": 10257, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 10321, "s": 10289, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 10351, "s": 10321, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 10389, "s": 10351, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 10427, "s": 10389, "text": "Longest Increasing Subsequence | DP-3" } ]
Insert a linked list into another linked list
23 Jan, 2022 Given two linked lists, list1 and list2 of sizes m and n respectively. The task is to remove list1’s nodes from the ath node to the bth node and insert the list2 in their place.Examples: Input: list1: 10->11->12->13->14->15, list2: 100->101->102->103, a = 3, b = 4Output: 10->11->12->100->101->102->103->15Explanation: Remove the nodes from 3rd index till 4th index (0-based) from list1 and insert list2 at their place.Input: list1: 1->2, list2: 3->4, a = 0, b = 1Output: 3->4 Approach: The task can be solved using simple iteration over the lists. Follow the below steps to solve the problem: Start iterating over the linked list1 until the ath node Now here take another variable and store the address of (a+1)th node of the list1 and link ath node to the list2 and then iterate over the list2 until the last node and just stop there Iterate from (a+1)th node to the bth node of the list1 and then link the last node of the list2 to the (b+1) node of the list1. Return the head node of the list1 and then print the whole list1 which will be the expected output. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; class Node {public: int data; Node* next;}; // Given a reference (pointer to pointer)// to the head of a list and an int,// appends a new node at the endvoid append(Node** head_ref, int new_data){ /* 1. allocate node */ Node* new_node = new Node(); Node* last = *head_ref; /* used in step 5*/ /* 2. put in the data */ new_node->data = new_data; /* 3. This new node is going to be the last node, so make next of it as NULL*/ new_node->next = NULL; /* 4. If the Linked List is empty, then make the new node as head */ if (*head_ref == NULL) { *head_ref = new_node; return; } /* 5. Else traverse till the last node */ while (last->next != NULL) { last = last->next; } /* 6. Change the next of last node */ last->next = new_node; return;} /* Given a reference (pointer to pointer) to the head of a list */void mergeInBetween(Node** list1, Node** list2, int a, int b){ // keeping the index count int cnt = 0; // taking a new variable for // iterating over the linked list1 Node* list = *list1; // condition for checking // till the count reached index a while (cnt + 1 != a) { // pointing the next node list = list->next; // increasing the count value everytime cnt++; } // Now demo will be used // to iterate from (a+1)th node // of list1 to bth node of list1 Node* demo = list->next; // now we are linking // the ath node to the list2 list->next = *list2; // now we use samp // for iterating over the list2 Node* samp = *list2; // we go until the last node of the list2 while (samp->next != NULL) samp = samp->next; // we go until the bth node of the list1 while (cnt + 1 != b) { demo = demo->next; cnt++; } // now we simply link disconnected // parts of list1 and list2 demo = demo->next; samp->next = demo;} // This function prints contents of// linked list starting from headvoid printList(Node* node){ while (node != NULL) { cout << " " << node->data; node = node->next; }} /* Driver code*/int main(){ Node *list1 = NULL, *list2 = NULL; append(&list1, 10); append(&list1, 11); append(&list1, 12); append(&list1, 13); append(&list1, 14); append(&list1, 15); append(&list2, 100); append(&list2, 101); append(&list2, 102); append(&list2, 103); int a = 3, b = 4; mergeInBetween(&list1, &list2, a, b); printList(list1); return 0;} // Java implementation of the above approachimport java.util.*; class GFG{ static class Node { int data; Node next;}; // Given a reference (pointer to pointer) // to the head of a list and an int, // appends a new node at the endstatic Node append(Node head_ref, int new_data){ /* 1. allocate node */ Node new_node = new Node(); Node last = head_ref; /* used in step 5*/ /* 2. put in the data */ new_node.data = new_data; /* 3. This new node is going to be the last node, so make next of it as null*/ new_node.next = null; /* 4. If the Linked List is empty, then make the new node as head */ if (head_ref == null) { head_ref = new_node; return head_ref; } /* 5. Else traverse till the last node */ while (last.next != null) { last = last.next; } /* 6. Change the next of last node */ last.next = new_node; return head_ref;} /* * Given a reference (pointer to pointer) to the head of a list */static Node mergeInBetween(Node list1, Node list2, int a, int b){ // keeping the index count int cnt = 0; // taking a new variable for // iterating over the linked list1 Node list = list1; // condition for checking // till the count reached index a while (cnt + 1 != a) { // pointing the next node list = list.next; // increasing the count value everytime cnt++; } // Now demo will be used // to iterate from (a+1)th node // of list1 to bth node of list1 Node demo = list.next; // now we are linking // the ath node to the list2 list.next = list2; // now we use samp // for iterating over the list2 Node samp = list2; // we go until the last node of the list2 while (samp.next != null) samp = samp.next; // we go until the bth node of the list1 while (cnt + 1 != b) { demo = demo.next; cnt++; } // now we simply link disconnected // parts of list1 and list2 demo = demo.next; samp.next = demo; return list1;} // This function prints contents of // linked list starting from headstatic void printList(Node node){ while (node != null) { System.out.print(" " + node.data); node = node.next; }} /* Driver code */public static void main(String[] args){ Node list1 = null, list2 = null; list1= append(list1, 10); list1 = append(list1, 11); list1= append(list1, 12); list1 = append(list1, 13); list1 =append(list1, 14); list1 = append(list1, 15); list2 = append(list2, 100); list2 = append(list2, 101); list2 = append(list2, 102); list2 =append(list2, 103); int a = 3, b = 4; list1 = mergeInBetween(list1, list2, a, b); printList(list1);}} // This code is contributed by gauravrajput1 # Python implementation of the above approachclass Node: def __init__(self): self.data = 0; self.next = None; # Given a reference (pointer to pointer)# to the head of a list and an int,# appends a new Node at the enddef append(head_ref, new_data): ''' 1. allocate Node ''' new_Node = Node(); last = head_ref; ''' used in step 5 ''' ''' 2. put in the data ''' new_Node.data = new_data; ''' * 3. This new Node is going to be the last Node, so make next of it as None ''' new_Node.next = None; ''' * 4. If the Linked List is empty, then make the new Node as head ''' if (head_ref == None): head_ref = new_Node; return head_ref; ''' 5. Else traverse till the last Node ''' while (last.next != None): last = last.next; ''' 6. Change the next of last Node ''' last.next = new_Node; return head_ref; ''' * Given a reference (pointer to pointer) to the head of a list '''def mergeInBetween(list1, list2, a, b): # keeping the index count cnt = 0; # taking a new variable for # iterating over the linked list1 list = list1; # condition for checking # till the count reached index a while (cnt + 1 != a): # pointing the next Node list = list.next; # increasing the count value everytime cnt += 1; # Now demo will be used # to iterate from (a+1)th Node # of list1 to bth Node of list1 demo = list.next; # now we are linking # the ath Node to the list2 list.next = list2; # now we use samp # for iterating over the list2 samp = list2; # we go until the last Node of the list2 while (samp.next != None): samp = samp.next; # we go until the bth Node of the list1 while (cnt + 1 != b): demo = demo.next; cnt+=1; # now we simply link disconnected # parts of list1 and list2 demo = demo.next; samp.next = demo; return list1; # This function prints contents of# linked list starting from headdef printList(Node): while (Node != None): print(Node.data, end=" "); Node = Node.next; ''' Driver code '''if __name__ == '__main__': list1 = None; list2 = None; list1 = append(list1, 10); list1 = append(list1, 11); list1 = append(list1, 12); list1 = append(list1, 13); list1 = append(list1, 14); list1 = append(list1, 15); list2 = append(list2, 100); list2 = append(list2, 101); list2 = append(list2, 102); list2 = append(list2, 103); a = 3 b = 4; list1 = mergeInBetween(list1, list2, a, b); printList(list1); # This code is contributed by gauravrajput1 // C# implementation of the above approachusing System; public class GFG{ class Node { public int data; public Node next; }; // Given a reference (pointer to pointer) // to the head of a list and an int, // appends a new node at the end static Node append(Node head_ref, int new_data) { /* 1. allocate node */ Node new_node = new Node(); Node last = head_ref; /* used in step 5*/ /* 2. put in the data */ new_node.data = new_data; /* 3. This new node is going to be the last node, so make next of it as null*/ new_node.next = null; /* 4. If the Linked List is empty, then make the new node as head */ if (head_ref == null) { head_ref = new_node; return head_ref; } /* 5. Else traverse till the last node */ while (last.next != null) { last = last.next; } /* 6. Change the next of last node */ last.next = new_node; return head_ref; } /* * Given a reference (pointer to pointer) to the head of a list */ static Node mergeInBetween(Node list1, Node list2, int a, int b) { // keeping the index count int cnt = 0; // taking a new variable for // iterating over the linked list1 Node list = list1; // condition for checking // till the count reached index a while (cnt + 1 != a) { // pointing the next node list = list.next; // increasing the count value everytime cnt++; } // Now demo will be used // to iterate from (a+1)th node // of list1 to bth node of list1 Node demo = list.next; // now we are linking // the ath node to the list2 list.next = list2; // now we use samp // for iterating over the list2 Node samp = list2; // we go until the last node of the list2 while (samp.next != null) samp = samp.next; // we go until the bth node of the list1 while (cnt + 1 != b) { demo = demo.next; cnt++; } // now we simply link disconnected // parts of list1 and list2 demo = demo.next; samp.next = demo; return list1; } // This function prints contents of // linked list starting from head static void printList(Node node) { while (node != null) { Console.Write(" " + node.data); node = node.next; } } /* Driver code */ public static void Main(String[] args) { Node list1 = null, list2 = null; list1= append(list1, 10); list1 = append(list1, 11); list1= append(list1, 12); list1 = append(list1, 13); list1 = append(list1, 14); list1 = append(list1, 15); list2 = append(list2, 100); list2 = append(list2, 101); list2 = append(list2, 102); list2 = append(list2, 103); int a = 3, b = 4; list1 = mergeInBetween(list1, list2, a, b); printList(list1); }} // This code is contributed by 29AjayKumar <script>// javascript implementation of the above approach class Node { constructor(){ this.data = 0; this.next = null; }} // Given a reference (pointer to pointer) // to the head of a list and an int, // appends a new node at the endfunction append(head_ref , new_data){ /* 1. allocate node */ var new_node = new Node(); var last = head_ref; /* used in step 5*/ /* 2. put in the data */ new_node.data = new_data; /* 3. This new node is going to be the last node, so make next of it as null*/ new_node.next = null; /* 4. If the Linked List is empty, then make the new node as head */ if (head_ref == null) { head_ref = new_node; return head_ref; } /* 5. Else traverse till the last node */ while (last.next != null) { last = last.next; } /* 6. Change the next of last node */ last.next = new_node; return head_ref;} /* * Given a reference (pointer to pointer) to the head of a list */function mergeInBetween(list1, list2, a , b){ // keeping the index count var cnt = 0; // taking a new variable for // iterating over the linked list1 var list = list1; // condition for checking // till the count reached index a while (cnt + 1 != a) { // pointing the next node list = list.next; // increasing the count value everytime cnt++; } // Now demo will be used // to iterate from (a+1)th node // of list1 to bth node of list1 var demo = list.next; // now we are linking // the ath node to the list2 list.next = list2; // now we use samp // for iterating over the list2 var samp = list2; // we go until the last node of the list2 while (samp.next != null) samp = samp.next; // we go until the bth node of the list1 while (cnt + 1 != b) { demo = demo.next; cnt++; } // now we simply link disconnected // parts of list1 and list2 demo = demo.next; samp.next = demo; return list1;} // This function prints contents of // linked list starting from headfunction printList(node){ while (node != null) { document.write(" " + node.data); node = node.next; }} /* Driver code */ var list1 = null, list2 = null; list1= append(list1, 10); list1 = append(list1, 11); list1= append(list1, 12); list1 = append(list1, 13); list1 =append(list1, 14); list1 = append(list1, 15); list2 = append(list2, 100); list2 = append(list2, 101); list2 = append(list2, 102); list2 =append(list2, 103); var a = 3, b = 4; list1 = mergeInBetween(list1, list2, a, b); printList(list1); // This code is contributed by gauravrajput1</script> 10 11 12 100 101 102 103 15 Time Complexity: O(m+n), n is the length of list1 and m is the length of list2Auxiliary Space: O(1) GauravRajput1 29AjayKumar simranarora5sos Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Types of Linked List Rearrange a given linked list in-place. Find first node of loop in a linked list Add two numbers represented by linked lists | Set 2 Circular Singly Linked List | Insertion Flattening a Linked List Real-time application of Data Structures Clone a linked list with next and random pointer | Set 1
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jan, 2022" }, { "code": null, "e": 239, "s": 52, "text": "Given two linked lists, list1 and list2 of sizes m and n respectively. The task is to remove list1’s nodes from the ath node to the bth node and insert the list2 in their place.Examples:" }, { "code": null, "e": 529, "s": 239, "text": "Input: list1: 10->11->12->13->14->15, list2: 100->101->102->103, a = 3, b = 4Output: 10->11->12->100->101->102->103->15Explanation: Remove the nodes from 3rd index till 4th index (0-based) from list1 and insert list2 at their place.Input: list1: 1->2, list2: 3->4, a = 0, b = 1Output: 3->4" }, { "code": null, "e": 646, "s": 529, "text": "Approach: The task can be solved using simple iteration over the lists. Follow the below steps to solve the problem:" }, { "code": null, "e": 703, "s": 646, "text": "Start iterating over the linked list1 until the ath node" }, { "code": null, "e": 888, "s": 703, "text": "Now here take another variable and store the address of (a+1)th node of the list1 and link ath node to the list2 and then iterate over the list2 until the last node and just stop there" }, { "code": null, "e": 1016, "s": 888, "text": "Iterate from (a+1)th node to the bth node of the list1 and then link the last node of the list2 to the (b+1) node of the list1." }, { "code": null, "e": 1116, "s": 1016, "text": "Return the head node of the list1 and then print the whole list1 which will be the expected output." }, { "code": null, "e": 1167, "s": 1116, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1171, "s": 1167, "text": "C++" }, { "code": null, "e": 1176, "s": 1171, "text": "Java" }, { "code": null, "e": 1184, "s": 1176, "text": "Python3" }, { "code": null, "e": 1187, "s": 1184, "text": "C#" }, { "code": null, "e": 1198, "s": 1187, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; class Node {public: int data; Node* next;}; // Given a reference (pointer to pointer)// to the head of a list and an int,// appends a new node at the endvoid append(Node** head_ref, int new_data){ /* 1. allocate node */ Node* new_node = new Node(); Node* last = *head_ref; /* used in step 5*/ /* 2. put in the data */ new_node->data = new_data; /* 3. This new node is going to be the last node, so make next of it as NULL*/ new_node->next = NULL; /* 4. If the Linked List is empty, then make the new node as head */ if (*head_ref == NULL) { *head_ref = new_node; return; } /* 5. Else traverse till the last node */ while (last->next != NULL) { last = last->next; } /* 6. Change the next of last node */ last->next = new_node; return;} /* Given a reference (pointer to pointer) to the head of a list */void mergeInBetween(Node** list1, Node** list2, int a, int b){ // keeping the index count int cnt = 0; // taking a new variable for // iterating over the linked list1 Node* list = *list1; // condition for checking // till the count reached index a while (cnt + 1 != a) { // pointing the next node list = list->next; // increasing the count value everytime cnt++; } // Now demo will be used // to iterate from (a+1)th node // of list1 to bth node of list1 Node* demo = list->next; // now we are linking // the ath node to the list2 list->next = *list2; // now we use samp // for iterating over the list2 Node* samp = *list2; // we go until the last node of the list2 while (samp->next != NULL) samp = samp->next; // we go until the bth node of the list1 while (cnt + 1 != b) { demo = demo->next; cnt++; } // now we simply link disconnected // parts of list1 and list2 demo = demo->next; samp->next = demo;} // This function prints contents of// linked list starting from headvoid printList(Node* node){ while (node != NULL) { cout << \" \" << node->data; node = node->next; }} /* Driver code*/int main(){ Node *list1 = NULL, *list2 = NULL; append(&list1, 10); append(&list1, 11); append(&list1, 12); append(&list1, 13); append(&list1, 14); append(&list1, 15); append(&list2, 100); append(&list2, 101); append(&list2, 102); append(&list2, 103); int a = 3, b = 4; mergeInBetween(&list1, &list2, a, b); printList(list1); return 0;}", "e": 3821, "s": 1198, "text": null }, { "code": "// Java implementation of the above approachimport java.util.*; class GFG{ static class Node { int data; Node next;}; // Given a reference (pointer to pointer) // to the head of a list and an int, // appends a new node at the endstatic Node append(Node head_ref, int new_data){ /* 1. allocate node */ Node new_node = new Node(); Node last = head_ref; /* used in step 5*/ /* 2. put in the data */ new_node.data = new_data; /* 3. This new node is going to be the last node, so make next of it as null*/ new_node.next = null; /* 4. If the Linked List is empty, then make the new node as head */ if (head_ref == null) { head_ref = new_node; return head_ref; } /* 5. Else traverse till the last node */ while (last.next != null) { last = last.next; } /* 6. Change the next of last node */ last.next = new_node; return head_ref;} /* * Given a reference (pointer to pointer) to the head of a list */static Node mergeInBetween(Node list1, Node list2, int a, int b){ // keeping the index count int cnt = 0; // taking a new variable for // iterating over the linked list1 Node list = list1; // condition for checking // till the count reached index a while (cnt + 1 != a) { // pointing the next node list = list.next; // increasing the count value everytime cnt++; } // Now demo will be used // to iterate from (a+1)th node // of list1 to bth node of list1 Node demo = list.next; // now we are linking // the ath node to the list2 list.next = list2; // now we use samp // for iterating over the list2 Node samp = list2; // we go until the last node of the list2 while (samp.next != null) samp = samp.next; // we go until the bth node of the list1 while (cnt + 1 != b) { demo = demo.next; cnt++; } // now we simply link disconnected // parts of list1 and list2 demo = demo.next; samp.next = demo; return list1;} // This function prints contents of // linked list starting from headstatic void printList(Node node){ while (node != null) { System.out.print(\" \" + node.data); node = node.next; }} /* Driver code */public static void main(String[] args){ Node list1 = null, list2 = null; list1= append(list1, 10); list1 = append(list1, 11); list1= append(list1, 12); list1 = append(list1, 13); list1 =append(list1, 14); list1 = append(list1, 15); list2 = append(list2, 100); list2 = append(list2, 101); list2 = append(list2, 102); list2 =append(list2, 103); int a = 3, b = 4; list1 = mergeInBetween(list1, list2, a, b); printList(list1);}} // This code is contributed by gauravrajput1", "e": 6634, "s": 3821, "text": null }, { "code": "# Python implementation of the above approachclass Node: def __init__(self): self.data = 0; self.next = None; # Given a reference (pointer to pointer)# to the head of a list and an int,# appends a new Node at the enddef append(head_ref, new_data): ''' 1. allocate Node ''' new_Node = Node(); last = head_ref; ''' used in step 5 ''' ''' 2. put in the data ''' new_Node.data = new_data; ''' * 3. This new Node is going to be the last Node, so make next of it as None ''' new_Node.next = None; ''' * 4. If the Linked List is empty, then make the new Node as head ''' if (head_ref == None): head_ref = new_Node; return head_ref; ''' 5. Else traverse till the last Node ''' while (last.next != None): last = last.next; ''' 6. Change the next of last Node ''' last.next = new_Node; return head_ref; ''' * Given a reference (pointer to pointer) to the head of a list '''def mergeInBetween(list1, list2, a, b): # keeping the index count cnt = 0; # taking a new variable for # iterating over the linked list1 list = list1; # condition for checking # till the count reached index a while (cnt + 1 != a): # pointing the next Node list = list.next; # increasing the count value everytime cnt += 1; # Now demo will be used # to iterate from (a+1)th Node # of list1 to bth Node of list1 demo = list.next; # now we are linking # the ath Node to the list2 list.next = list2; # now we use samp # for iterating over the list2 samp = list2; # we go until the last Node of the list2 while (samp.next != None): samp = samp.next; # we go until the bth Node of the list1 while (cnt + 1 != b): demo = demo.next; cnt+=1; # now we simply link disconnected # parts of list1 and list2 demo = demo.next; samp.next = demo; return list1; # This function prints contents of# linked list starting from headdef printList(Node): while (Node != None): print(Node.data, end=\" \"); Node = Node.next; ''' Driver code '''if __name__ == '__main__': list1 = None; list2 = None; list1 = append(list1, 10); list1 = append(list1, 11); list1 = append(list1, 12); list1 = append(list1, 13); list1 = append(list1, 14); list1 = append(list1, 15); list2 = append(list2, 100); list2 = append(list2, 101); list2 = append(list2, 102); list2 = append(list2, 103); a = 3 b = 4; list1 = mergeInBetween(list1, list2, a, b); printList(list1); # This code is contributed by gauravrajput1", "e": 9325, "s": 6634, "text": null }, { "code": "// C# implementation of the above approachusing System; public class GFG{ class Node { public int data; public Node next; }; // Given a reference (pointer to pointer) // to the head of a list and an int, // appends a new node at the end static Node append(Node head_ref, int new_data) { /* 1. allocate node */ Node new_node = new Node(); Node last = head_ref; /* used in step 5*/ /* 2. put in the data */ new_node.data = new_data; /* 3. This new node is going to be the last node, so make next of it as null*/ new_node.next = null; /* 4. If the Linked List is empty, then make the new node as head */ if (head_ref == null) { head_ref = new_node; return head_ref; } /* 5. Else traverse till the last node */ while (last.next != null) { last = last.next; } /* 6. Change the next of last node */ last.next = new_node; return head_ref; } /* * Given a reference (pointer to pointer) to the head of a list */ static Node mergeInBetween(Node list1, Node list2, int a, int b) { // keeping the index count int cnt = 0; // taking a new variable for // iterating over the linked list1 Node list = list1; // condition for checking // till the count reached index a while (cnt + 1 != a) { // pointing the next node list = list.next; // increasing the count value everytime cnt++; } // Now demo will be used // to iterate from (a+1)th node // of list1 to bth node of list1 Node demo = list.next; // now we are linking // the ath node to the list2 list.next = list2; // now we use samp // for iterating over the list2 Node samp = list2; // we go until the last node of the list2 while (samp.next != null) samp = samp.next; // we go until the bth node of the list1 while (cnt + 1 != b) { demo = demo.next; cnt++; } // now we simply link disconnected // parts of list1 and list2 demo = demo.next; samp.next = demo; return list1; } // This function prints contents of // linked list starting from head static void printList(Node node) { while (node != null) { Console.Write(\" \" + node.data); node = node.next; } } /* Driver code */ public static void Main(String[] args) { Node list1 = null, list2 = null; list1= append(list1, 10); list1 = append(list1, 11); list1= append(list1, 12); list1 = append(list1, 13); list1 = append(list1, 14); list1 = append(list1, 15); list2 = append(list2, 100); list2 = append(list2, 101); list2 = append(list2, 102); list2 = append(list2, 103); int a = 3, b = 4; list1 = mergeInBetween(list1, list2, a, b); printList(list1); }} // This code is contributed by 29AjayKumar", "e": 12153, "s": 9325, "text": null }, { "code": "<script>// javascript implementation of the above approach class Node { constructor(){ this.data = 0; this.next = null; }} // Given a reference (pointer to pointer) // to the head of a list and an int, // appends a new node at the endfunction append(head_ref , new_data){ /* 1. allocate node */ var new_node = new Node(); var last = head_ref; /* used in step 5*/ /* 2. put in the data */ new_node.data = new_data; /* 3. This new node is going to be the last node, so make next of it as null*/ new_node.next = null; /* 4. If the Linked List is empty, then make the new node as head */ if (head_ref == null) { head_ref = new_node; return head_ref; } /* 5. Else traverse till the last node */ while (last.next != null) { last = last.next; } /* 6. Change the next of last node */ last.next = new_node; return head_ref;} /* * Given a reference (pointer to pointer) to the head of a list */function mergeInBetween(list1, list2, a , b){ // keeping the index count var cnt = 0; // taking a new variable for // iterating over the linked list1 var list = list1; // condition for checking // till the count reached index a while (cnt + 1 != a) { // pointing the next node list = list.next; // increasing the count value everytime cnt++; } // Now demo will be used // to iterate from (a+1)th node // of list1 to bth node of list1 var demo = list.next; // now we are linking // the ath node to the list2 list.next = list2; // now we use samp // for iterating over the list2 var samp = list2; // we go until the last node of the list2 while (samp.next != null) samp = samp.next; // we go until the bth node of the list1 while (cnt + 1 != b) { demo = demo.next; cnt++; } // now we simply link disconnected // parts of list1 and list2 demo = demo.next; samp.next = demo; return list1;} // This function prints contents of // linked list starting from headfunction printList(node){ while (node != null) { document.write(\" \" + node.data); node = node.next; }} /* Driver code */ var list1 = null, list2 = null; list1= append(list1, 10); list1 = append(list1, 11); list1= append(list1, 12); list1 = append(list1, 13); list1 =append(list1, 14); list1 = append(list1, 15); list2 = append(list2, 100); list2 = append(list2, 101); list2 = append(list2, 102); list2 =append(list2, 103); var a = 3, b = 4; list1 = mergeInBetween(list1, list2, a, b); printList(list1); // This code is contributed by gauravrajput1</script>", "e": 14935, "s": 12153, "text": null }, { "code": null, "e": 14963, "s": 14935, "text": "10 11 12 100 101 102 103 15" }, { "code": null, "e": 15065, "s": 14965, "text": "Time Complexity: O(m+n), n is the length of list1 and m is the length of list2Auxiliary Space: O(1)" }, { "code": null, "e": 15079, "s": 15065, "text": "GauravRajput1" }, { "code": null, "e": 15091, "s": 15079, "text": "29AjayKumar" }, { "code": null, "e": 15107, "s": 15091, "text": "simranarora5sos" }, { "code": null, "e": 15119, "s": 15107, "text": "Linked List" }, { "code": null, "e": 15131, "s": 15119, "text": "Linked List" }, { "code": null, "e": 15229, "s": 15131, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15261, "s": 15229, "text": "Introduction to Data Structures" }, { "code": null, "e": 15325, "s": 15261, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 15346, "s": 15325, "text": "Types of Linked List" }, { "code": null, "e": 15386, "s": 15346, "text": "Rearrange a given linked list in-place." }, { "code": null, "e": 15427, "s": 15386, "text": "Find first node of loop in a linked list" }, { "code": null, "e": 15479, "s": 15427, "text": "Add two numbers represented by linked lists | Set 2" }, { "code": null, "e": 15519, "s": 15479, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 15544, "s": 15519, "text": "Flattening a Linked List" }, { "code": null, "e": 15585, "s": 15544, "text": "Real-time application of Data Structures" } ]
Print a 2 D Array or Matrix in C#
First, set a two-dimensional array. int[,] arr = new int[10, 10]; Now, get the elements from the user − for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { arr[i, j] = Convert.ToInt16(Console.ReadLine()); } } Let us see the complete example to display the matrix. Live Demo using System; using System.Linq; class Demo { static void Main() { int m, n, i, j; // rows and columns of the matrix+ m = 2; n = 2; int[,] arr = new int[10, 10]; Console.Write("Enter elements of the Matrix: "); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { arr[i, j] = Convert.ToInt16(Console.ReadLine()); } } Console.WriteLine("Printing Matrix: "); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { Console.Write(arr[i, j] + "\t"); } Console.WriteLine(); } Console.ReadLine(); } } The following is the output. Enter elements of the Matrix: 5 10 12 15 Printing Matrix: 510 1215
[ { "code": null, "e": 1223, "s": 1187, "text": "First, set a two-dimensional array." }, { "code": null, "e": 1253, "s": 1223, "text": "int[,] arr = new int[10, 10];" }, { "code": null, "e": 1291, "s": 1253, "text": "Now, get the elements from the user −" }, { "code": null, "e": 1408, "s": 1291, "text": "for (i = 0; i < m; i++) {\n for (j = 0; j < n; j++) {\n arr[i, j] = Convert.ToInt16(Console.ReadLine());\n }\n}" }, { "code": null, "e": 1463, "s": 1408, "text": "Let us see the complete example to display the matrix." }, { "code": null, "e": 1474, "s": 1463, "text": " Live Demo" }, { "code": null, "e": 2119, "s": 1474, "text": "using System;\nusing System.Linq;\n\nclass Demo {\n\n static void Main() {\n\n int m, n, i, j;\n\n // rows and columns of the matrix+\n m = 2;\n n = 2;\n\n int[,] arr = new int[10, 10];\n\n Console.Write(\"Enter elements of the Matrix: \");\n for (i = 0; i < m; i++) {\n for (j = 0; j < n; j++) {\n arr[i, j] = Convert.ToInt16(Console.ReadLine());\n }\n }\n\n Console.WriteLine(\"Printing Matrix: \");\n for (i = 0; i < m; i++) {\n for (j = 0; j < n; j++) {\n Console.Write(arr[i, j] + \"\\t\");\n }\n Console.WriteLine();\n }\n\n Console.ReadLine();\n }\n}" }, { "code": null, "e": 2148, "s": 2119, "text": "The following is the output." }, { "code": null, "e": 2215, "s": 2148, "text": "Enter elements of the Matrix: 5 10 12 15\nPrinting Matrix:\n510\n1215" } ]
Python os.chdir() method
01 Nov, 2021 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.chdir() method in Python used to change the current working directory to specified path. It takes only a single argument as new directory path. Syntax: os.chdir(path)Parameters: path: A complete path of directory to be changed to new directory path.Returns: Doesn’t return any value Code #1: Use chdir() to change the directory Python3 # Python3 program to change the# directory of file using os.chdir() method # import os libraryimport os # change the current directory# to specified directoryos.chdir(r"C:\Users\Gfg\Desktop\geeks") print("Directory changed") Output: Directory changed Code #2: Use of os.getcwd() To know the current working directory of the file, getcwd() method can be used. After changing the path, one can verify the path of current working directory using this method. Python3 # import os moduleimport os # change the current working directory# to specified pathos.chdir('c:\\gfg_dir') # verify the path using getcwd()cwd = os.getcwd() # print the current directoryprint("Current working directory is:", cwd) Output: Current working directory is: c:\\gfg_dir Code #3: Handling the errors while changing the directory Python3 # importing all necessary librariesimport sys, os # initial directorycwd = os.getcwd() # some non existing directoryfd = 'false_dir / temp' # trying to insert to false directorytry: os.chdir(fd) print("Inserting inside-", os.getcwd()) # Caching the exception except: print("Something wrong with specified\ directory. Exception- ", sys.exc_info()) # handling with finally finally: print("Restoring the path") os.chdir(cwd) print("Current directory is-", os.getcwd()) Output: Inserting inside- c:\gfg_dir\gfg Something wrong with specified directory. Exception- Restoring the path Current directory is- c:\gfg_dir\gfg sumitgumber28 prachisoda1234 python-modules python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? Python String | replace() *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Nov, 2021" }, { "code": null, "e": 422, "s": 54, "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.chdir() method in Python used to change the current working directory to specified path. It takes only a single argument as new directory path. " }, { "code": null, "e": 561, "s": 422, "text": "Syntax: os.chdir(path)Parameters: path: A complete path of directory to be changed to new directory path.Returns: Doesn’t return any value" }, { "code": null, "e": 606, "s": 561, "text": "Code #1: Use chdir() to change the directory" }, { "code": null, "e": 614, "s": 606, "text": "Python3" }, { "code": "# Python3 program to change the# directory of file using os.chdir() method # import os libraryimport os # change the current directory# to specified directoryos.chdir(r\"C:\\Users\\Gfg\\Desktop\\geeks\") print(\"Directory changed\")", "e": 839, "s": 614, "text": null }, { "code": null, "e": 849, "s": 839, "text": "Output: " }, { "code": null, "e": 867, "s": 849, "text": "Directory changed" }, { "code": null, "e": 1073, "s": 867, "text": "Code #2: Use of os.getcwd() To know the current working directory of the file, getcwd() method can be used. After changing the path, one can verify the path of current working directory using this method. " }, { "code": null, "e": 1081, "s": 1073, "text": "Python3" }, { "code": "# import os moduleimport os # change the current working directory# to specified pathos.chdir('c:\\\\gfg_dir') # verify the path using getcwd()cwd = os.getcwd() # print the current directoryprint(\"Current working directory is:\", cwd)", "e": 1313, "s": 1081, "text": null }, { "code": null, "e": 1323, "s": 1313, "text": "Output: " }, { "code": null, "e": 1365, "s": 1323, "text": "Current working directory is: c:\\\\gfg_dir" }, { "code": null, "e": 1426, "s": 1365, "text": " Code #3: Handling the errors while changing the directory " }, { "code": null, "e": 1434, "s": 1426, "text": "Python3" }, { "code": "# importing all necessary librariesimport sys, os # initial directorycwd = os.getcwd() # some non existing directoryfd = 'false_dir / temp' # trying to insert to false directorytry: os.chdir(fd) print(\"Inserting inside-\", os.getcwd()) # Caching the exception except: print(\"Something wrong with specified\\ directory. Exception- \", sys.exc_info()) # handling with finally finally: print(\"Restoring the path\") os.chdir(cwd) print(\"Current directory is-\", os.getcwd())", "e": 1951, "s": 1434, "text": null }, { "code": null, "e": 1960, "s": 1951, "text": "Output: " }, { "code": null, "e": 2103, "s": 1960, "text": "Inserting inside- c:\\gfg_dir\\gfg\nSomething wrong with specified directory. Exception- \nRestoring the path\nCurrent directory is- c:\\gfg_dir\\gfg" }, { "code": null, "e": 2117, "s": 2103, "text": "sumitgumber28" }, { "code": null, "e": 2132, "s": 2117, "text": "prachisoda1234" }, { "code": null, "e": 2147, "s": 2132, "text": "python-modules" }, { "code": null, "e": 2164, "s": 2147, "text": "python-os-module" }, { "code": null, "e": 2171, "s": 2164, "text": "Python" }, { "code": null, "e": 2269, "s": 2171, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2287, "s": 2269, "text": "Python Dictionary" }, { "code": null, "e": 2329, "s": 2287, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2351, "s": 2329, "text": "Enumerate() in Python" }, { "code": null, "e": 2386, "s": 2351, "text": "Read a file line by line in Python" }, { "code": null, "e": 2418, "s": 2386, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2444, "s": 2418, "text": "Python String | replace()" }, { "code": null, "e": 2473, "s": 2444, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2500, "s": 2473, "text": "Python Classes and Objects" }, { "code": null, "e": 2521, "s": 2500, "text": "Python OOPs Concepts" } ]
Length of the longest substring | Practice | GeeksforGeeks
Given a string S, find the length of the longest substring without repeating characters. Example 1: Input: S = "geeksforgeeks" Output: 7 Explanation: Longest substring is "eksforg". Example 2: Input: S = "abdefgabef" Output: 6 Explanation: Longest substring are "abdefg" , "bdefga" and "defgab". Your Task: You don't need to take input or print anything. Your task is to complete the function longestUniqueSubsttr() which takes a string S as and returns the length of the longest substring. Expected Time Complexity: O(|S|). Expected Auxiliary Space: O(K) where K is constant. 0 himanshukug19cs21 hours ago int ans=0; ArrayDeque<Character> dq = new ArrayDeque<>(); for(int i=0;i<S.length();i++){ char ch=S.charAt(i); if(!dq.contains(ch)){ dq.add(ch); } else{ ans=Math.max(ans,dq.size()); while(dq.contains(ch))dq.remove(); dq.add(ch); } } if(!dq.isEmpty()) ans=Math.max(ans,dq.size()); return ans; +1 badgujarsachin833 days ago int longestUniqueSubsttr(string S){ //code int maxi=INT_MIN, i=0,j=0,n=S.size(); int arr[26]={0}; while(j<n){ arr[S[j]-'a']++; while(i<n && arr[S[j]-'a']!=1){ arr[S[i]-'a']--; i++; } maxi=max(maxi,j-i+1); j++; } return maxi; } 0 kake13372 weeks ago int longestUniqueSubsttr(string S){ vector<int>v(26,-1); int i=0,j=0,r=1; while(j<S.length()) { if(v[S[j]-'a']!=-1) { if(v[S[j]-'a']>=i) i=v[S[j]-'a']+1; } v[S[j]-'a']=j; r=max(r,j-i+1); j++; } return r; } 0 koresachin19993 weeks ago class Solution{ int longestUniqueSubsttr(String s){ int n=s.length(); HashMap<Character, Integer> map=new HashMap<>(); int ans=0; int start=0, end=0; while(end<n) { map.put(s.charAt(end), map.getOrDefault(s.charAt(end),0)+1); while(start<=end&& map.get(s.charAt(end))>1) { map.put(s.charAt(start),map.get(s.charAt(start))-1); start++; } ans=Math.max(ans, end-start+1); end++; } return ans; }} 0 kumaraditya338713 weeks ago // please up vote this code ☺️ int longestUniqueSubsttr(string S){ //code int i=0; int j=0; int mx=INT_MIN; map<char,int>mp; while(j<S.length()) { mp[S[j]]++; if(mp.size()>j-i+1) j++; else if(mp.size()==j-i+1) { mx=max(mx , j-i+1); j++; } else if(mp.size()<j-i+1) { while(mp.size()<j-i+1) { mp[S[i]]-- ; if(mp[S[i]]==0) mp.erase(S[i]); i++; } j++; } }//while loop end return mx; } 0 ujjwalraj57983 weeks ago O(N) solution using two pointers int longestUniqueSubsttr(string S){ //code int n=S.length(); vector<int>freq; freq.resize(26,0); int ans=0; int head=-1;int tail=0; while(tail<n){ //head move while(head+1<n&&freq[S[head+1]-'a']==0){ head++; freq[S[head]-'a']++; } //process ans=max(ans,head-tail+1); //tail updation if(head>=tail){ freq[S[tail]-'a']--; tail++; }else{ tail++; head=tail-1; } } return ans; } 0 iamkhijiralam1 month ago Simple C++ | O(N) solution |Accepted int longestUniqueSubsttr(string S){ //code int start=0,next=0; vector<int> lastIndex(256,-1); int longestSoFar=0; while(S[next]!='\0'){ char nextChar=S[next]; if(lastIndex[nextChar]<start){ next++; } else{ int currentOP=next-start; if(currentOP > longestSoFar){ longestSoFar= currentOP; } start=lastIndex[nextChar] +1; next++; } lastIndex[nextChar]=next-1; } int currentOP=next-start; if(currentOP > longestSoFar){ longestSoFar= currentOP; } return longestSoFar; } +1 namantam11 month ago Simple C++ | O(N) solution | Without set or hashmap class Solution{ int arr[26] = {0}; bool contains(char c) { return arr[c - 'a']; } void erase(char c) { arr[c - 'a'] = 0; } void insert(char c) { arr[c - 'a'] = 1; } public: int longestUniqueSubsttr(string s){ int i=0, j=0, ans=0, n=s.size(); while (j < n) { while (i<n and contains(s[j])) { erase(s[i++]); } insert(s[j++]); ans = max(ans, j-i); } return ans; } }; +1 abhinavjain78981 month ago Java Easy Solution Using HashMap class Solution{ int longestUniqueSubsttr(String s){ HashMap<Character,Integer> hm = new HashMap<>(); int max = 0; int n = s.length(); for(int i=0;i<n;i++){ char temp = s.charAt(i); if(!hm.containsKey(temp)){ hm.put(temp,i); } else{ i = hm.get(temp); hm.clear(); } if(hm.size()>max){ max = hm.size(); } } return max; } } 0 mebhowmik3211 month ago Successful C++ solution: int longestUniqueSubsttr(string S){ //code vector<int> vec(26,0); int res=0; int l=0,r=0,n=S.length(); while(r<n) { int c=S[r]-'a'; vec[c]++; while(vec[c]>1) vec[S[l++]-'a']--; res=max(r-l+1,res); r++; } return res; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 328, "s": 238, "text": "Given a string S, find the length of the longest substring without repeating characters. " }, { "code": null, "e": 340, "s": 328, "text": "\nExample 1:" }, { "code": null, "e": 422, "s": 340, "text": "Input:\nS = \"geeksforgeeks\"\nOutput:\n7\nExplanation:\nLongest substring is\n\"eksforg\"." }, { "code": null, "e": 433, "s": 422, "text": "Example 2:" }, { "code": null, "e": 536, "s": 433, "text": "Input:\nS = \"abdefgabef\"\nOutput:\n6\nExplanation:\nLongest substring are\n\"abdefg\" , \"bdefga\" and \"defgab\"." }, { "code": null, "e": 734, "s": 538, "text": "Your Task:\nYou don't need to take input or print anything. Your task is to complete the function longestUniqueSubsttr() which takes a string S as and returns the length of the longest substring. " }, { "code": null, "e": 822, "s": 736, "text": "Expected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(K) where K is constant." }, { "code": null, "e": 824, "s": 822, "text": "0" }, { "code": null, "e": 852, "s": 824, "text": "himanshukug19cs21 hours ago" }, { "code": null, "e": 1257, "s": 852, "text": " int ans=0; ArrayDeque<Character> dq = new ArrayDeque<>(); for(int i=0;i<S.length();i++){ char ch=S.charAt(i); if(!dq.contains(ch)){ dq.add(ch); } else{ ans=Math.max(ans,dq.size()); while(dq.contains(ch))dq.remove(); dq.add(ch); } } if(!dq.isEmpty()) ans=Math.max(ans,dq.size()); return ans;" }, { "code": null, "e": 1260, "s": 1257, "text": "+1" }, { "code": null, "e": 1287, "s": 1260, "text": "badgujarsachin833 days ago" }, { "code": null, "e": 1638, "s": 1287, "text": "int longestUniqueSubsttr(string S){\n //code\n int maxi=INT_MIN, i=0,j=0,n=S.size();\n int arr[26]={0};\n while(j<n){\n arr[S[j]-'a']++;\n while(i<n && arr[S[j]-'a']!=1){\n arr[S[i]-'a']--;\n i++;\n }\n maxi=max(maxi,j-i+1);\n j++;\n }\n return maxi;\n }" }, { "code": null, "e": 1640, "s": 1638, "text": "0" }, { "code": null, "e": 1660, "s": 1640, "text": "kake13372 weeks ago" }, { "code": null, "e": 2011, "s": 1660, "text": " int longestUniqueSubsttr(string S){\n vector<int>v(26,-1);\n int i=0,j=0,r=1;\n while(j<S.length())\n {\n if(v[S[j]-'a']!=-1)\n {\n if(v[S[j]-'a']>=i)\n i=v[S[j]-'a']+1;\n }\n v[S[j]-'a']=j;\n r=max(r,j-i+1);\n j++;\n }\n return r;\n }" }, { "code": null, "e": 2013, "s": 2011, "text": "0" }, { "code": null, "e": 2039, "s": 2013, "text": "koresachin19993 weeks ago" }, { "code": null, "e": 2586, "s": 2039, "text": "class Solution{ int longestUniqueSubsttr(String s){ int n=s.length(); HashMap<Character, Integer> map=new HashMap<>(); int ans=0; int start=0, end=0; while(end<n) { map.put(s.charAt(end), map.getOrDefault(s.charAt(end),0)+1); while(start<=end&& map.get(s.charAt(end))>1) { map.put(s.charAt(start),map.get(s.charAt(start))-1); start++; } ans=Math.max(ans, end-start+1); end++; } return ans; }}" }, { "code": null, "e": 2588, "s": 2586, "text": "0" }, { "code": null, "e": 2616, "s": 2588, "text": "kumaraditya338713 weeks ago" }, { "code": null, "e": 2648, "s": 2616, "text": "// please up vote this code ☺️" }, { "code": null, "e": 2702, "s": 2652, "text": " int longestUniqueSubsttr(string S){ //code" }, { "code": null, "e": 3232, "s": 2702, "text": " int i=0; int j=0; int mx=INT_MIN; map<char,int>mp; while(j<S.length()) { mp[S[j]]++; if(mp.size()>j-i+1) j++; else if(mp.size()==j-i+1) { mx=max(mx , j-i+1); j++; } else if(mp.size()<j-i+1) { while(mp.size()<j-i+1) { mp[S[i]]-- ; if(mp[S[i]]==0) mp.erase(S[i]); i++; } j++; } " }, { "code": null, "e": 3274, "s": 3232, "text": "}//while loop end return mx; }" }, { "code": null, "e": 3278, "s": 3276, "text": "0" }, { "code": null, "e": 3303, "s": 3278, "text": "ujjwalraj57983 weeks ago" }, { "code": null, "e": 3336, "s": 3303, "text": "O(N) solution using two pointers" }, { "code": null, "e": 4003, "s": 3336, "text": "int longestUniqueSubsttr(string S){\n //code\n int n=S.length();\n vector<int>freq;\n freq.resize(26,0);\n int ans=0;\n int head=-1;int tail=0;\n while(tail<n){\n //head move\n while(head+1<n&&freq[S[head+1]-'a']==0){\n head++;\n freq[S[head]-'a']++;\n }\n //process\n ans=max(ans,head-tail+1);\n //tail updation\n if(head>=tail){\n freq[S[tail]-'a']--;\n tail++;\n }else{\n tail++;\n head=tail-1;\n }\n \n }\n return ans;\n }" }, { "code": null, "e": 4005, "s": 4003, "text": "0" }, { "code": null, "e": 4030, "s": 4005, "text": "iamkhijiralam1 month ago" }, { "code": null, "e": 4067, "s": 4030, "text": "Simple C++ | O(N) solution |Accepted" }, { "code": null, "e": 4797, "s": 4069, "text": "int longestUniqueSubsttr(string S){ //code int start=0,next=0; vector<int> lastIndex(256,-1); int longestSoFar=0; while(S[next]!='\\0'){ char nextChar=S[next]; if(lastIndex[nextChar]<start){ next++; } else{ int currentOP=next-start; if(currentOP > longestSoFar){ longestSoFar= currentOP; } start=lastIndex[nextChar] +1; next++; } lastIndex[nextChar]=next-1; } int currentOP=next-start; if(currentOP > longestSoFar){ longestSoFar= currentOP; } return longestSoFar; }" }, { "code": null, "e": 4800, "s": 4797, "text": "+1" }, { "code": null, "e": 4821, "s": 4800, "text": "namantam11 month ago" }, { "code": null, "e": 4873, "s": 4821, "text": "Simple C++ | O(N) solution | Without set or hashmap" }, { "code": null, "e": 5450, "s": 4875, "text": "class Solution{\n int arr[26] = {0};\n \n bool contains(char c) {\n return arr[c - 'a'];\n }\n \n void erase(char c) {\n arr[c - 'a'] = 0;\n }\n \n void insert(char c) {\n arr[c - 'a'] = 1;\n }\n \n public:\n int longestUniqueSubsttr(string s){\n int i=0, j=0, ans=0, n=s.size();\n \n while (j < n) {\n while (i<n and contains(s[j])) {\n erase(s[i++]);\n }\n insert(s[j++]);\n \n ans = max(ans, j-i);\n }\n \n return ans;\n }\n};" }, { "code": null, "e": 5453, "s": 5450, "text": "+1" }, { "code": null, "e": 5480, "s": 5453, "text": "abhinavjain78981 month ago" }, { "code": null, "e": 5513, "s": 5480, "text": "Java Easy Solution Using HashMap" }, { "code": null, "e": 6033, "s": 5513, "text": "class Solution{\n int longestUniqueSubsttr(String s){\n HashMap<Character,Integer> hm = new HashMap<>();\n int max = 0;\n int n = s.length();\n for(int i=0;i<n;i++){\n char temp = s.charAt(i);\n if(!hm.containsKey(temp)){\n hm.put(temp,i);\n }\n else{\n i = hm.get(temp);\n hm.clear();\n }\n if(hm.size()>max){\n max = hm.size();\n }\n }\n return max;\n }\n}" }, { "code": null, "e": 6035, "s": 6033, "text": "0" }, { "code": null, "e": 6059, "s": 6035, "text": "mebhowmik3211 month ago" }, { "code": null, "e": 6084, "s": 6059, "text": "Successful C++ solution:" }, { "code": null, "e": 6446, "s": 6084, "text": "int longestUniqueSubsttr(string S){\n //code\n vector<int> vec(26,0);\n int res=0;\n int l=0,r=0,n=S.length();\n while(r<n)\n {\n int c=S[r]-'a';\n vec[c]++;\n while(vec[c]>1)\n vec[S[l++]-'a']--;\n res=max(r-l+1,res);\n r++;\n }\n return res;\n }" }, { "code": null, "e": 6592, "s": 6446, "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": 6628, "s": 6592, "text": " Login to access your submissions. " }, { "code": null, "e": 6638, "s": 6628, "text": "\nProblem\n" }, { "code": null, "e": 6648, "s": 6638, "text": "\nContest\n" }, { "code": null, "e": 6711, "s": 6648, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6896, "s": 6711, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 7180, "s": 6896, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 7326, "s": 7180, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 7403, "s": 7326, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 7444, "s": 7403, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 7472, "s": 7444, "text": "Disable browser extensions." }, { "code": null, "e": 7543, "s": 7472, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 7730, "s": 7543, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
How to add Music Playlist in Pygame?
18 Jul, 2021 In this article, we are going to see how to add a music playlist in Pygame. Pygame has a method, pygame.mixer() which has all the functionalities regarding audio operations like playing a song, queuing a song, setting the volume, rewind, stop, pause, resume, and many more. Functions provided by this class are – pygame.mixer.music.load(): This will load the music file/filename object. pygame.mixer.music.play(loops, start, fade_ms ): Starts the playback of the music which has been loaded. This takes 3 argumentsloops: It is an optional integer argument that states how many times the song should repeat. If set to -1, then it will loop indefinitely.start: It is an optional float argument, which denotes the position in time and from where the music should start playing.fade_ms: It is an optional integer argument. It makes the music start from 0 volume and fades up to full volume at the given time. loops: It is an optional integer argument that states how many times the song should repeat. If set to -1, then it will loop indefinitely. start: It is an optional float argument, which denotes the position in time and from where the music should start playing. fade_ms: It is an optional integer argument. It makes the music start from 0 volume and fades up to full volume at the given time. pygame.mixer.music.queue(): This will queue a song at the end of the current music file. As soon as the current file ends, the next queued music file gets played. You can also queue multiple songs and this will be our main logic for building a playlist. pygame.mixer.music.rewind(): This rewinds the playback of the current music file to the beginning. pygame.mixer.music.pause(): This pauses the playback of the current music file. pygame.mixer.music.set_endevent(): This sends a signal i.e, an event. If the music file has finished playing, an event will be queued. pygame.mixer.music.get_busy(): This returns a boolean value, indicating if a music file has currently been played or not. Inorder to create a playlist in Pygame we’ll be using all the above-mentioned methods to form a flow in which all our chosen music files will be pushed to list and each one of those files will be queued and played one after the other in sequential order. This logic can be implemented as follows: Load the first entry of the list containing music files into pygame by using pygame.mixer.music.load() and simultaneously deleting the first entry from the list. On loading the first song, we’ll play it using pygame.mixer.music.play(). Subsequently, we will also queue the second entry by using pygame.mixer.music.queue() and delete the same from our list. Whenever music ends, we’ll be hosting an event pygame.MUSIC_END by using pygame.mixer.music.set_endevent() to notify the player to queue the next song from the list. Once all the music files from our playList has been played/queued then pygame.mixer.music.get_busy() returns false and we break the for-loop and while-loop bringing our program to the end. Below is the implementation: Python import pygame # setting up pygamepygame.init() def insert_into_playlist(playlist, music_file): # Adding songs file in our playlist playlist.append(music_file) def start_playlist(playList): # Loading first audio file into our player pygame.mixer.music.load(playList[0]) # Removing the loaded song from our playlist list playList.pop(0) # Playing our music pygame.mixer.music.play() # Queueing next song into our player pygame.mixer.music.queue(playList[0]) playList.pop(0) # setting up an end event which host an event # after the end of every song pygame.mixer.music.set_endevent(pygame.MUSIC_END) # Playing the songs in the background running = True while running: # checking if any event has been # hosted at time of playing for event in pygame.event.get(): # A event will be hosted # after the end of every song if event.type == pygame.MUSIC_END: print('Song Finished') # Checking our playList # that if any song exist or # it is empty if len(playList) > 0: # if song available then load it in player # and remove from the player pygame.mixer.music.queue(playList[0]) playList.pop(0) # Checking whether the # player is still playing any song # if yes it will return true and false otherwise if not pygame.mixer.music.get_busy(): print("Playlist completed") # When the playlist has # completed playing successfully # we'll go out of the # while-loop by using break running = False break if __name__ == '__main__': # This list is going to be # our playlist as we can # only queue one song at a # time by using `.queue()` method # therefore we are using list # and will queue song one by one. playList = [] insert_into_playlist(playList, 'eg1.wav') insert_into_playlist(playList, 'eg2.wav') insert_into_playlist(playList, 'eg3.wav') start_playlist(playList) Output: Picked Python-PyGame Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jul, 2021" }, { "code": null, "e": 104, "s": 28, "text": "In this article, we are going to see how to add a music playlist in Pygame." }, { "code": null, "e": 342, "s": 104, "text": "Pygame has a method, pygame.mixer() which has all the functionalities regarding audio operations like playing a song, queuing a song, setting the volume, rewind, stop, pause, resume, and many more. Functions provided by this class are – " }, { "code": null, "e": 416, "s": 342, "text": "pygame.mixer.music.load(): This will load the music file/filename object." }, { "code": null, "e": 934, "s": 416, "text": "pygame.mixer.music.play(loops, start, fade_ms ): Starts the playback of the music which has been loaded. This takes 3 argumentsloops: It is an optional integer argument that states how many times the song should repeat. If set to -1, then it will loop indefinitely.start: It is an optional float argument, which denotes the position in time and from where the music should start playing.fade_ms: It is an optional integer argument. It makes the music start from 0 volume and fades up to full volume at the given time." }, { "code": null, "e": 1073, "s": 934, "text": "loops: It is an optional integer argument that states how many times the song should repeat. If set to -1, then it will loop indefinitely." }, { "code": null, "e": 1196, "s": 1073, "text": "start: It is an optional float argument, which denotes the position in time and from where the music should start playing." }, { "code": null, "e": 1327, "s": 1196, "text": "fade_ms: It is an optional integer argument. It makes the music start from 0 volume and fades up to full volume at the given time." }, { "code": null, "e": 1581, "s": 1327, "text": "pygame.mixer.music.queue(): This will queue a song at the end of the current music file. As soon as the current file ends, the next queued music file gets played. You can also queue multiple songs and this will be our main logic for building a playlist." }, { "code": null, "e": 1680, "s": 1581, "text": "pygame.mixer.music.rewind(): This rewinds the playback of the current music file to the beginning." }, { "code": null, "e": 1760, "s": 1680, "text": "pygame.mixer.music.pause(): This pauses the playback of the current music file." }, { "code": null, "e": 1896, "s": 1760, "text": "pygame.mixer.music.set_endevent(): This sends a signal i.e, an event. If the music file has finished playing, an event will be queued. " }, { "code": null, "e": 2019, "s": 1896, "text": "pygame.mixer.music.get_busy(): This returns a boolean value, indicating if a music file has currently been played or not. " }, { "code": null, "e": 2316, "s": 2019, "text": "Inorder to create a playlist in Pygame we’ll be using all the above-mentioned methods to form a flow in which all our chosen music files will be pushed to list and each one of those files will be queued and played one after the other in sequential order. This logic can be implemented as follows:" }, { "code": null, "e": 2478, "s": 2316, "text": "Load the first entry of the list containing music files into pygame by using pygame.mixer.music.load() and simultaneously deleting the first entry from the list." }, { "code": null, "e": 2552, "s": 2478, "text": "On loading the first song, we’ll play it using pygame.mixer.music.play()." }, { "code": null, "e": 2673, "s": 2552, "text": "Subsequently, we will also queue the second entry by using pygame.mixer.music.queue() and delete the same from our list." }, { "code": null, "e": 2840, "s": 2673, "text": "Whenever music ends, we’ll be hosting an event pygame.MUSIC_END by using pygame.mixer.music.set_endevent() to notify the player to queue the next song from the list." }, { "code": null, "e": 3029, "s": 2840, "text": "Once all the music files from our playList has been played/queued then pygame.mixer.music.get_busy() returns false and we break the for-loop and while-loop bringing our program to the end." }, { "code": null, "e": 3058, "s": 3029, "text": "Below is the implementation:" }, { "code": null, "e": 3065, "s": 3058, "text": "Python" }, { "code": "import pygame # setting up pygamepygame.init() def insert_into_playlist(playlist, music_file): # Adding songs file in our playlist playlist.append(music_file) def start_playlist(playList): # Loading first audio file into our player pygame.mixer.music.load(playList[0]) # Removing the loaded song from our playlist list playList.pop(0) # Playing our music pygame.mixer.music.play() # Queueing next song into our player pygame.mixer.music.queue(playList[0]) playList.pop(0) # setting up an end event which host an event # after the end of every song pygame.mixer.music.set_endevent(pygame.MUSIC_END) # Playing the songs in the background running = True while running: # checking if any event has been # hosted at time of playing for event in pygame.event.get(): # A event will be hosted # after the end of every song if event.type == pygame.MUSIC_END: print('Song Finished') # Checking our playList # that if any song exist or # it is empty if len(playList) > 0: # if song available then load it in player # and remove from the player pygame.mixer.music.queue(playList[0]) playList.pop(0) # Checking whether the # player is still playing any song # if yes it will return true and false otherwise if not pygame.mixer.music.get_busy(): print(\"Playlist completed\") # When the playlist has # completed playing successfully # we'll go out of the # while-loop by using break running = False break if __name__ == '__main__': # This list is going to be # our playlist as we can # only queue one song at a # time by using `.queue()` method # therefore we are using list # and will queue song one by one. playList = [] insert_into_playlist(playList, 'eg1.wav') insert_into_playlist(playList, 'eg2.wav') insert_into_playlist(playList, 'eg3.wav') start_playlist(playList)", "e": 5380, "s": 3065, "text": null }, { "code": null, "e": 5388, "s": 5380, "text": "Output:" }, { "code": null, "e": 5395, "s": 5388, "text": "Picked" }, { "code": null, "e": 5409, "s": 5395, "text": "Python-PyGame" }, { "code": null, "e": 5416, "s": 5409, "text": "Python" } ]
Python - API.show_friendship() in Tweepy - GeeksforGeeks
07 Oct, 2021 Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key, and access secret from the Twitter developer available easily for each user. These keys will help the API for authentication. The show_friendship() method of the API class in Tweepy module is used to get the detailed relationship between two users. Syntax : API.show_friendship(source_id / source_screen_name, target_id / target_screen_name)Parameters : source_id : specifies the ID of the user 1. source_screen_name : specifies the screen name of the user 1. target_id : specifies the ID of the user 2. target_screen_name : specifies the screen name of the user 2. Returns : an object of the class Friendship Example 1 : Analyzing friendships by using the screen names. Python3 # import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secretauth.set_access_token(access_token, access_token_secret) # calling the apiapi = tweepy.API(auth) # screen name of the account 1source_screen_name = "Twitter" # screen name of the account 2target_screen_name = "TwitterIndia" # getting the friendship detailsfriendship = api.show_friendship(source_screen_name = source_screen_name, target_screen_name = target_screen_name) print("Is " + friendship[0].screen_name + " followed by " + friendship[1].screen_name, end = "? : ")if friendship[0].followed_by == False: print("No")else: print("Yes") print("Is " + friendship[0].screen_name + " following " + friendship[1].screen_name, end = "? : ")if friendship[0].following == False: print("No")else: print("Yes") Output : Is Twitter followed by TwitterIndia? : Yes Is Twitter following TwitterIndia? : No Example 2 : Analyzing friendships by using the user IDs. Python3 # user ID of the account 1source_id = 14230524 # user ID of the account 2target_id = 34507480 # getting the friendship detailsfriendship = api.show_friendship(source_id = source_id, target_id = target_id) print("The screen name of user 1 is : " + friendship[0].screen_name)print("The screen name of user 2 is : " + friendship[1].screen_name) print("Is " + friendship[0].screen_name + " followed by " + friendship[1].screen_name, end = "? : ")if friendship[0].followed_by == False: print("No")else: print("Yes") print("Is " + friendship[0].screen_name + " following " + friendship[1].screen_name, end = "? : ")if friendship[0].following == False: print("No")else: print("Yes") Output : The screen name of user 1 is : ladygaga The screen name of user 2 is : ArianaGrande Is ladygaga followed by ArianaGrande? : Yes Is ladygaga following ArianaGrande? : No varshagumber28 saurabh1990aror Python-Tweepy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 24454, "s": 24426, "text": "\n07 Oct, 2021" }, { "code": null, "e": 24859, "s": 24454, "text": "Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key, and access secret from the Twitter developer available easily for each user. These keys will help the API for authentication." }, { "code": null, "e": 24982, "s": 24859, "text": "The show_friendship() method of the API class in Tweepy module is used to get the detailed relationship between two users." }, { "code": null, "e": 25088, "s": 24982, "text": "Syntax : API.show_friendship(source_id / source_screen_name, target_id / target_screen_name)Parameters : " }, { "code": null, "e": 25132, "s": 25088, "text": "source_id : specifies the ID of the user 1." }, { "code": null, "e": 25194, "s": 25132, "text": "source_screen_name : specifies the screen name of the user 1." }, { "code": null, "e": 25238, "s": 25194, "text": "target_id : specifies the ID of the user 2." }, { "code": null, "e": 25300, "s": 25238, "text": "target_screen_name : specifies the screen name of the user 2." }, { "code": null, "e": 25346, "s": 25300, "text": "Returns : an object of the class Friendship " }, { "code": null, "e": 25408, "s": 25346, "text": "Example 1 : Analyzing friendships by using the screen names. " }, { "code": null, "e": 25416, "s": 25408, "text": "Python3" }, { "code": "# import the moduleimport tweepy # assign the values accordinglyconsumer_key = \"\"consumer_secret = \"\"access_token = \"\"access_token_secret = \"\" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secretauth.set_access_token(access_token, access_token_secret) # calling the apiapi = tweepy.API(auth) # screen name of the account 1source_screen_name = \"Twitter\" # screen name of the account 2target_screen_name = \"TwitterIndia\" # getting the friendship detailsfriendship = api.show_friendship(source_screen_name = source_screen_name, target_screen_name = target_screen_name) print(\"Is \" + friendship[0].screen_name + \" followed by \" + friendship[1].screen_name, end = \"? : \")if friendship[0].followed_by == False: print(\"No\")else: print(\"Yes\") print(\"Is \" + friendship[0].screen_name + \" following \" + friendship[1].screen_name, end = \"? : \")if friendship[0].following == False: print(\"No\")else: print(\"Yes\")", "e": 26436, "s": 25416, "text": null }, { "code": null, "e": 26447, "s": 26436, "text": "Output : " }, { "code": null, "e": 26530, "s": 26447, "text": "Is Twitter followed by TwitterIndia? : Yes\nIs Twitter following TwitterIndia? : No" }, { "code": null, "e": 26587, "s": 26530, "text": "Example 2 : Analyzing friendships by using the user IDs." }, { "code": null, "e": 26595, "s": 26587, "text": "Python3" }, { "code": "# user ID of the account 1source_id = 14230524 # user ID of the account 2target_id = 34507480 # getting the friendship detailsfriendship = api.show_friendship(source_id = source_id, target_id = target_id) print(\"The screen name of user 1 is : \" + friendship[0].screen_name)print(\"The screen name of user 2 is : \" + friendship[1].screen_name) print(\"Is \" + friendship[0].screen_name + \" followed by \" + friendship[1].screen_name, end = \"? : \")if friendship[0].followed_by == False: print(\"No\")else: print(\"Yes\") print(\"Is \" + friendship[0].screen_name + \" following \" + friendship[1].screen_name, end = \"? : \")if friendship[0].following == False: print(\"No\")else: print(\"Yes\")", "e": 27283, "s": 26595, "text": null }, { "code": null, "e": 27293, "s": 27283, "text": "Output : " }, { "code": null, "e": 27462, "s": 27293, "text": "The screen name of user 1 is : ladygaga\nThe screen name of user 2 is : ArianaGrande\nIs ladygaga followed by ArianaGrande? : Yes\nIs ladygaga following ArianaGrande? : No" }, { "code": null, "e": 27477, "s": 27462, "text": "varshagumber28" }, { "code": null, "e": 27493, "s": 27477, "text": "saurabh1990aror" }, { "code": null, "e": 27507, "s": 27493, "text": "Python-Tweepy" }, { "code": null, "e": 27514, "s": 27507, "text": "Python" }, { "code": null, "e": 27612, "s": 27514, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27621, "s": 27612, "text": "Comments" }, { "code": null, "e": 27634, "s": 27621, "text": "Old Comments" }, { "code": null, "e": 27652, "s": 27634, "text": "Python Dictionary" }, { "code": null, "e": 27687, "s": 27652, "text": "Read a file line by line in Python" }, { "code": null, "e": 27709, "s": 27687, "text": "Enumerate() in Python" }, { "code": null, "e": 27741, "s": 27709, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27771, "s": 27741, "text": "Iterate over a list in Python" }, { "code": null, "e": 27813, "s": 27771, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27839, "s": 27813, "text": "Python String | replace()" }, { "code": null, "e": 27882, "s": 27839, "text": "Python program to convert a list to string" }, { "code": null, "e": 27926, "s": 27882, "text": "Reading and Writing to text files in Python" } ]
Reverse a String | Shell Programming - GeeksforGeeks
04 May, 2022 We are given a string and we have to use shell script print it in the reverse order. Asked in FICO Examples: Input : geeksforgeeks Output :skeegrofskeeg Algorithm step 1:- Take user input in a string step 2:- Findthe length of given string using length function step 3:- Set i = length-1 and run loop till i <= 0 step 4:- echo the $i step 5:- repeat step 3 and 4 till i==0 step 6:- end CPP // reverse a string using shell script// reverse a string is in linux and unix #!/ bin / bash// reading a string// using via user inputread - p "Enter string:" string // getting the length of given string len = ${ #string}// looping for reversing a string// initialize i=len-1 for reversing a string and run till i=0// printing in the reverse order of the given stringfor ((i = $len - 1; i >= 0; i--)) do // "${string:$i:1}"extract single character from string. reverse = "$reverse${string:$i:1}" done echo "$reverse" Output: skeegrofskeeg Reverse a string in shell scripting using Commands rev command : It is used to reverse the lines in a file. This command can take standard input as well as shown below. rev command : It is used to reverse the lines in a file. This command can take standard input as well as shown below. $ echo welcome | rev emoclew Note: The rev command is not present in all flavors of Unix.awk command : Using the substring function, can reverse a string: Note: The rev command is not present in all flavors of Unix. awk command : Using the substring function, can reverse a string: $ echo welcome | awk '{ for(i = length; i!=0; i--) x = x substr($0, i, 1); }END {print x}' emoclew This logic is the common logic used in any programming language to reverse a string: Start from the last position of the string and keep printing a character till the first position is reached. We loop on the string starting from the last position and moving towards the beginning. The length command gives the length of the argument passed to it. With no argument, length gives the length of the current line which is $0. The substr command in awk extracts one character at a time and is appended to the resultant variable x which is printed at the end using the END label.sed command : Total 2 sed commands are used here. This logic is the common logic used in any programming language to reverse a string: Start from the last position of the string and keep printing a character till the first position is reached. We loop on the string starting from the last position and moving towards the beginning. The length command gives the length of the argument passed to it. With no argument, length gives the length of the current line which is $0. The substr command in awk extracts one character at a time and is appended to the resultant variable x which is printed at the end using the END label. sed command : Total 2 sed commands are used here. $ echo welcome | sed 's/./&\n/g' | tac | sed -e :a -e 'N;s/\n//g;ta' emoclew To understand this command properly, break it up at every pipe and observe the output. The first sed reads a character(.) and appends a newline(\n) character behind every matched character(&). tac command reverses the contents of a file or the standard input. The second sed command now joins all the lines together. Note: The tac command is not present in all the Unix flavors.Perl solution : Using the inbuilt perl function reverse. To understand this command properly, break it up at every pipe and observe the output. The first sed reads a character(.) and appends a newline(\n) character behind every matched character(&). tac command reverses the contents of a file or the standard input. The second sed command now joins all the lines together. Note: The tac command is not present in all the Unix flavors. Perl solution : Using the inbuilt perl function reverse. $ echo welcome | perl -ne 'chomp; print scalar reverse;' emoclew reverse function reverses all the elements present in a list. In scalar context as used here, it reverses a string as well. The chomp command is used to remove the newline character in the string. reverse function reverses all the elements present in a list. In scalar context as used here, it reverses a string as well. The chomp command is used to remove the newline character in the string. This article is contributed by Ajay Puri(ajay0007). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.. surinderdawra388 FICO linux-command Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C SORT command in Linux/Unix with examples tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script 'crontab' in Linux with Examples diff command in Linux with examples Tail command in Linux with examples UDP Server-Client implementation in C Cat command in Linux with examples
[ { "code": null, "e": 25853, "s": 25825, "text": "\n04 May, 2022" }, { "code": null, "e": 25962, "s": 25853, "text": "We are given a string and we have to use shell script print it in the reverse order. Asked in FICO Examples:" }, { "code": null, "e": 26007, "s": 25962, "text": "Input : geeksforgeeks \nOutput :skeegrofskeeg" }, { "code": null, "e": 26017, "s": 26007, "text": "Algorithm" }, { "code": null, "e": 26240, "s": 26017, "text": "step 1:- Take user input in a string\nstep 2:- Findthe length of given string using length function\nstep 3:- Set i = length-1 and run loop till i <= 0\nstep 4:- echo the $i\nstep 5:- repeat step 3 and 4 till i==0\nstep 6:- end" }, { "code": null, "e": 26244, "s": 26240, "text": "CPP" }, { "code": "// reverse a string using shell script// reverse a string is in linux and unix #!/ bin / bash// reading a string// using via user inputread - p \"Enter string:\" string // getting the length of given string len = ${ #string}// looping for reversing a string// initialize i=len-1 for reversing a string and run till i=0// printing in the reverse order of the given stringfor ((i = $len - 1; i >= 0; i--)) do // \"${string:$i:1}\"extract single character from string. reverse = \"$reverse${string:$i:1}\" done echo \"$reverse\"", "e": 26790, "s": 26244, "text": null }, { "code": null, "e": 26798, "s": 26790, "text": "Output:" }, { "code": null, "e": 26812, "s": 26798, "text": "skeegrofskeeg" }, { "code": null, "e": 26863, "s": 26812, "text": "Reverse a string in shell scripting using Commands" }, { "code": null, "e": 26981, "s": 26863, "text": "rev command : It is used to reverse the lines in a file. This command can take standard input as well as shown below." }, { "code": null, "e": 27099, "s": 26981, "text": "rev command : It is used to reverse the lines in a file. This command can take standard input as well as shown below." }, { "code": null, "e": 27129, "s": 27099, "text": "$ echo welcome | rev\n\nemoclew" }, { "code": null, "e": 27255, "s": 27129, "text": "Note: The rev command is not present in all flavors of Unix.awk command : Using the substring function, can reverse a string:" }, { "code": null, "e": 27316, "s": 27255, "text": "Note: The rev command is not present in all flavors of Unix." }, { "code": null, "e": 27382, "s": 27316, "text": "awk command : Using the substring function, can reverse a string:" }, { "code": null, "e": 27483, "s": 27382, "text": "$ echo welcome | awk \n'{ for(i = length; i!=0; i--)\nx = x substr($0, i, 1);\n}END\n{print x}'\n\nemoclew" }, { "code": null, "e": 28107, "s": 27483, "text": "This logic is the common logic used in any programming language to reverse a string: Start from the last position of the string and keep printing a character till the first position is reached. We loop on the string starting from the last position and moving towards the beginning. The length command gives the length of the argument passed to it. With no argument, length gives the length of the current line which is $0. The substr command in awk extracts one character at a time and is appended to the resultant variable x which is printed at the end using the END label.sed command : Total 2 sed commands are used here." }, { "code": null, "e": 28682, "s": 28107, "text": "This logic is the common logic used in any programming language to reverse a string: Start from the last position of the string and keep printing a character till the first position is reached. We loop on the string starting from the last position and moving towards the beginning. The length command gives the length of the argument passed to it. With no argument, length gives the length of the current line which is $0. The substr command in awk extracts one character at a time and is appended to the resultant variable x which is printed at the end using the END label." }, { "code": null, "e": 28732, "s": 28682, "text": "sed command : Total 2 sed commands are used here." }, { "code": null, "e": 28810, "s": 28732, "text": "$ echo welcome | sed 's/./&\\n/g' | tac | sed -e :a -e 'N;s/\\n//g;ta'\n\nemoclew" }, { "code": null, "e": 29245, "s": 28810, "text": "To understand this command properly, break it up at every pipe and observe the output. The first sed reads a character(.) and appends a newline(\\n) character behind every matched character(&). tac command reverses the contents of a file or the standard input. The second sed command now joins all the lines together. Note: The tac command is not present in all the Unix flavors.Perl solution : Using the inbuilt perl function reverse." }, { "code": null, "e": 29624, "s": 29245, "text": "To understand this command properly, break it up at every pipe and observe the output. The first sed reads a character(.) and appends a newline(\\n) character behind every matched character(&). tac command reverses the contents of a file or the standard input. The second sed command now joins all the lines together. Note: The tac command is not present in all the Unix flavors." }, { "code": null, "e": 29681, "s": 29624, "text": "Perl solution : Using the inbuilt perl function reverse." }, { "code": null, "e": 29747, "s": 29681, "text": "$ echo welcome | perl -ne 'chomp;\nprint scalar reverse;'\n\nemoclew" }, { "code": null, "e": 29944, "s": 29747, "text": "reverse function reverses all the elements present in a list. In scalar context as used here, it reverses a string as well. The chomp command is used to remove the newline character in the string." }, { "code": null, "e": 30141, "s": 29944, "text": "reverse function reverses all the elements present in a list. In scalar context as used here, it reverses a string as well. The chomp command is used to remove the newline character in the string." }, { "code": null, "e": 30570, "s": 30141, "text": "This article is contributed by Ajay Puri(ajay0007). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.." }, { "code": null, "e": 30587, "s": 30570, "text": "surinderdawra388" }, { "code": null, "e": 30592, "s": 30587, "text": "FICO" }, { "code": null, "e": 30606, "s": 30592, "text": "linux-command" }, { "code": null, "e": 30617, "s": 30606, "text": "Linux-Unix" }, { "code": null, "e": 30715, "s": 30617, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30753, "s": 30715, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 30794, "s": 30753, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 30829, "s": 30794, "text": "tar command in Linux with examples" }, { "code": null, "e": 30865, "s": 30829, "text": "curl command in Linux with Examples" }, { "code": null, "e": 30903, "s": 30865, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 30936, "s": 30903, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 30972, "s": 30936, "text": "diff command in Linux with examples" }, { "code": null, "e": 31008, "s": 30972, "text": "Tail command in Linux with examples" }, { "code": null, "e": 31046, "s": 31008, "text": "UDP Server-Client implementation in C" } ]
Angular ngx Bootstrap Tooltip Component - GeeksforGeeks
02 Sep, 2021 Angular ngx bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites.In this article, we will see how to use Tooltip in angular ngx bootstrap. Installation syntax: npm install ngx-bootstrap --save Approach: First, install the angular ngx bootstrap using the above-mentioned command. Add the following script in index.html<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”> <link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”> Import tooltip component in module.ts In app.component.html make a tooltip component. Serve the app using ng serve. Example: index.html <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <title>Demo</title> <base href="/" /> <meta name="viewport" content= "width=device-width, initial-scale=1" /> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" /> <link rel="icon" type="image/x-icon" href="favicon.ico" /> <link rel="preconnect" href="https://fonts.gstatic.com" /> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet" /> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" /></head> <body class="mat-typography"> <app-root></app-root></body> </html> app.component.html <button id='gfg' type="button" class="btn btn-success" tooltip="Tooltip component in Angular ngx bootstrap."> GeeksforGeeks</button> app.module.ts import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule }from '@angular/forms';import { BrowserModule }from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { TooltipModule} from 'ngx-bootstrap/tooltip'; import { AppComponent } from './app.component'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, TooltipModule.forRoot() ]})export class AppModule { } app.component.css #gfg { margin: 10px;} app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent {} Output: ysachin2314 Angular-ngx-bootstrap AngularJS Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular PrimeNG Messages Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? How to change navigation bar color in Bootstrap ? Form validation using jQuery How to pass data into a bootstrap modal? How to align navbar items to the right in Bootstrap 4 ? How to Show Images on Click using HTML ?
[ { "code": null, "e": 26464, "s": 26436, "text": "\n02 Sep, 2021" }, { "code": null, "e": 26722, "s": 26464, "text": "Angular ngx bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites.In this article, we will see how to use Tooltip in angular ngx bootstrap." }, { "code": null, "e": 26743, "s": 26722, "text": "Installation syntax:" }, { "code": null, "e": 26776, "s": 26743, "text": "npm install ngx-bootstrap --save" }, { "code": null, "e": 26786, "s": 26776, "text": "Approach:" }, { "code": null, "e": 26862, "s": 26786, "text": "First, install the angular ngx bootstrap using the above-mentioned command." }, { "code": null, "e": 27001, "s": 26862, "text": "Add the following script in index.html<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”>" }, { "code": null, "e": 27102, "s": 27001, "text": "<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”>" }, { "code": null, "e": 27140, "s": 27102, "text": "Import tooltip component in module.ts" }, { "code": null, "e": 27188, "s": 27140, "text": "In app.component.html make a tooltip component." }, { "code": null, "e": 27218, "s": 27188, "text": "Serve the app using ng serve." }, { "code": null, "e": 27229, "s": 27220, "text": "Example:" }, { "code": null, "e": 27240, "s": 27229, "text": "index.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <title>Demo</title> <base href=\"/\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\" /> <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" rel=\"stylesheet\" /> <link rel=\"icon\" type=\"image/x-icon\" href=\"favicon.ico\" /> <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" /> <link href=\"https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap\" rel=\"stylesheet\" /> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\" /></head> <body class=\"mat-typography\"> <app-root></app-root></body> </html>", "e": 27968, "s": 27240, "text": null }, { "code": null, "e": 27987, "s": 27968, "text": "app.component.html" }, { "code": "<button id='gfg' type=\"button\" class=\"btn btn-success\" tooltip=\"Tooltip component in Angular ngx bootstrap.\"> GeeksforGeeks</button>", "e": 28130, "s": 27987, "text": null }, { "code": null, "e": 28144, "s": 28130, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule }from '@angular/forms';import { BrowserModule }from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { TooltipModule} from 'ngx-bootstrap/tooltip'; import { AppComponent } from './app.component'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, TooltipModule.forRoot() ]})export class AppModule { }", "e": 28759, "s": 28144, "text": null }, { "code": null, "e": 28777, "s": 28759, "text": "app.component.css" }, { "code": "#gfg { margin: 10px;}", "e": 28802, "s": 28777, "text": null }, { "code": null, "e": 28819, "s": 28802, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent {}", "e": 29009, "s": 28819, "text": null }, { "code": null, "e": 29017, "s": 29009, "text": "Output:" }, { "code": null, "e": 29029, "s": 29017, "text": "ysachin2314" }, { "code": null, "e": 29051, "s": 29029, "text": "Angular-ngx-bootstrap" }, { "code": null, "e": 29061, "s": 29051, "text": "AngularJS" }, { "code": null, "e": 29071, "s": 29061, "text": "Bootstrap" }, { "code": null, "e": 29088, "s": 29071, "text": "Web Technologies" }, { "code": null, "e": 29186, "s": 29088, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29221, "s": 29186, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 29256, "s": 29221, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 29291, "s": 29256, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 29315, "s": 29291, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 29368, "s": 29315, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 29418, "s": 29368, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 29447, "s": 29418, "text": "Form validation using jQuery" }, { "code": null, "e": 29488, "s": 29447, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 29544, "s": 29488, "text": "How to align navbar items to the right in Bootstrap 4 ?" } ]
How to find Min/Max numbers in a java array?
You can find the minimum and maximum values of an array using for loops − Live Demo public class MinAndMax { public int max(int [] array) { int max = 0; for(int i=0; i<array.length; i++ ) { if(array[i]>max) { max = array[i]; } } return max; } public int min(int [] array) { int min = array[0]; for(int i=0; i<array.length; i++ ) { if(array[i]<min) { min = array[i]; } } return min; } public static void main(String args[]) { int[] myArray = {23, 92, 56, 39, 93}; MinAndMax m = new MinAndMax(); System.out.println("Maximum value in the array is::"+m.max(myArray)); System.out.println("Minimum value in the array is::"+m.min(myArray)); } } Maximum value in the array is ::93 Minimum value in the array is ::23
[ { "code": null, "e": 1136, "s": 1062, "text": "You can find the minimum and maximum values of an array using for loops −" }, { "code": null, "e": 1146, "s": 1136, "text": "Live Demo" }, { "code": null, "e": 1862, "s": 1146, "text": "public class MinAndMax {\n public int max(int [] array) {\n int max = 0;\n \n for(int i=0; i<array.length; i++ ) {\n if(array[i]>max) {\n max = array[i];\n }\n }\n return max;\n }\n public int min(int [] array) {\n int min = array[0];\n \n for(int i=0; i<array.length; i++ ) {\n if(array[i]<min) {\n min = array[i];\n }\n }\n return min;\n }\n public static void main(String args[]) {\n int[] myArray = {23, 92, 56, 39, 93};\n MinAndMax m = new MinAndMax();\n System.out.println(\"Maximum value in the array is::\"+m.max(myArray));\n System.out.println(\"Minimum value in the array is::\"+m.min(myArray));\n }\n}" }, { "code": null, "e": 1932, "s": 1862, "text": "Maximum value in the array is ::93\nMinimum value in the array is ::23" } ]
8085 program for hexadecimal counter - GeeksforGeeks
12 Dec, 2018 Write a program to count continuously in hexadecimal from FFH to 00H in a system with clock frequency 0.5 microseconds. Use register C to set up a delay of 1ms between each count and display output at one of the output ports. Problem Analysis: The hexadecimal counter is set by loading a register with starting number and decrementing it till zero is reached and then again decrementing it to will produce -1, which is two’s complement of FFH. Hence, the register again reaches FFH.The 1ms time delay is set up by the procedure shown in flowchart-The register is loaded with appropriate number such that the execution of above loop produces a time delay of 1ms. The hexadecimal counter is set by loading a register with starting number and decrementing it till zero is reached and then again decrementing it to will produce -1, which is two’s complement of FFH. Hence, the register again reaches FFH. The 1ms time delay is set up by the procedure shown in flowchart-The register is loaded with appropriate number such that the execution of above loop produces a time delay of 1ms. Program: The C register is the time delay register which is loaded by a value COUNT to produce a time delay of 1ms.To find the value of COUNT we do- TD = TL + TO where- TD = Time Delay TL = Time delay inside loop TO = Time delay outside loop The delay loop includes two instructions- DCR C (4 T-states) and JNZ (10 T-states)So TL = 14*Clock period*COUNT=> 14*(0.5*10-6)*COUNT=> (7*10-6)*COUNT Delay outside the loop includes-DCR B : 4TMVI C, COUNT : 7TMOV A, B : 4TOUTPORT : 10TJMP : 10TTotal : 35T TO= 35*Clock period => 17.5 microseconds So, 1ms= (17.5+ 7*COUNT)microsecond Therefore, COUNT=(140)10 Kartikaybhutani microprocessor system-programming Computer Organization & Architecture microprocessor Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Architecture of 8085 microprocessor Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard) Pin diagram of 8086 microprocessor Direct Access Media (DMA) Controller in Computer Architecture Memory mapped I/O and Isolated I/O General purpose registers in 8086 microprocessor Difference between SRAM and DRAM Registers of 8085 microprocessor 8085 program to multiply two 8 bit numbers 8085 program to add two 16 bit numbers
[ { "code": null, "e": 24700, "s": 24672, "text": "\n12 Dec, 2018" }, { "code": null, "e": 24926, "s": 24700, "text": "Write a program to count continuously in hexadecimal from FFH to 00H in a system with clock frequency 0.5 microseconds. Use register C to set up a delay of 1ms between each count and display output at one of the output ports." }, { "code": null, "e": 24944, "s": 24926, "text": "Problem Analysis:" }, { "code": null, "e": 25362, "s": 24944, "text": "The hexadecimal counter is set by loading a register with starting number and decrementing it till zero is reached and then again decrementing it to will produce -1, which is two’s complement of FFH. Hence, the register again reaches FFH.The 1ms time delay is set up by the procedure shown in flowchart-The register is loaded with appropriate number such that the execution of above loop produces a time delay of 1ms." }, { "code": null, "e": 25601, "s": 25362, "text": "The hexadecimal counter is set by loading a register with starting number and decrementing it till zero is reached and then again decrementing it to will produce -1, which is two’s complement of FFH. Hence, the register again reaches FFH." }, { "code": null, "e": 25781, "s": 25601, "text": "The 1ms time delay is set up by the procedure shown in flowchart-The register is loaded with appropriate number such that the execution of above loop produces a time delay of 1ms." }, { "code": null, "e": 25790, "s": 25781, "text": "Program:" }, { "code": null, "e": 25930, "s": 25790, "text": "The C register is the time delay register which is loaded by a value COUNT to produce a time delay of 1ms.To find the value of COUNT we do-" }, { "code": null, "e": 26024, "s": 25930, "text": "TD = TL + TO\nwhere- TD = Time Delay\nTL = Time delay inside loop\nTO = Time delay outside loop\n" }, { "code": null, "e": 26175, "s": 26024, "text": "The delay loop includes two instructions- DCR C (4 T-states) and JNZ (10 T-states)So TL = 14*Clock period*COUNT=> 14*(0.5*10-6)*COUNT=> (7*10-6)*COUNT" }, { "code": null, "e": 26281, "s": 26175, "text": "Delay outside the loop includes-DCR B : 4TMVI C, COUNT : 7TMOV A, B : 4TOUTPORT : 10TJMP : 10TTotal : 35T" }, { "code": null, "e": 26322, "s": 26281, "text": "TO= 35*Clock period => 17.5 microseconds" }, { "code": null, "e": 26358, "s": 26322, "text": "So, 1ms= (17.5+ 7*COUNT)microsecond" }, { "code": null, "e": 26383, "s": 26358, "text": "Therefore, COUNT=(140)10" }, { "code": null, "e": 26399, "s": 26383, "text": "Kartikaybhutani" }, { "code": null, "e": 26414, "s": 26399, "text": "microprocessor" }, { "code": null, "e": 26433, "s": 26414, "text": "system-programming" }, { "code": null, "e": 26470, "s": 26433, "text": "Computer Organization & Architecture" }, { "code": null, "e": 26485, "s": 26470, "text": "microprocessor" }, { "code": null, "e": 26583, "s": 26485, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26592, "s": 26583, "text": "Comments" }, { "code": null, "e": 26605, "s": 26592, "text": "Old Comments" }, { "code": null, "e": 26641, "s": 26605, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 26732, "s": 26641, "text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)" }, { "code": null, "e": 26767, "s": 26732, "text": "Pin diagram of 8086 microprocessor" }, { "code": null, "e": 26829, "s": 26767, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 26864, "s": 26829, "text": "Memory mapped I/O and Isolated I/O" }, { "code": null, "e": 26913, "s": 26864, "text": "General purpose registers in 8086 microprocessor" }, { "code": null, "e": 26946, "s": 26913, "text": "Difference between SRAM and DRAM" }, { "code": null, "e": 26979, "s": 26946, "text": "Registers of 8085 microprocessor" }, { "code": null, "e": 27022, "s": 26979, "text": "8085 program to multiply two 8 bit numbers" } ]
Top 4 Python libraries to build interactive timeseries plots | by Shoumik Goswami | Towards Data Science
One of the most prevalent data types encountered while analyzing data is timeseries. From identifying trends to understanding ’cause and effect’ behaviors, timeseries analysis is one of the most popular ways of understanding user behaviors, buying patterns, and much more. In Python, we often start by plotting a simple line curve using Matplotlib or Seaborn, which are perfect, if you are working with just one categorical variable changing over time. But often you’ll need to show multiple categorical variables together e.g. a list of stocks for market data, or regions/locations for sales data. In such cases, you can either show all your series in the same plot or create a separate plot for each series. However, these options are hard to make sense of and take up a lot of space. This is where advanced visualization libraries like Plotly, Bokeh, and Altair come into the picture, as they allow you to create interactive plots and dashboards using features like dropdowns, sliders, buttons, etc., which help your users explore complex data. In this article, we will explore two interactive elements for timeseries visualization - Dropdown menus let you toggle between different series in the same plot Date range sliders allowing you to observe trends between specific periods All codes used in the below examples can be found here. Disclaimer: This article is written in collaboration with Datapane and I work on the datapane team as a community evangelist. A dropdown menu is really handy if you have a lot of categories in the data, e.g. stocks or countries, and you want to observe the trends using a line plot in the same plot or figure. This saves you from creating several plots in a loop. All three libraries i.e. Plotly, Bokeh, and Altair allow you to add a dropdown menu to the plots but each of them has its pros and cons. As a bonus, I will also show you a way to do this using Matplotlib or Seaborn, which do not support interactive components out of the box. Plotly offers a range of interactive options which are called Custom Controls. The best part about these controls is that they can be added to the plots purely in pythonic code. For the purposes of this tutorial, we are going to use Covid 19 dataset which can be accessed here. We will create a plot to visualize the spread of Covid 19 across the globe and add a dropdown to change the country within the same plot. buttons = []i = 0fig3 = go.Figure()country_list = list(df['country'].unique())for country in country_list: fig3.add_trace( go.Scatter( x = df['date'][df['country']==country], y = df['confirmed'][df['country']==country], name = country, visible = (i==0) ) ) for country in country_list: args = [False] * len(country_list) args[i] = True #create a button object for the country we are on button = dict(label = country, method = "update", args=[{"visible": args}]) #add the button to our list of buttons buttons.append(button) #i is an iterable used to tell our "args" list which value to set to True i+=1 fig3.update_layout(updatemenus=[dict(active=0, type="dropdown", buttons=buttons, x = 0, y = 1.1, xanchor = 'left', yanchor = 'bottom'), ])fig3.update_layout( autosize=False, width=1000, height=800,) And you will have a nice-looking dropdown added to the time-series plot. Bokeh has components called widgets which can be used to add several interactive components to your plots. Widgets are primarily aimed at creating dashboard components hosted on the Bokeh server. You can read more about widgets here. Keep in mind that in order to create widgets for standalone HTML files or even while working with Jupyter notebook, you will need to use CustomJS callbacks. This requires a bit of JavaScript knowledge to get the dropdown working properly. If you want to do it the pure pythonic way, you have to use the Bokeh server to make the widgets work. We will replicate the same use-case as above using Bokeh dropdowns. cols1=df.loc[:, ['country','date', 'confirmed']]cols2 = cols1[cols1['country'] == 'Afghanistan' ]Overall = ColumnDataSource(data=cols1)Curr=ColumnDataSource(data=cols2)#plot and the menu is linked with each other by this callback functioncallback = CustomJS(args=dict(source=Overall, sc=Curr), code="""var f = cb_obj.valuesc.data['date']=[]sc.data['confirmed']=[]for(var i = 0; i <= source.get_length(); i++){ if (source.data['country'][i] == f){ sc.data['date'].push(source.data['date'][i]) sc.data['confirmed'].push(source.data['confirmed'][i]) }} sc.change.emit();""")menu = Select(options=country_list,value='Afghanistan', title = 'Country') # drop down menubokeh_p=figure(x_axis_label ='date', y_axis_label = 'confirmed', y_axis_type="linear",x_axis_type="datetime") #creating figure objectbokeh_p.line(x='date', y='confirmed', color='green', source=Curr) # plotting the data using glyph circlemenu.js_on_change('value', callback) # calling the function on change of selectionlayout=column(menu, bokeh_p) # creating the layoutshow(layout) This is how the plot will look like - Altair is similar to Plotly when it comes to building visualizations in a pure pythonic way. While Altair offers a number of interactive components, it is a bit difficult to arrange the components in a user-friendly layout. You can read more about interactive components with Altair here. We will now create the same plot using Altair and add a dropdown menu to the plot. input_dropdown = alt.binding_select(options=country_list)selection = alt.selection_single(fields=['country'], bind=input_dropdown, name='Country')alt_plot = alt.Chart(df).mark_line().encode( x='date', y='confirmed', tooltip='confirmed').add_selection( selection).transform_filter( selection)alt_plot This is how the plot will look like - If you want to use a non-interactive library like Matplotlib or Seaborn, you can add interactivity using Datapane, which is a library for creating and hosting data reports. Datapane offers some advanced layout blocks like dp.Select which let you mimic the interactive filtering ability, like this: plot_list = []plt.figure(figsize=(10, 5), dpi=300)for country in country_list: plot = dp.Plot(df[df['country']==country].plot.scatter(x='date', y='confirmed'), label=country) plot_list.append(plot)report = dp.Report( dp.Text('''## Dropdown using Datapane'''), dp.Select(blocks = plot_list))report.preview() This is how it will look like - Please note that you cannot add Date Range sliders to your plots using Datapane currently. If you are new to Datapane, you can read more about different blocks here. Another interactive component that comes really handy while working with timeseries plots is a date range slider or a slider in general. Since most of the timeseries plots have a date range in the X-axis, a slider allows you to dynamically change the period and view only a section of the plot to understand the trends for that particular period. Plotly has a generic slider component that can be used to change the data corresponding to any axis. While it does not have a specific slider for timeseries data, the generic slider can be used to create a date range slider. You can read more about sliders here. To create a slider, we will take the same timeseries plot created previously with the dropdown menu and add a slider component below the plot. buttons = []i = 0fig3 = go.Figure()country_list = list(df['country'].unique())for country in country_list: fig3.add_trace( go.Scatter( x = df['date'][df['country']==country], y = df['confirmed'][df['country']==country], name = country, visible = (i==0) ) ) for country in country_list: args = [False] * len(country_list) args[i] = True #create a button object for the country we are on button = dict(label = country, method = "update", args=[{"visible": args}]) #add the button to our list of buttons buttons.append(button) #i is an iterable used to tell our "args" list which value to set to True i+=1 fig3.update_layout(updatemenus=[dict(active=0, type="dropdown", buttons=buttons, x = 0, y = 1.1, xanchor = 'left', yanchor = 'bottom'), ])fig3.update_layout( autosize=False, width=1000, height=800,) This will give you something like this - Similar to the Dropdown widget, Bokeh has a Date Range Slider widget specifically to work with timeseries data. This widget is different from the generic Range Slider widget. In order to make this widget work, a CustomJS callback is required. cols1=df.loc[:, ['country','date', 'confirmed']]cols2 = cols1[cols1['country'] == 'Afghanistan' ]Overall = ColumnDataSource(data=cols1)Curr=ColumnDataSource(data=cols2)#plot and the menu is linked with each other by this callback functioncallback = CustomJS(args=dict(source=Overall, sc=Curr), code="""var f = cb_obj.valuesc.data['date']=[]sc.data['confirmed']=[]for(var i = 0; i <= source.get_length(); i++){ if (source.data['country'][i] == f){ sc.data['date'].push(source.data['date'][i]) sc.data['confirmed'].push(source.data['confirmed'][i]) }} sc.change.emit();""")menu = Select(options=country_list,value='Afghanistan', title = 'Country') # drop down menubokeh_p=figure(x_axis_label ='date', y_axis_label = 'confirmed', y_axis_type="linear",x_axis_type="datetime") #creating figure object bokeh_p.line(x='date', y='confirmed', color='green', source=Curr) # plotting the data using glyph circlemenu.js_on_change('value', callback) # calling the function on change of selectiondate_range_slider = DateRangeSlider(value=(min(df['date']), max(df['date'])), start=min(df['date']), end=max(df['date']))date_range_slider.js_link("value", bokeh_p.x_range, "start", attr_selector=0)date_range_slider.js_link("value", bokeh_p.x_range, "end", attr_selector=1)layout = column(menu, date_range_slider, bokeh_p)show(layout) # displaying the layout This is how it will look like - With Altair, similar to Plotly, you can use the generic slider to use as a Date Range Slider. However, keep in mind that Vega considers the timeseries data in milliseconds and it is very difficult to show the date information in the slider. It works if you have yearly data but if the data is broken into days and months, it is tricky to make it work. input_dropdown = alt.binding_select(options=country_list)selection = alt.selection_single(fields=['country'], bind=input_dropdown, name='Country')def timestamp(t): return pd.to_datetime(t).timestamp() * 1000slider = alt.binding_range( step=30 * 24 * 60 * 60 * 1000, # 30 days in milliseconds min=timestamp(min(df['date'])), max=timestamp(max(df['date'])))select_date = alt.selection_single( fields=['date'], bind=slider, init={'date': timestamp(min(df['date']))}, name='slider')alt_plot = alt.Chart(df).mark_line().encode( x='date', y='confirmed', tooltip='confirmed').add_selection( selection).transform_filter( selection).add_selection(select_date).transform_filter( "(year(datum.date) == year(slider.date[0])) && " "(month(datum.date) == month(slider.date[0]))")alt_plot This is how it will look like - Now having worked with all three libraries, we are in a state to compare them and share our views on which is the best python library to create interactive visualizations. Pros - Easy to use and works seamlessly with Python. Layouts can be designed as per requirements to ensure the menus appear in the right areas of the plot. Easy to view and embed Plotly plots. Cons - Does not offer many interactive components. Has a steep learning curve to make the interactive components work. Pros - Plots and interactive widgets created with Bokeh look aesthetically pleasing. Since Bokeh is more directed towards creating dashboards, it is easier to create layouts using multiple components. A number of interactive widgets can be added to the plots. Cons - In order to make the widgets work, you need to know a bit of JavaScript to be able to create the CustomJS callbacks. Lack of proper documentation with sample codes when it comes to creating these JavaScript callbacks. Difficult to embed these plots unless you are working with Bokeh Server. Pros - Altair offers more options of interactive components compared to Plotly. Easy to build interactive components using pure Python. Requires fewer lines of code to make the interactive components work. Cons - It is difficult to design and create visually appealing layouts using Altair. Working with timeseries data is not straightforward as Vega does not support timeseries data out of the box and some transformations are required to make it work. Overall, if you are getting started with interactive plots using Python, Plotly can be a good choice to create simple plots with limited interactive components. But if you are looking to add a number of interactive components to your plots, then Altair is something you should really try your hands on. The best part is you can add several interactive components with just Python codes. If you are looking to build extremely complex dashboards which are interactive, you can use Bokeh. But bear in mind that you will need some JavaScript know-how to make them work. Datapane can be a good option if you want to stick to non-interactive visualization libraries like Matplotlib and Seaborn and still want some form of interactivity like having just a dropdown menu. I hope you find this tutorial along with the sample codes useful. Do share your thoughts or feedback in the comments below.
[ { "code": null, "e": 444, "s": 171, "text": "One of the most prevalent data types encountered while analyzing data is timeseries. From identifying trends to understanding ’cause and effect’ behaviors, timeseries analysis is one of the most popular ways of understanding user behaviors, buying patterns, and much more." }, { "code": null, "e": 770, "s": 444, "text": "In Python, we often start by plotting a simple line curve using Matplotlib or Seaborn, which are perfect, if you are working with just one categorical variable changing over time. But often you’ll need to show multiple categorical variables together e.g. a list of stocks for market data, or regions/locations for sales data." }, { "code": null, "e": 958, "s": 770, "text": "In such cases, you can either show all your series in the same plot or create a separate plot for each series. However, these options are hard to make sense of and take up a lot of space." }, { "code": null, "e": 1219, "s": 958, "text": "This is where advanced visualization libraries like Plotly, Bokeh, and Altair come into the picture, as they allow you to create interactive plots and dashboards using features like dropdowns, sliders, buttons, etc., which help your users explore complex data." }, { "code": null, "e": 1308, "s": 1219, "text": "In this article, we will explore two interactive elements for timeseries visualization -" }, { "code": null, "e": 1380, "s": 1308, "text": "Dropdown menus let you toggle between different series in the same plot" }, { "code": null, "e": 1455, "s": 1380, "text": "Date range sliders allowing you to observe trends between specific periods" }, { "code": null, "e": 1511, "s": 1455, "text": "All codes used in the below examples can be found here." }, { "code": null, "e": 1637, "s": 1511, "text": "Disclaimer: This article is written in collaboration with Datapane and I work on the datapane team as a community evangelist." }, { "code": null, "e": 1875, "s": 1637, "text": "A dropdown menu is really handy if you have a lot of categories in the data, e.g. stocks or countries, and you want to observe the trends using a line plot in the same plot or figure. This saves you from creating several plots in a loop." }, { "code": null, "e": 2012, "s": 1875, "text": "All three libraries i.e. Plotly, Bokeh, and Altair allow you to add a dropdown menu to the plots but each of them has its pros and cons." }, { "code": null, "e": 2151, "s": 2012, "text": "As a bonus, I will also show you a way to do this using Matplotlib or Seaborn, which do not support interactive components out of the box." }, { "code": null, "e": 2329, "s": 2151, "text": "Plotly offers a range of interactive options which are called Custom Controls. The best part about these controls is that they can be added to the plots purely in pythonic code." }, { "code": null, "e": 2429, "s": 2329, "text": "For the purposes of this tutorial, we are going to use Covid 19 dataset which can be accessed here." }, { "code": null, "e": 2567, "s": 2429, "text": "We will create a plot to visualize the spread of Covid 19 across the globe and add a dropdown to change the country within the same plot." }, { "code": null, "e": 3746, "s": 2567, "text": "buttons = []i = 0fig3 = go.Figure()country_list = list(df['country'].unique())for country in country_list: fig3.add_trace( go.Scatter( x = df['date'][df['country']==country], y = df['confirmed'][df['country']==country], name = country, visible = (i==0) ) ) for country in country_list: args = [False] * len(country_list) args[i] = True #create a button object for the country we are on button = dict(label = country, method = \"update\", args=[{\"visible\": args}]) #add the button to our list of buttons buttons.append(button) #i is an iterable used to tell our \"args\" list which value to set to True i+=1 fig3.update_layout(updatemenus=[dict(active=0, type=\"dropdown\", buttons=buttons, x = 0, y = 1.1, xanchor = 'left', yanchor = 'bottom'), ])fig3.update_layout( autosize=False, width=1000, height=800,)" }, { "code": null, "e": 3819, "s": 3746, "text": "And you will have a nice-looking dropdown added to the time-series plot." }, { "code": null, "e": 4053, "s": 3819, "text": "Bokeh has components called widgets which can be used to add several interactive components to your plots. Widgets are primarily aimed at creating dashboard components hosted on the Bokeh server. You can read more about widgets here." }, { "code": null, "e": 4395, "s": 4053, "text": "Keep in mind that in order to create widgets for standalone HTML files or even while working with Jupyter notebook, you will need to use CustomJS callbacks. This requires a bit of JavaScript knowledge to get the dropdown working properly. If you want to do it the pure pythonic way, you have to use the Bokeh server to make the widgets work." }, { "code": null, "e": 4463, "s": 4395, "text": "We will replicate the same use-case as above using Bokeh dropdowns." }, { "code": null, "e": 5516, "s": 4463, "text": "cols1=df.loc[:, ['country','date', 'confirmed']]cols2 = cols1[cols1['country'] == 'Afghanistan' ]Overall = ColumnDataSource(data=cols1)Curr=ColumnDataSource(data=cols2)#plot and the menu is linked with each other by this callback functioncallback = CustomJS(args=dict(source=Overall, sc=Curr), code=\"\"\"var f = cb_obj.valuesc.data['date']=[]sc.data['confirmed']=[]for(var i = 0; i <= source.get_length(); i++){\tif (source.data['country'][i] == f){\t\tsc.data['date'].push(source.data['date'][i])\t\tsc.data['confirmed'].push(source.data['confirmed'][i])\t }} sc.change.emit();\"\"\")menu = Select(options=country_list,value='Afghanistan', title = 'Country') # drop down menubokeh_p=figure(x_axis_label ='date', y_axis_label = 'confirmed', y_axis_type=\"linear\",x_axis_type=\"datetime\") #creating figure objectbokeh_p.line(x='date', y='confirmed', color='green', source=Curr) # plotting the data using glyph circlemenu.js_on_change('value', callback) # calling the function on change of selectionlayout=column(menu, bokeh_p) # creating the layoutshow(layout)" }, { "code": null, "e": 5554, "s": 5516, "text": "This is how the plot will look like -" }, { "code": null, "e": 5843, "s": 5554, "text": "Altair is similar to Plotly when it comes to building visualizations in a pure pythonic way. While Altair offers a number of interactive components, it is a bit difficult to arrange the components in a user-friendly layout. You can read more about interactive components with Altair here." }, { "code": null, "e": 5926, "s": 5843, "text": "We will now create the same plot using Altair and add a dropdown menu to the plot." }, { "code": null, "e": 6241, "s": 5926, "text": "input_dropdown = alt.binding_select(options=country_list)selection = alt.selection_single(fields=['country'], bind=input_dropdown, name='Country')alt_plot = alt.Chart(df).mark_line().encode( x='date', y='confirmed', tooltip='confirmed').add_selection( selection).transform_filter( selection)alt_plot" }, { "code": null, "e": 6279, "s": 6241, "text": "This is how the plot will look like -" }, { "code": null, "e": 6577, "s": 6279, "text": "If you want to use a non-interactive library like Matplotlib or Seaborn, you can add interactivity using Datapane, which is a library for creating and hosting data reports. Datapane offers some advanced layout blocks like dp.Select which let you mimic the interactive filtering ability, like this:" }, { "code": null, "e": 6896, "s": 6577, "text": "plot_list = []plt.figure(figsize=(10, 5), dpi=300)for country in country_list: plot = dp.Plot(df[df['country']==country].plot.scatter(x='date', y='confirmed'), label=country) plot_list.append(plot)report = dp.Report( dp.Text('''## Dropdown using Datapane'''), dp.Select(blocks = plot_list))report.preview()" }, { "code": null, "e": 6928, "s": 6896, "text": "This is how it will look like -" }, { "code": null, "e": 7094, "s": 6928, "text": "Please note that you cannot add Date Range sliders to your plots using Datapane currently. If you are new to Datapane, you can read more about different blocks here." }, { "code": null, "e": 7231, "s": 7094, "text": "Another interactive component that comes really handy while working with timeseries plots is a date range slider or a slider in general." }, { "code": null, "e": 7441, "s": 7231, "text": "Since most of the timeseries plots have a date range in the X-axis, a slider allows you to dynamically change the period and view only a section of the plot to understand the trends for that particular period." }, { "code": null, "e": 7666, "s": 7441, "text": "Plotly has a generic slider component that can be used to change the data corresponding to any axis. While it does not have a specific slider for timeseries data, the generic slider can be used to create a date range slider." }, { "code": null, "e": 7704, "s": 7666, "text": "You can read more about sliders here." }, { "code": null, "e": 7847, "s": 7704, "text": "To create a slider, we will take the same timeseries plot created previously with the dropdown menu and add a slider component below the plot." }, { "code": null, "e": 9026, "s": 7847, "text": "buttons = []i = 0fig3 = go.Figure()country_list = list(df['country'].unique())for country in country_list: fig3.add_trace( go.Scatter( x = df['date'][df['country']==country], y = df['confirmed'][df['country']==country], name = country, visible = (i==0) ) ) for country in country_list: args = [False] * len(country_list) args[i] = True #create a button object for the country we are on button = dict(label = country, method = \"update\", args=[{\"visible\": args}]) #add the button to our list of buttons buttons.append(button) #i is an iterable used to tell our \"args\" list which value to set to True i+=1 fig3.update_layout(updatemenus=[dict(active=0, type=\"dropdown\", buttons=buttons, x = 0, y = 1.1, xanchor = 'left', yanchor = 'bottom'), ])fig3.update_layout( autosize=False, width=1000, height=800,)" }, { "code": null, "e": 9067, "s": 9026, "text": "This will give you something like this -" }, { "code": null, "e": 9310, "s": 9067, "text": "Similar to the Dropdown widget, Bokeh has a Date Range Slider widget specifically to work with timeseries data. This widget is different from the generic Range Slider widget. In order to make this widget work, a CustomJS callback is required." }, { "code": null, "e": 10695, "s": 9310, "text": "cols1=df.loc[:, ['country','date', 'confirmed']]cols2 = cols1[cols1['country'] == 'Afghanistan' ]Overall = ColumnDataSource(data=cols1)Curr=ColumnDataSource(data=cols2)#plot and the menu is linked with each other by this callback functioncallback = CustomJS(args=dict(source=Overall, sc=Curr), code=\"\"\"var f = cb_obj.valuesc.data['date']=[]sc.data['confirmed']=[]for(var i = 0; i <= source.get_length(); i++){\tif (source.data['country'][i] == f){\t\tsc.data['date'].push(source.data['date'][i])\t\tsc.data['confirmed'].push(source.data['confirmed'][i])\t }} sc.change.emit();\"\"\")menu = Select(options=country_list,value='Afghanistan', title = 'Country') # drop down menubokeh_p=figure(x_axis_label ='date', y_axis_label = 'confirmed', y_axis_type=\"linear\",x_axis_type=\"datetime\") #creating figure object bokeh_p.line(x='date', y='confirmed', color='green', source=Curr) # plotting the data using glyph circlemenu.js_on_change('value', callback) # calling the function on change of selectiondate_range_slider = DateRangeSlider(value=(min(df['date']), max(df['date'])), start=min(df['date']), end=max(df['date']))date_range_slider.js_link(\"value\", bokeh_p.x_range, \"start\", attr_selector=0)date_range_slider.js_link(\"value\", bokeh_p.x_range, \"end\", attr_selector=1)layout = column(menu, date_range_slider, bokeh_p)show(layout) # displaying the layout" }, { "code": null, "e": 10727, "s": 10695, "text": "This is how it will look like -" }, { "code": null, "e": 11079, "s": 10727, "text": "With Altair, similar to Plotly, you can use the generic slider to use as a Date Range Slider. However, keep in mind that Vega considers the timeseries data in milliseconds and it is very difficult to show the date information in the slider. It works if you have yearly data but if the data is broken into days and months, it is tricky to make it work." }, { "code": null, "e": 11896, "s": 11079, "text": "input_dropdown = alt.binding_select(options=country_list)selection = alt.selection_single(fields=['country'], bind=input_dropdown, name='Country')def timestamp(t): return pd.to_datetime(t).timestamp() * 1000slider = alt.binding_range( step=30 * 24 * 60 * 60 * 1000, # 30 days in milliseconds min=timestamp(min(df['date'])), max=timestamp(max(df['date'])))select_date = alt.selection_single( fields=['date'], bind=slider, init={'date': timestamp(min(df['date']))}, name='slider')alt_plot = alt.Chart(df).mark_line().encode( x='date', y='confirmed', tooltip='confirmed').add_selection( selection).transform_filter( selection).add_selection(select_date).transform_filter( \"(year(datum.date) == year(slider.date[0])) && \" \"(month(datum.date) == month(slider.date[0]))\")alt_plot" }, { "code": null, "e": 11928, "s": 11896, "text": "This is how it will look like -" }, { "code": null, "e": 12100, "s": 11928, "text": "Now having worked with all three libraries, we are in a state to compare them and share our views on which is the best python library to create interactive visualizations." }, { "code": null, "e": 12107, "s": 12100, "text": "Pros -" }, { "code": null, "e": 12153, "s": 12107, "text": "Easy to use and works seamlessly with Python." }, { "code": null, "e": 12256, "s": 12153, "text": "Layouts can be designed as per requirements to ensure the menus appear in the right areas of the plot." }, { "code": null, "e": 12293, "s": 12256, "text": "Easy to view and embed Plotly plots." }, { "code": null, "e": 12300, "s": 12293, "text": "Cons -" }, { "code": null, "e": 12344, "s": 12300, "text": "Does not offer many interactive components." }, { "code": null, "e": 12412, "s": 12344, "text": "Has a steep learning curve to make the interactive components work." }, { "code": null, "e": 12419, "s": 12412, "text": "Pros -" }, { "code": null, "e": 12497, "s": 12419, "text": "Plots and interactive widgets created with Bokeh look aesthetically pleasing." }, { "code": null, "e": 12613, "s": 12497, "text": "Since Bokeh is more directed towards creating dashboards, it is easier to create layouts using multiple components." }, { "code": null, "e": 12672, "s": 12613, "text": "A number of interactive widgets can be added to the plots." }, { "code": null, "e": 12679, "s": 12672, "text": "Cons -" }, { "code": null, "e": 12796, "s": 12679, "text": "In order to make the widgets work, you need to know a bit of JavaScript to be able to create the CustomJS callbacks." }, { "code": null, "e": 12897, "s": 12796, "text": "Lack of proper documentation with sample codes when it comes to creating these JavaScript callbacks." }, { "code": null, "e": 12970, "s": 12897, "text": "Difficult to embed these plots unless you are working with Bokeh Server." }, { "code": null, "e": 12977, "s": 12970, "text": "Pros -" }, { "code": null, "e": 13050, "s": 12977, "text": "Altair offers more options of interactive components compared to Plotly." }, { "code": null, "e": 13106, "s": 13050, "text": "Easy to build interactive components using pure Python." }, { "code": null, "e": 13176, "s": 13106, "text": "Requires fewer lines of code to make the interactive components work." }, { "code": null, "e": 13183, "s": 13176, "text": "Cons -" }, { "code": null, "e": 13261, "s": 13183, "text": "It is difficult to design and create visually appealing layouts using Altair." }, { "code": null, "e": 13424, "s": 13261, "text": "Working with timeseries data is not straightforward as Vega does not support timeseries data out of the box and some transformations are required to make it work." }, { "code": null, "e": 13585, "s": 13424, "text": "Overall, if you are getting started with interactive plots using Python, Plotly can be a good choice to create simple plots with limited interactive components." }, { "code": null, "e": 13811, "s": 13585, "text": "But if you are looking to add a number of interactive components to your plots, then Altair is something you should really try your hands on. The best part is you can add several interactive components with just Python codes." }, { "code": null, "e": 13990, "s": 13811, "text": "If you are looking to build extremely complex dashboards which are interactive, you can use Bokeh. But bear in mind that you will need some JavaScript know-how to make them work." }, { "code": null, "e": 14188, "s": 13990, "text": "Datapane can be a good option if you want to stick to non-interactive visualization libraries like Matplotlib and Seaborn and still want some form of interactivity like having just a dropdown menu." } ]
Create Table Using Tkinter
24 Feb, 2022 Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.Note: For more information, refer to Python GUI – tkinter A table is useful to display data in the form of rows and columns. Unfortunately, Tkinter does not provide a Table widget to create a table. But we can create a table using alternate methods. For example, we can make a table by repeatedly displaying entry widgets in the form of rows and columns.To create a table with five rows and four columns we can use two for loops as: for i in range(5): for j in range(4): Inside these loops, we have to create an Entry widget by creating an object of Entry class, as: e = Entry(root, width=20, fg='blue', font=('Arial', 16, 'bold') Now, we need logic to place this Entry widget in rows and columns. This can be done by using grid() method to which we can pass row and column positions, as: # here i and j indicate # row and column positions e.grid(row=i, column=j) We can insert data into the Entry widget using insert() method, as: e.insert(END, data) Here, ‘END’ indicates that the data continuous to append at the end of previous data in the Entry widget.This is the logic that is used in the program given below using the data that is coming from a list. We have taken a list containing 5 tuples and each tuple contains four values which indicate student id, name, city and age.Hence, we will have a table with 5 rows and 4 columns in each row. This program can also be applied on data coming from a database to display the entire data in the form of a table.Source Code: Python3 # Python program to create a table from tkinter import * class Table: def __init__(self,root): # code for creating table for i in range(total_rows): for j in range(total_columns): self.e = Entry(root, width=20, fg='blue', font=('Arial',16,'bold')) self.e.grid(row=i, column=j) self.e.insert(END, lst[i][j]) # take the datalst = [(1,'Raj','Mumbai',19), (2,'Aaryan','Pune',18), (3,'Vaishnavi','Mumbai',20), (4,'Rachna','Mumbai',21), (5,'Shubham','Delhi',21)] # find total number of rows and# columns in listtotal_rows = len(lst)total_columns = len(lst[0]) # create root windowroot = Tk()t = Table(root)root.mainloop() Output: geeky01adarsh Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Feb, 2022" }, { "code": null, "e": 464, "s": 54, "text": "Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.Note: For more information, refer to Python GUI – tkinter " }, { "code": null, "e": 841, "s": 464, "text": "A table is useful to display data in the form of rows and columns. Unfortunately, Tkinter does not provide a Table widget to create a table. But we can create a table using alternate methods. For example, we can make a table by repeatedly displaying entry widgets in the form of rows and columns.To create a table with five rows and four columns we can use two for loops as: " }, { "code": null, "e": 883, "s": 841, "text": "for i in range(5):\n for j in range(4):" }, { "code": null, "e": 981, "s": 883, "text": "Inside these loops, we have to create an Entry widget by creating an object of Entry class, as: " }, { "code": null, "e": 1045, "s": 981, "text": "e = Entry(root, width=20, fg='blue', font=('Arial', 16, 'bold')" }, { "code": null, "e": 1205, "s": 1045, "text": "Now, we need logic to place this Entry widget in rows and columns. This can be done by using grid() method to which we can pass row and column positions, as: " }, { "code": null, "e": 1281, "s": 1205, "text": "# here i and j indicate \n# row and column positions\ne.grid(row=i, column=j)" }, { "code": null, "e": 1351, "s": 1281, "text": "We can insert data into the Entry widget using insert() method, as: " }, { "code": null, "e": 1371, "s": 1351, "text": "e.insert(END, data)" }, { "code": null, "e": 1896, "s": 1371, "text": "Here, ‘END’ indicates that the data continuous to append at the end of previous data in the Entry widget.This is the logic that is used in the program given below using the data that is coming from a list. We have taken a list containing 5 tuples and each tuple contains four values which indicate student id, name, city and age.Hence, we will have a table with 5 rows and 4 columns in each row. This program can also be applied on data coming from a database to display the entire data in the form of a table.Source Code: " }, { "code": null, "e": 1904, "s": 1896, "text": "Python3" }, { "code": "# Python program to create a table from tkinter import * class Table: def __init__(self,root): # code for creating table for i in range(total_rows): for j in range(total_columns): self.e = Entry(root, width=20, fg='blue', font=('Arial',16,'bold')) self.e.grid(row=i, column=j) self.e.insert(END, lst[i][j]) # take the datalst = [(1,'Raj','Mumbai',19), (2,'Aaryan','Pune',18), (3,'Vaishnavi','Mumbai',20), (4,'Rachna','Mumbai',21), (5,'Shubham','Delhi',21)] # find total number of rows and# columns in listtotal_rows = len(lst)total_columns = len(lst[0]) # create root windowroot = Tk()t = Table(root)root.mainloop()", "e": 2699, "s": 1904, "text": null }, { "code": null, "e": 2709, "s": 2699, "text": "Output: " }, { "code": null, "e": 2725, "s": 2711, "text": "geeky01adarsh" }, { "code": null, "e": 2740, "s": 2725, "text": "Python-tkinter" }, { "code": null, "e": 2747, "s": 2740, "text": "Python" }, { "code": null, "e": 2845, "s": 2747, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2863, "s": 2845, "text": "Python Dictionary" }, { "code": null, "e": 2905, "s": 2863, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2927, "s": 2905, "text": "Enumerate() in Python" }, { "code": null, "e": 2953, "s": 2927, "text": "Python String | replace()" }, { "code": null, "e": 2985, "s": 2953, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3014, "s": 2985, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3041, "s": 3014, "text": "Python Classes and Objects" }, { "code": null, "e": 3071, "s": 3041, "text": "Iterate over a list in Python" }, { "code": null, "e": 3092, "s": 3071, "text": "Python OOPs Concepts" } ]
Python | sympy.Matrix.row_del() method
12 Jun, 2019 With the help of sympy.Matrix.row_del() method, we can delete the rows of the matrix. Syntax : sympy.Matrix().row_del()Return : Return a new matrix. Example #1 : # Import all the methods from sympyfrom sympy import * # use the row_del() method for matrixgfg_val = Matrix([[1, 2], [2, 1]]).col_row(1) print(gfg_val) Output : Matrix([1, 2]) Example #2 : from sympy import * # use the row_del() method for matrixgfg_val = Matrix([[1, 2], [2, 3], [23, 45]]).row_del(0) print(gfg_val) Output : Matrix([[2, 3], [23, 45]]) SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jun, 2019" }, { "code": null, "e": 114, "s": 28, "text": "With the help of sympy.Matrix.row_del() method, we can delete the rows of the matrix." }, { "code": null, "e": 177, "s": 114, "text": "Syntax : sympy.Matrix().row_del()Return : Return a new matrix." }, { "code": null, "e": 190, "s": 177, "text": "Example #1 :" }, { "code": "# Import all the methods from sympyfrom sympy import * # use the row_del() method for matrixgfg_val = Matrix([[1, 2], [2, 1]]).col_row(1) print(gfg_val)", "e": 345, "s": 190, "text": null }, { "code": null, "e": 354, "s": 345, "text": "Output :" }, { "code": null, "e": 369, "s": 354, "text": "Matrix([1, 2])" }, { "code": null, "e": 382, "s": 369, "text": "Example #2 :" }, { "code": "from sympy import * # use the row_del() method for matrixgfg_val = Matrix([[1, 2], [2, 3], [23, 45]]).row_del(0) print(gfg_val)", "e": 512, "s": 382, "text": null }, { "code": null, "e": 521, "s": 512, "text": "Output :" }, { "code": null, "e": 548, "s": 521, "text": "Matrix([[2, 3], [23, 45]])" }, { "code": null, "e": 554, "s": 548, "text": "SymPy" }, { "code": null, "e": 561, "s": 554, "text": "Python" }, { "code": null, "e": 659, "s": 561, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 691, "s": 659, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 718, "s": 691, "text": "Python Classes and Objects" }, { "code": null, "e": 739, "s": 718, "text": "Python OOPs Concepts" }, { "code": null, "e": 762, "s": 739, "text": "Introduction To PYTHON" }, { "code": null, "e": 818, "s": 762, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 849, "s": 818, "text": "Python | os.path.join() method" }, { "code": null, "e": 891, "s": 849, "text": "Check if element exists in list in Python" }, { "code": null, "e": 933, "s": 891, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 972, "s": 933, "text": "Python | Get unique values from a list" } ]
Minimum of two numbers in Python
17 May, 2020 Given two numbers, write a Python code to find the Minimum of these two numbers. Examples: Input: a = 2, b = 4 Output: 2 Input: a = -1, b = -4 Output: -4 Method #1: This is the naive approach where we will compare the numbers using if-else statement and will print the output accordingly. Example: # Python program to find the# minimum of two numbers def minimum(a, b): if a <= b: return a else: return b # Driver codea = 2b = 4print(minimum(a, b)) Output: 2 Method #2: Using min() function This function is used to find the minimum of the values passed as its arguments. Example: # Python program to find the# minimum of two numbers a = 2b = 4 minimum = min(a, b)print(minimum) Output: 2 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 53, "s": 25, "text": "\n17 May, 2020" }, { "code": null, "e": 134, "s": 53, "text": "Given two numbers, write a Python code to find the Minimum of these two numbers." }, { "code": null, "e": 144, "s": 134, "text": "Examples:" }, { "code": null, "e": 209, "s": 144, "text": "Input: a = 2, b = 4\nOutput: 2\n\nInput: a = -1, b = -4\nOutput: -4\n" }, { "code": null, "e": 344, "s": 209, "text": "Method #1: This is the naive approach where we will compare the numbers using if-else statement and will print the output accordingly." }, { "code": null, "e": 353, "s": 344, "text": "Example:" }, { "code": "# Python program to find the# minimum of two numbers def minimum(a, b): if a <= b: return a else: return b # Driver codea = 2b = 4print(minimum(a, b))", "e": 538, "s": 353, "text": null }, { "code": null, "e": 546, "s": 538, "text": "Output:" }, { "code": null, "e": 548, "s": 546, "text": "2" }, { "code": null, "e": 580, "s": 548, "text": "Method #2: Using min() function" }, { "code": null, "e": 661, "s": 580, "text": "This function is used to find the minimum of the values passed as its arguments." }, { "code": null, "e": 670, "s": 661, "text": "Example:" }, { "code": "# Python program to find the# minimum of two numbers a = 2b = 4 minimum = min(a, b)print(minimum)", "e": 772, "s": 670, "text": null }, { "code": null, "e": 780, "s": 772, "text": "Output:" }, { "code": null, "e": 782, "s": 780, "text": "2" }, { "code": null, "e": 803, "s": 782, "text": "Python list-programs" }, { "code": null, "e": 810, "s": 803, "text": "Python" }, { "code": null, "e": 826, "s": 810, "text": "Python Programs" }, { "code": null, "e": 924, "s": 826, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 956, "s": 924, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 983, "s": 956, "text": "Python Classes and Objects" }, { "code": null, "e": 1004, "s": 983, "text": "Python OOPs Concepts" }, { "code": null, "e": 1027, "s": 1004, "text": "Introduction To PYTHON" }, { "code": null, "e": 1083, "s": 1027, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1105, "s": 1083, "text": "Defaultdict in Python" }, { "code": null, "e": 1144, "s": 1105, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1182, "s": 1144, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 1231, "s": 1182, "text": "Python | Convert string dictionary to dictionary" } ]
Python | Check if a given object is list or not
19 Mar, 2019 Given an object, the task is to check whether the object is list or not. Method #1: Using isinstance # Python code to demonstrate# check whether the object # is a list or not # initialisation listini_list1 = [1, 2, 3, 4, 5]ini_list2 = '12345' # code to check whether# object is a list or notif isinstance(ini_list1, list): print("your object is a list !")else: print("your object is not a list") if isinstance(ini_list2, list): print("your object is a list")else: print("your object is not a list") your object is a list ! your object is not a list Method #2: Using type(x) # Python code to demonstrate# check whether object # is a list or not # initialisation listini_list1 = [1, 2, 3, 4, 5]ini_list2 = (12, 22, 33) # code to check whether# object is a list or notif type(ini_list1) is list: print("your object is a list")else: print("your object is not a list") if type(ini_list2) is list: print("your object is a list")else: print("your object is not a list") your object is a list your object is not a list Python list-programs python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Mar, 2019" }, { "code": null, "e": 101, "s": 28, "text": "Given an object, the task is to check whether the object is list or not." }, { "code": null, "e": 129, "s": 101, "text": "Method #1: Using isinstance" }, { "code": "# Python code to demonstrate# check whether the object # is a list or not # initialisation listini_list1 = [1, 2, 3, 4, 5]ini_list2 = '12345' # code to check whether# object is a list or notif isinstance(ini_list1, list): print(\"your object is a list !\")else: print(\"your object is not a list\") if isinstance(ini_list2, list): print(\"your object is a list\")else: print(\"your object is not a list\")", "e": 542, "s": 129, "text": null }, { "code": null, "e": 593, "s": 542, "text": "your object is a list !\nyour object is not a list\n" }, { "code": null, "e": 619, "s": 593, "text": " Method #2: Using type(x)" }, { "code": "# Python code to demonstrate# check whether object # is a list or not # initialisation listini_list1 = [1, 2, 3, 4, 5]ini_list2 = (12, 22, 33) # code to check whether# object is a list or notif type(ini_list1) is list: print(\"your object is a list\")else: print(\"your object is not a list\") if type(ini_list2) is list: print(\"your object is a list\")else: print(\"your object is not a list\")", "e": 1023, "s": 619, "text": null }, { "code": null, "e": 1072, "s": 1023, "text": "your object is a list\nyour object is not a list\n" }, { "code": null, "e": 1093, "s": 1072, "text": "Python list-programs" }, { "code": null, "e": 1105, "s": 1093, "text": "python-list" }, { "code": null, "e": 1112, "s": 1105, "text": "Python" }, { "code": null, "e": 1128, "s": 1112, "text": "Python Programs" }, { "code": null, "e": 1140, "s": 1128, "text": "python-list" }, { "code": null, "e": 1238, "s": 1140, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1256, "s": 1238, "text": "Python Dictionary" }, { "code": null, "e": 1298, "s": 1256, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1320, "s": 1298, "text": "Enumerate() in Python" }, { "code": null, "e": 1355, "s": 1320, "text": "Read a file line by line in Python" }, { "code": null, "e": 1381, "s": 1355, "text": "Python String | replace()" }, { "code": null, "e": 1424, "s": 1381, "text": "Python program to convert a list to string" }, { "code": null, "e": 1446, "s": 1424, "text": "Defaultdict in Python" }, { "code": null, "e": 1485, "s": 1446, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1523, "s": 1485, "text": "Python | Convert a list to dictionary" } ]
How to pass a 2D array as a parameter in C?
24 Jun, 2021 This post is an extension of How to dynamically allocate a 2D array in C? A one dimensional array can be easily passed as a pointer, but syntax for passing a 2D array to a function can be difficult to remember. One important thing for passing multidimensional arrays is, first array dimension does not have to be specified. The second (and any subsequent) dimensions must be given1) When both dimensions are available globally (either as a macro or as a global constant). C #include <stdio.h>const int M = 3;const int N = 3; void print(int arr[M][N]){ int i, j; for (i = 0; i < M; i++) for (j = 0; j < N; j++) printf("%d ", arr[i][j]);} int main(){ int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; print(arr); return 0;} 1 2 3 4 5 6 7 8 9 2) When only second dimension is available globally (either as a macro or as a global constant). C #include <stdio.h>const int N = 3; void print(int arr[][N], int m){ int i, j; for (i = 0; i < m; i++) for (j = 0; j < N; j++) printf("%d ", arr[i][j]);} int main(){ int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; print(arr, 3); return 0;} 1 2 3 4 5 6 7 8 9 The above method is fine if second dimension is fixed and is not user specified. The following methods handle cases when second dimension can also change.3) If compiler is C99 compatible From C99, C language supports variable sized arrays to be passed simply by specifying the variable dimensions (See this for an example run) C // The following program works only if your compiler is C99 compatible.#include <stdio.h> // n must be passed before the 2D arrayvoid print(int m, int n, int arr[][n]){ int i, j; for (i = 0; i < m; i++) for (j = 0; j < n; j++) printf("%d ", arr[i][j]);} int main(){ int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int m = 3, n = 3; print(m, n, arr); return 0;} 1 2 3 4 5 6 7 8 9 If compiler is not C99 compatible, then we can use one of the following methods to pass a variable sized 2D array.4) Using a single pointer In this method, we must typecast the 2D array when passing to function. C #include <stdio.h>void print(int *arr, int m, int n){ int i, j; for (i = 0; i < m; i++) for (j = 0; j < n; j++) printf("%d ", *((arr+i*n) + j));} int main(){ int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int m = 3, n = 3; // We can also use "print(&arr[0][0], m, n);" print((int *)arr, m, n); return 0;} 1 2 3 4 5 6 7 8 9 5) Using the concept of pointer to an array C #include <stdio.h>const int M = 3; void print(int (*arr)[M]){ int i, j; for (i = 0; i < M; i++) for (j = 0; j < M; j++) printf("%d ", arr[i][j]);} int main(){ int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; print(arr); return 0;} 1 2 3 4 5 6 7 8 9 References: http://www.eskimo.com/~scs/cclass/int/sx9a.htmlThis article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above BabisSarantoglou abhishek20aeccse C Array and String cpp-array cpp-parameter-passing cpp-pointer C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Different Methods to Reverse a String in C++ std::string class in C++ Unordered Sets in C++ Standard Template Library Enumeration (or enum) in C What is the purpose of a function prototype? C Language Introduction Command line arguments in C/C++ Operators in C / C++
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Jun, 2021" }, { "code": null, "e": 528, "s": 54, "text": "This post is an extension of How to dynamically allocate a 2D array in C? A one dimensional array can be easily passed as a pointer, but syntax for passing a 2D array to a function can be difficult to remember. One important thing for passing multidimensional arrays is, first array dimension does not have to be specified. The second (and any subsequent) dimensions must be given1) When both dimensions are available globally (either as a macro or as a global constant). " }, { "code": null, "e": 530, "s": 528, "text": "C" }, { "code": "#include <stdio.h>const int M = 3;const int N = 3; void print(int arr[M][N]){ int i, j; for (i = 0; i < M; i++) for (j = 0; j < N; j++) printf(\"%d \", arr[i][j]);} int main(){ int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; print(arr); return 0;}", "e": 805, "s": 530, "text": null }, { "code": null, "e": 824, "s": 805, "text": "1 2 3 4 5 6 7 8 9 " }, { "code": null, "e": 923, "s": 824, "text": "2) When only second dimension is available globally (either as a macro or as a global constant). " }, { "code": null, "e": 925, "s": 923, "text": "C" }, { "code": "#include <stdio.h>const int N = 3; void print(int arr[][N], int m){ int i, j; for (i = 0; i < m; i++) for (j = 0; j < N; j++) printf(\"%d \", arr[i][j]);} int main(){ int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; print(arr, 3); return 0;}", "e": 1193, "s": 925, "text": null }, { "code": null, "e": 1212, "s": 1193, "text": "1 2 3 4 5 6 7 8 9 " }, { "code": null, "e": 1541, "s": 1212, "text": "The above method is fine if second dimension is fixed and is not user specified. The following methods handle cases when second dimension can also change.3) If compiler is C99 compatible From C99, C language supports variable sized arrays to be passed simply by specifying the variable dimensions (See this for an example run) " }, { "code": null, "e": 1543, "s": 1541, "text": "C" }, { "code": "// The following program works only if your compiler is C99 compatible.#include <stdio.h> // n must be passed before the 2D arrayvoid print(int m, int n, int arr[][n]){ int i, j; for (i = 0; i < m; i++) for (j = 0; j < n; j++) printf(\"%d \", arr[i][j]);} int main(){ int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int m = 3, n = 3; print(m, n, arr); return 0;}", "e": 1936, "s": 1543, "text": null }, { "code": null, "e": 1955, "s": 1936, "text": "1 2 3 4 5 6 7 8 9 " }, { "code": null, "e": 2169, "s": 1955, "text": "If compiler is not C99 compatible, then we can use one of the following methods to pass a variable sized 2D array.4) Using a single pointer In this method, we must typecast the 2D array when passing to function. " }, { "code": null, "e": 2171, "s": 2169, "text": "C" }, { "code": "#include <stdio.h>void print(int *arr, int m, int n){ int i, j; for (i = 0; i < m; i++) for (j = 0; j < n; j++) printf(\"%d \", *((arr+i*n) + j));} int main(){ int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int m = 3, n = 3; // We can also use \"print(&arr[0][0], m, n);\" print((int *)arr, m, n); return 0;}", "e": 2513, "s": 2171, "text": null }, { "code": null, "e": 2532, "s": 2513, "text": "1 2 3 4 5 6 7 8 9 " }, { "code": null, "e": 2576, "s": 2532, "text": "5) Using the concept of pointer to an array" }, { "code": null, "e": 2578, "s": 2576, "text": "C" }, { "code": "#include <stdio.h>const int M = 3; void print(int (*arr)[M]){ int i, j; for (i = 0; i < M; i++) for (j = 0; j < M; j++) printf(\"%d \", arr[i][j]);} int main(){ int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; print(arr); return 0;}", "e": 2836, "s": 2578, "text": null }, { "code": null, "e": 2855, "s": 2836, "text": "1 2 3 4 5 6 7 8 9 " }, { "code": null, "e": 3083, "s": 2855, "text": "References: http://www.eskimo.com/~scs/cclass/int/sx9a.htmlThis article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 3100, "s": 3083, "text": "BabisSarantoglou" }, { "code": null, "e": 3117, "s": 3100, "text": "abhishek20aeccse" }, { "code": null, "e": 3136, "s": 3117, "text": "C Array and String" }, { "code": null, "e": 3146, "s": 3136, "text": "cpp-array" }, { "code": null, "e": 3168, "s": 3146, "text": "cpp-parameter-passing" }, { "code": null, "e": 3180, "s": 3168, "text": "cpp-pointer" }, { "code": null, "e": 3191, "s": 3180, "text": "C Language" }, { "code": null, "e": 3289, "s": 3191, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3306, "s": 3289, "text": "Substring in C++" }, { "code": null, "e": 3328, "s": 3306, "text": "Function Pointer in C" }, { "code": null, "e": 3373, "s": 3328, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 3398, "s": 3373, "text": "std::string class in C++" }, { "code": null, "e": 3446, "s": 3398, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 3473, "s": 3446, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 3518, "s": 3473, "text": "What is the purpose of a function prototype?" }, { "code": null, "e": 3542, "s": 3518, "text": "C Language Introduction" }, { "code": null, "e": 3574, "s": 3542, "text": "Command line arguments in C/C++" } ]
Set the limit of text length to N lines using CSS
02 Jan, 2019 It is possible to limit the text length to lines using CSS. This is known as line clamping or multiple line truncating. There can be two possible cases: Truncating text after 1 line: If you need to truncate text after 1 line then the text-overflow property of CSS can be used. It creates ellipses and gracefully cut off words.div{ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } The below code demonstrates text-overflow property of CSS:<!DOCTYPE html><html><head> <title></title> <style> .text{ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } </style></head> <body> <div class="text"> Hello GeeksforGeeks. A Computer Science portal for geeks. It contains well written, well thought articles. This is a paragraph containing multiple lines. </div></body></html> div{ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } The below code demonstrates text-overflow property of CSS: <!DOCTYPE html><html><head> <title></title> <style> .text{ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } </style></head> <body> <div class="text"> Hello GeeksforGeeks. A Computer Science portal for geeks. It contains well written, well thought articles. This is a paragraph containing multiple lines. </div></body></html> Truncating text after more than 1 line: If you need to truncate text after more than 1 line then you will have to use WebKit. Webkit is the html/css rendering engine used in Apple’s Safari browser, and in Google’s Chrome.The various problems with using WebKit are:WebKit is supported only in some browsers. It is supported only by Google chrome and Apple’s Safari browser and is not supported by Internet Explorer, Microsoft Edge, Firefox or Opera Mini.It sometimes cuts off the last letters of the word hence it does not break on only spaces.In WebKit there is No Alternate to Ellipsis i.e. you cannot use anything besides ellipses at the end of the truncated line..text{ overflow: hidden; text-overflow: ellipsis; display: -webkit-box; line-height: 16px; max-height: 32px; -webkit-line-clamp: 2; /* Write the number of lines you want to be displayed */ -webkit-box-orient: vertical; } The below code demonstrates truncating of N lines using WebKit:<!DOCTYPE html><html><head> <title></title> <style> .text{ overflow: hidden; text-overflow: ellipsis; display: -webkit-box; line-height: 16px; max-height: 32px; /* The number of lines to be displayed */ -webkit-line-clamp: 2; -webkit-box-orient: vertical; } </style> </head> <body> <div class="text"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div></body></html> The Opera Web Browser has its own way to handle this situation. It applies ellipsis on the line after which the text is truncated..text{ overflow: hidden; white-space: normal; height: 1.2em; /* exactly 2 lines */ text-overflow: -o-ellipsis-lastline; } <!DOCTYPE html><html><head> <title></title> <style> .text{ overflow: hidden; white-space: normal; /* Exactly 2 lines are displayed. Height of 1 line is 1.2em*/ height: 2.4em; text-overflow: -o-ellipsis-lastline; } </style></head> <body> <div class="text"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. t enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div></body></html> The various problems with using WebKit are: WebKit is supported only in some browsers. It is supported only by Google chrome and Apple’s Safari browser and is not supported by Internet Explorer, Microsoft Edge, Firefox or Opera Mini.It sometimes cuts off the last letters of the word hence it does not break on only spaces.In WebKit there is No Alternate to Ellipsis i.e. you cannot use anything besides ellipses at the end of the truncated line. WebKit is supported only in some browsers. It is supported only by Google chrome and Apple’s Safari browser and is not supported by Internet Explorer, Microsoft Edge, Firefox or Opera Mini. It sometimes cuts off the last letters of the word hence it does not break on only spaces. In WebKit there is No Alternate to Ellipsis i.e. you cannot use anything besides ellipses at the end of the truncated line. .text{ overflow: hidden; text-overflow: ellipsis; display: -webkit-box; line-height: 16px; max-height: 32px; -webkit-line-clamp: 2; /* Write the number of lines you want to be displayed */ -webkit-box-orient: vertical; } The below code demonstrates truncating of N lines using WebKit: <!DOCTYPE html><html><head> <title></title> <style> .text{ overflow: hidden; text-overflow: ellipsis; display: -webkit-box; line-height: 16px; max-height: 32px; /* The number of lines to be displayed */ -webkit-line-clamp: 2; -webkit-box-orient: vertical; } </style> </head> <body> <div class="text"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div></body></html> The Opera Web Browser has its own way to handle this situation. It applies ellipsis on the line after which the text is truncated. .text{ overflow: hidden; white-space: normal; height: 1.2em; /* exactly 2 lines */ text-overflow: -o-ellipsis-lastline; } <!DOCTYPE html><html><head> <title></title> <style> .text{ overflow: hidden; white-space: normal; /* Exactly 2 lines are displayed. Height of 1 line is 1.2em*/ height: 2.4em; text-overflow: -o-ellipsis-lastline; } </style></head> <body> <div class="text"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. t enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div></body></html> Picked Technical Scripter 2018 CSS HTML Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS How to set space between the flexbox ? How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Jan, 2019" }, { "code": null, "e": 149, "s": 28, "text": "It is possible to limit the text length to lines using CSS. This is known as line clamping or multiple line truncating." }, { "code": null, "e": 182, "s": 149, "text": "There can be two possible cases:" }, { "code": null, "e": 947, "s": 182, "text": "Truncating text after 1 line: If you need to truncate text after 1 line then the text-overflow property of CSS can be used. It creates ellipses and gracefully cut off words.div{\n white-space: nowrap; \n overflow: hidden;\n text-overflow: ellipsis;\n}\nThe below code demonstrates text-overflow property of CSS:<!DOCTYPE html><html><head> <title></title> <style> .text{ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } </style></head> <body> <div class=\"text\"> Hello GeeksforGeeks. A Computer Science portal for geeks. It contains well written, well thought articles. This is a paragraph containing multiple lines. </div></body></html> " }, { "code": null, "e": 1026, "s": 947, "text": "div{\n white-space: nowrap; \n overflow: hidden;\n text-overflow: ellipsis;\n}\n" }, { "code": null, "e": 1085, "s": 1026, "text": "The below code demonstrates text-overflow property of CSS:" }, { "code": "<!DOCTYPE html><html><head> <title></title> <style> .text{ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } </style></head> <body> <div class=\"text\"> Hello GeeksforGeeks. A Computer Science portal for geeks. It contains well written, well thought articles. This is a paragraph containing multiple lines. </div></body></html> ", "e": 1541, "s": 1085, "text": null }, { "code": null, "e": 5801, "s": 1541, "text": "Truncating text after more than 1 line: If you need to truncate text after more than 1 line then you will have to use WebKit. Webkit is the html/css rendering engine used in Apple’s Safari browser, and in Google’s Chrome.The various problems with using WebKit are:WebKit is supported only in some browsers. It is supported only by Google chrome and Apple’s Safari browser and is not supported by Internet Explorer, Microsoft Edge, Firefox or Opera Mini.It sometimes cuts off the last letters of the word hence it does not break on only spaces.In WebKit there is No Alternate to Ellipsis i.e. you cannot use anything besides ellipses at the end of the truncated line..text{\n overflow: hidden;\n text-overflow: ellipsis;\n display: -webkit-box;\n line-height: 16px; \n max-height: 32px; \n -webkit-line-clamp: 2; /* Write the number of \n lines you want to be \n displayed */\n -webkit-box-orient: vertical;\n}\nThe below code demonstrates truncating of N lines using WebKit:<!DOCTYPE html><html><head> <title></title> <style> .text{ overflow: hidden; text-overflow: ellipsis; display: -webkit-box; line-height: 16px; max-height: 32px; /* The number of lines to be displayed */ -webkit-line-clamp: 2; -webkit-box-orient: vertical; } </style> </head> <body> <div class=\"text\"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div></body></html> The Opera Web Browser has its own way to handle this situation. It applies ellipsis on the line after which the text is truncated..text{\n overflow: hidden;\n white-space: normal;\n height: 1.2em; /* exactly 2 lines */\n text-overflow: -o-ellipsis-lastline;\n}\n<!DOCTYPE html><html><head> <title></title> <style> .text{ overflow: hidden; white-space: normal; /* Exactly 2 lines are displayed. Height of 1 line is 1.2em*/ height: 2.4em; text-overflow: -o-ellipsis-lastline; } </style></head> <body> <div class=\"text\"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. t enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div></body></html> " }, { "code": null, "e": 5845, "s": 5801, "text": "The various problems with using WebKit are:" }, { "code": null, "e": 6248, "s": 5845, "text": "WebKit is supported only in some browsers. It is supported only by Google chrome and Apple’s Safari browser and is not supported by Internet Explorer, Microsoft Edge, Firefox or Opera Mini.It sometimes cuts off the last letters of the word hence it does not break on only spaces.In WebKit there is No Alternate to Ellipsis i.e. you cannot use anything besides ellipses at the end of the truncated line." }, { "code": null, "e": 6438, "s": 6248, "text": "WebKit is supported only in some browsers. It is supported only by Google chrome and Apple’s Safari browser and is not supported by Internet Explorer, Microsoft Edge, Firefox or Opera Mini." }, { "code": null, "e": 6529, "s": 6438, "text": "It sometimes cuts off the last letters of the word hence it does not break on only spaces." }, { "code": null, "e": 6653, "s": 6529, "text": "In WebKit there is No Alternate to Ellipsis i.e. you cannot use anything besides ellipses at the end of the truncated line." }, { "code": null, "e": 6974, "s": 6653, "text": ".text{\n overflow: hidden;\n text-overflow: ellipsis;\n display: -webkit-box;\n line-height: 16px; \n max-height: 32px; \n -webkit-line-clamp: 2; /* Write the number of \n lines you want to be \n displayed */\n -webkit-box-orient: vertical;\n}\n" }, { "code": null, "e": 7038, "s": 6974, "text": "The below code demonstrates truncating of N lines using WebKit:" }, { "code": "<!DOCTYPE html><html><head> <title></title> <style> .text{ overflow: hidden; text-overflow: ellipsis; display: -webkit-box; line-height: 16px; max-height: 32px; /* The number of lines to be displayed */ -webkit-line-clamp: 2; -webkit-box-orient: vertical; } </style> </head> <body> <div class=\"text\"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div></body></html> ", "e": 8552, "s": 7038, "text": null }, { "code": null, "e": 8683, "s": 8552, "text": "The Opera Web Browser has its own way to handle this situation. It applies ellipsis on the line after which the text is truncated." }, { "code": null, "e": 8822, "s": 8683, "text": ".text{\n overflow: hidden;\n white-space: normal;\n height: 1.2em; /* exactly 2 lines */\n text-overflow: -o-ellipsis-lastline;\n}\n" }, { "code": "<!DOCTYPE html><html><head> <title></title> <style> .text{ overflow: hidden; white-space: normal; /* Exactly 2 lines are displayed. Height of 1 line is 1.2em*/ height: 2.4em; text-overflow: -o-ellipsis-lastline; } </style></head> <body> <div class=\"text\"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. t enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div></body></html> ", "e": 10252, "s": 8822, "text": null }, { "code": null, "e": 10259, "s": 10252, "text": "Picked" }, { "code": null, "e": 10283, "s": 10259, "text": "Technical Scripter 2018" }, { "code": null, "e": 10287, "s": 10283, "text": "CSS" }, { "code": null, "e": 10292, "s": 10287, "text": "HTML" }, { "code": null, "e": 10311, "s": 10292, "text": "Technical Scripter" }, { "code": null, "e": 10328, "s": 10311, "text": "Web Technologies" }, { "code": null, "e": 10333, "s": 10328, "text": "HTML" }, { "code": null, "e": 10431, "s": 10333, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10468, "s": 10431, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 10507, "s": 10468, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 10546, "s": 10507, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 10610, "s": 10546, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 10671, "s": 10610, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 10695, "s": 10671, "text": "REST API (Introduction)" }, { "code": null, "e": 10748, "s": 10695, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 10808, "s": 10748, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 10845, "s": 10808, "text": "Types of CSS (Cascading Style Sheet)" } ]
How to Display Changed Browser URL Without Reloading Through alert using JavaScript ?
30 Jan, 2020 To change the URL in the browser without loading the new page, we can use history.pushState() method and replaceState() method from JavaScript. To display the browser-URL before changing the URL we will use window.location.href in the alert() function and will use again after changing the browsers-URL. Note: The history.pushState() method combines HTML 5 History and JavaScript pushState() method. Syntax: alert(" Message:" + window.location.hrf); Below examples illustrate the above approach: Example 1: <!DOCTYPE html><html> <head> <script type="text/javascript"> function geeks() { alert("The current URL of this" + " page is: " + window.location.href); } function change_url() { window.history.pushState("stateObj", "new page", "changedURL.html"); alert("The URL of this page is: " + window.location.href); } </script></head> <body onload="geeks()"> <a href="javascript:change_url()"> Click to change url </a></body> </html> Output: Example 2: <!DOCTYPE html><html> <head> <script type="text/javascript"> function geeks() { alert("The current URL of this " + "page is: " + window.location.href); } function change_url() { window.history.replaceState("stateObj", "new page", "changedURL.html"); alert("The URL of this page is: " + window.location.href); } </script></head> <body onload="geeks()"> <a href="javascript:change_url()"> Click to change url </a></body> </html> Output: JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jan, 2020" }, { "code": null, "e": 332, "s": 28, "text": "To change the URL in the browser without loading the new page, we can use history.pushState() method and replaceState() method from JavaScript. To display the browser-URL before changing the URL we will use window.location.href in the alert() function and will use again after changing the browsers-URL." }, { "code": null, "e": 428, "s": 332, "text": "Note: The history.pushState() method combines HTML 5 History and JavaScript pushState() method." }, { "code": null, "e": 436, "s": 428, "text": "Syntax:" }, { "code": null, "e": 478, "s": 436, "text": "alert(\" Message:\" + window.location.hrf);" }, { "code": null, "e": 524, "s": 478, "text": "Below examples illustrate the above approach:" }, { "code": null, "e": 535, "s": 524, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <script type=\"text/javascript\"> function geeks() { alert(\"The current URL of this\" + \" page is: \" + window.location.href); } function change_url() { window.history.pushState(\"stateObj\", \"new page\", \"changedURL.html\"); alert(\"The URL of this page is: \" + window.location.href); } </script></head> <body onload=\"geeks()\"> <a href=\"javascript:change_url()\"> Click to change url </a></body> </html>", "e": 1104, "s": 535, "text": null }, { "code": null, "e": 1112, "s": 1104, "text": "Output:" }, { "code": null, "e": 1123, "s": 1112, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <script type=\"text/javascript\"> function geeks() { alert(\"The current URL of this \" + \"page is: \" + window.location.href); } function change_url() { window.history.replaceState(\"stateObj\", \"new page\", \"changedURL.html\"); alert(\"The URL of this page is: \" + window.location.href); } </script></head> <body onload=\"geeks()\"> <a href=\"javascript:change_url()\"> Click to change url </a></body> </html>", "e": 1698, "s": 1123, "text": null }, { "code": null, "e": 1706, "s": 1698, "text": "Output:" }, { "code": null, "e": 1722, "s": 1706, "text": "JavaScript-Misc" }, { "code": null, "e": 1729, "s": 1722, "text": "Picked" }, { "code": null, "e": 1740, "s": 1729, "text": "JavaScript" }, { "code": null, "e": 1757, "s": 1740, "text": "Web Technologies" }, { "code": null, "e": 1784, "s": 1757, "text": "Web technologies Questions" } ]
PyQt5 QColorDialog – Changing Font
24 Jun, 2020 In this article we will see how we can change the font of QColorDialog. Font is the style i.e properties of the text present in the color dialog. Note : Increasing size of font will increase the size of the dialog box although dialog size is fixed In order to do this we use setFont method with the QColorDialog object Syntax : dialog.setFont(font) Argument : It takes QFont object as argument Return : It returns None Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom 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, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QColorDialog object dialog = QColorDialog(self) # setting custom colors dialog.setCustomColor(1, Qt.red) dialog.setCustomColor(2, Qt.green) dialog.setCustomColor(3, Qt.yellow) dialog.setCustomColor(4, Qt.blue) # font font = QFont('Times', 12) # setting font to the dialog dialog.setFont(font) # creating label label = QLabel("Geeks for Geeks", self) label.setAlignment(Qt.AlignCenter) # making label multi line label.setWordWrap(True) # setting stylesheet of the label label.setStyleSheet("QLabel" "{" "border : 5px solid black;" "}") # getting the custom color color = dialog.customColor(4) # setting graphic effect to the label graphic = QGraphicsColorizeEffect(self) # setting color to the graphic graphic.setColor(color) # setting graphic to the label label.setGraphicsEffect(graphic) layout = dialog.layout() layout.addWidget(label) dialog.setLayout(layout) dialog.exec_() self.deleteLater() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt-QColorDialog Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jun, 2020" }, { "code": null, "e": 174, "s": 28, "text": "In this article we will see how we can change the font of QColorDialog. Font is the style i.e properties of the text present in the color dialog." }, { "code": null, "e": 276, "s": 174, "text": "Note : Increasing size of font will increase the size of the dialog box although dialog size is fixed" }, { "code": null, "e": 347, "s": 276, "text": "In order to do this we use setFont method with the QColorDialog object" }, { "code": null, "e": 377, "s": 347, "text": "Syntax : dialog.setFont(font)" }, { "code": null, "e": 422, "s": 377, "text": "Argument : It takes QFont object as argument" }, { "code": null, "e": 447, "s": 422, "text": "Return : It returns None" }, { "code": null, "e": 475, "s": 447, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom 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, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QColorDialog object dialog = QColorDialog(self) # setting custom colors dialog.setCustomColor(1, Qt.red) dialog.setCustomColor(2, Qt.green) dialog.setCustomColor(3, Qt.yellow) dialog.setCustomColor(4, Qt.blue) # font font = QFont('Times', 12) # setting font to the dialog dialog.setFont(font) # creating label label = QLabel(\"Geeks for Geeks\", self) label.setAlignment(Qt.AlignCenter) # making label multi line label.setWordWrap(True) # setting stylesheet of the label label.setStyleSheet(\"QLabel\" \"{\" \"border : 5px solid black;\" \"}\") # getting the custom color color = dialog.customColor(4) # setting graphic effect to the label graphic = QGraphicsColorizeEffect(self) # setting color to the graphic graphic.setColor(color) # setting graphic to the label label.setGraphicsEffect(graphic) layout = dialog.layout() layout.addWidget(label) dialog.setLayout(layout) dialog.exec_() self.deleteLater() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 2391, "s": 475, "text": null }, { "code": null, "e": 2400, "s": 2391, "text": "Output :" }, { "code": null, "e": 2425, "s": 2400, "text": "Python PyQt-QColorDialog" }, { "code": null, "e": 2436, "s": 2425, "text": "Python-gui" }, { "code": null, "e": 2448, "s": 2436, "text": "Python-PyQt" }, { "code": null, "e": 2455, "s": 2448, "text": "Python" }, { "code": null, "e": 2553, "s": 2455, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2585, "s": 2553, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2612, "s": 2585, "text": "Python Classes and Objects" }, { "code": null, "e": 2633, "s": 2612, "text": "Python OOPs Concepts" }, { "code": null, "e": 2656, "s": 2633, "text": "Introduction To PYTHON" }, { "code": null, "e": 2712, "s": 2656, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2743, "s": 2712, "text": "Python | os.path.join() method" }, { "code": null, "e": 2785, "s": 2743, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2827, "s": 2785, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2866, "s": 2827, "text": "Python | Get unique values from a list" } ]
Goldman Sachs Internship Interview Experience 2022
28 Dec, 2021 Every year, Goldman Sachs runs its Engineering Campus Hiring Program, an off-campus drive for their Bengaluru office. This year the applications opened from mid-July for about 3 weeks. Here, I am (extensively) sharing my own experience with this program, the entire selection process, Hope this helps! So all this started in July when one of my seniors told us about this Goldman Sachs Engineering campus hiring program and we applied directly through Goldman Sachs careers portal because there is no referral applicable for this program. Aptitude Test: Their first assessment was an Aptitude Test which took place on 23rd August. It was for a duration of 105 minutes with 66 questions divided as follows: Section 1: Numerical Computations (basically maths) — 8 questions Section 2: Numerical Reasoning — 12 questions Section 3: Comprehension — 10 questions Section 4: Abstract Reasoning — 12 questions Section 5: Diagrammatic Reasoning — 12 questions Section 6: Logical Reasoning — 12 questions All these MCQ questions had 5 marks for correct answers and -2 for incorrect. This Aptitude round was the toughest Aptitude test I ever had, and I suggest you to practice previous year GS questions. My seniors had told me to solve at least 40-45 questions to have a chance so I solved 47 questions and was confident that at least 40 of them are correct Technical Test: After a month on 17th September, I received a mail that I have cleared the first round. The next step was the technical assessment scheduled for 24th October. GS provided us with a general syllabus and pattern of the test. It had 5 sections with a total duration of 1 hour 50 minutes. Section 1: 2 programming questions— 30 mins. Both the question was of leetcode easy-medium level and I was able to solve 1 completely and 1 partially due to time constraints Section 2: Problem Solving 10 MCQs — 40 mins. This section was the hardest and had all the questions were of JEE mains-Advance level maths. The topics were probability, Statistics, number theory, set theory, algebra, trigonometry, and logical reasoning. I solved 5 questions from this section Section 3: Computer Science 7 MCQs — 25 mins. This section had questions on CS fundamentals, data structures, algorithms, operating systems (process scheduling), OOPs, and output type questions. Here I solved 4 questions. Section 4: 2 subjective questions — 15 mins. We were given 2 situations based subjective questions and we have to write our answer in 200 words On 3rd December I got to know that many people got the invite for interview scheduled on 7th December, I waited for 3 days but didn’t receive any mail, but finally, on 6th December I received A mail congratulating me that I have made it to the interviews and my interview is scheduled tomorrow from 10 AM to 5 PM, and all 3 round of interview are going to be conducted tomorrow itself. I read all the GS interview experience from GFG and come to know that DP and puzzles are their fav topics, so I revised DP, Tree and Graph from my notes and solved all the puzzles available on GFG. The Interviews My interview was scheduled for 7th December on Zoom. Round 1: My first round took place at around 10 am, Firstly, my interviewer asked me “Tell me something about yourself”. In this round the interviewer asked just theory based question, he first asked me # All the OOPs concepts with real-life examples, #Difference between Tree and Graph, # What is Greedy method? Give 3 examples of the greedy method, # Difference between linear search and binary search, # Which is the best sorting technique, and why?? I answered all this, but at the end, he asked me if I know DBMS, I directly said No, He asked me if I have any question for him, and I asked a couple of questions and with this the interview ended, overall the interview went well and my interviewer was quite impressed and appreciated me. Round 2: After waiting for an hour, I had my second interview. my interviewer was very sweet and friendly, with 13 years of experience in goldman sachs, first, he made me comfortable asked me about my day, how my first round went, here intentionally I told him that “my 1st round of interview was great but he didn’t asked me any coding question ” so that my current interviewer don’t ask me any theoretical question and I can show my strength in CP. He asked me the same interview opener question “Tell me something about yourself”. and then directly jumped onto the coding part he shared a code pair link and asked a medium level array question, I explained him the approach and coded my approach within 5 min then he asked me what will I do if this array was a circular array, I answered that too, and he looked satisfied with my approach, then he asked me some managerial questions like # why Goldman Sachs?? # Mention any point in your life when you felt very low and how you handled that situation. then I asked him 2-3 questions and we had a good healthy conversation for a while, the interviewer was quite impressed and appreciated me for my coding skills. Both of my rounds were over by 12noon and I was eagerly waiting for my 3rd round of interview but I wasn’t called for the third interview and after around 6 hours at 6 PM we were told to leave the meeting and that they are not going to take any more interviews and we will get the results in a few days, later I found out a lot of students had 3 round of interview some had 4 round too. Finally on 16th December I received my selection mail Goldman Sachs Marketing Off-Campus Internship Interview Experiences Goldman Sachs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Microsoft Interview Experience for SWE Intern Samsung R&D Bangalore (SRIB) Interview Experience | On- Campus for Internship 2021 Zoho Interview Experience (Off-Campus ) 2022 Google STEP Interview Experience Internship 2022 Microsoft Interview Experience for SWE Intern (On-Campus) Amazon Interview Questions TCS Digital Interview Questions Google SWE Interview Experience (Google Online Coding Challenge) 2022 Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022 Amazon Interview Experience for SDE 1
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Dec, 2021" }, { "code": null, "e": 237, "s": 52, "text": "Every year, Goldman Sachs runs its Engineering Campus Hiring Program, an off-campus drive for their Bengaluru office. This year the applications opened from mid-July for about 3 weeks." }, { "code": null, "e": 337, "s": 237, "text": "Here, I am (extensively) sharing my own experience with this program, the entire selection process," }, { "code": null, "e": 354, "s": 337, "text": "Hope this helps!" }, { "code": null, "e": 591, "s": 354, "text": "So all this started in July when one of my seniors told us about this Goldman Sachs Engineering campus hiring program and we applied directly through Goldman Sachs careers portal because there is no referral applicable for this program." }, { "code": null, "e": 758, "s": 591, "text": "Aptitude Test: Their first assessment was an Aptitude Test which took place on 23rd August. It was for a duration of 105 minutes with 66 questions divided as follows:" }, { "code": null, "e": 824, "s": 758, "text": "Section 1: Numerical Computations (basically maths) — 8 questions" }, { "code": null, "e": 871, "s": 824, "text": "Section 2: Numerical Reasoning — 12 questions " }, { "code": null, "e": 911, "s": 871, "text": "Section 3: Comprehension — 10 questions" }, { "code": null, "e": 956, "s": 911, "text": "Section 4: Abstract Reasoning — 12 questions" }, { "code": null, "e": 1005, "s": 956, "text": "Section 5: Diagrammatic Reasoning — 12 questions" }, { "code": null, "e": 1049, "s": 1005, "text": "Section 6: Logical Reasoning — 12 questions" }, { "code": null, "e": 1127, "s": 1049, "text": "All these MCQ questions had 5 marks for correct answers and -2 for incorrect." }, { "code": null, "e": 1402, "s": 1127, "text": "This Aptitude round was the toughest Aptitude test I ever had, and I suggest you to practice previous year GS questions. My seniors had told me to solve at least 40-45 questions to have a chance so I solved 47 questions and was confident that at least 40 of them are correct" }, { "code": null, "e": 1642, "s": 1402, "text": "Technical Test: After a month on 17th September, I received a mail that I have cleared the first round. The next step was the technical assessment scheduled for 24th October. GS provided us with a general syllabus and pattern of the test. " }, { "code": null, "e": 1704, "s": 1642, "text": "It had 5 sections with a total duration of 1 hour 50 minutes." }, { "code": null, "e": 1749, "s": 1704, "text": "Section 1: 2 programming questions— 30 mins." }, { "code": null, "e": 1878, "s": 1749, "text": "Both the question was of leetcode easy-medium level and I was able to solve 1 completely and 1 partially due to time constraints" }, { "code": null, "e": 1924, "s": 1878, "text": "Section 2: Problem Solving 10 MCQs — 40 mins." }, { "code": null, "e": 2019, "s": 1924, "text": "This section was the hardest and had all the questions were of JEE mains-Advance level maths. " }, { "code": null, "e": 2172, "s": 2019, "text": "The topics were probability, Statistics, number theory, set theory, algebra, trigonometry, and logical reasoning. I solved 5 questions from this section" }, { "code": null, "e": 2218, "s": 2172, "text": "Section 3: Computer Science 7 MCQs — 25 mins." }, { "code": null, "e": 2394, "s": 2218, "text": "This section had questions on CS fundamentals, data structures, algorithms, operating systems (process scheduling), OOPs, and output type questions. Here I solved 4 questions." }, { "code": null, "e": 2439, "s": 2394, "text": "Section 4: 2 subjective questions — 15 mins." }, { "code": null, "e": 2540, "s": 2439, "text": "We were given 2 situations based subjective questions and we have to write our answer in 200 words " }, { "code": null, "e": 2926, "s": 2540, "text": "On 3rd December I got to know that many people got the invite for interview scheduled on 7th December, I waited for 3 days but didn’t receive any mail, but finally, on 6th December I received A mail congratulating me that I have made it to the interviews and my interview is scheduled tomorrow from 10 AM to 5 PM, and all 3 round of interview are going to be conducted tomorrow itself." }, { "code": null, "e": 3124, "s": 2926, "text": "I read all the GS interview experience from GFG and come to know that DP and puzzles are their fav topics, so I revised DP, Tree and Graph from my notes and solved all the puzzles available on GFG." }, { "code": null, "e": 3139, "s": 3124, "text": "The Interviews" }, { "code": null, "e": 3192, "s": 3139, "text": "My interview was scheduled for 7th December on Zoom." }, { "code": null, "e": 3201, "s": 3192, "text": "Round 1:" }, { "code": null, "e": 3245, "s": 3201, "text": "My first round took place at around 10 am, " }, { "code": null, "e": 3314, "s": 3245, "text": "Firstly, my interviewer asked me “Tell me something about yourself”." }, { "code": null, "e": 3397, "s": 3314, "text": "In this round the interviewer asked just theory based question, he first asked me " }, { "code": null, "e": 3648, "s": 3397, "text": "# All the OOPs concepts with real-life examples, #Difference between Tree and Graph, # What is Greedy method? Give 3 examples of the greedy method, # Difference between linear search and binary search, # Which is the best sorting technique, and why??" }, { "code": null, "e": 3937, "s": 3648, "text": "I answered all this, but at the end, he asked me if I know DBMS, I directly said No, He asked me if I have any question for him, and I asked a couple of questions and with this the interview ended, overall the interview went well and my interviewer was quite impressed and appreciated me." }, { "code": null, "e": 3946, "s": 3937, "text": "Round 2:" }, { "code": null, "e": 4000, "s": 3946, "text": "After waiting for an hour, I had my second interview." }, { "code": null, "e": 4388, "s": 4000, "text": "my interviewer was very sweet and friendly, with 13 years of experience in goldman sachs, first, he made me comfortable asked me about my day, how my first round went, here intentionally I told him that “my 1st round of interview was great but he didn’t asked me any coding question ” so that my current interviewer don’t ask me any theoretical question and I can show my strength in CP." }, { "code": null, "e": 4829, "s": 4388, "text": "He asked me the same interview opener question “Tell me something about yourself”. and then directly jumped onto the coding part he shared a code pair link and asked a medium level array question, I explained him the approach and coded my approach within 5 min then he asked me what will I do if this array was a circular array, I answered that too, and he looked satisfied with my approach, then he asked me some managerial questions like " }, { "code": null, "e": 4851, "s": 4829, "text": "# why Goldman Sachs??" }, { "code": null, "e": 4943, "s": 4851, "text": "# Mention any point in your life when you felt very low and how you handled that situation." }, { "code": null, "e": 5103, "s": 4943, "text": "then I asked him 2-3 questions and we had a good healthy conversation for a while, the interviewer was quite impressed and appreciated me for my coding skills." }, { "code": null, "e": 5490, "s": 5103, "text": "Both of my rounds were over by 12noon and I was eagerly waiting for my 3rd round of interview but I wasn’t called for the third interview and after around 6 hours at 6 PM we were told to leave the meeting and that they are not going to take any more interviews and we will get the results in a few days, later I found out a lot of students had 3 round of interview some had 4 round too." }, { "code": null, "e": 5544, "s": 5490, "text": "Finally on 16th December I received my selection mail" }, { "code": null, "e": 5558, "s": 5544, "text": "Goldman Sachs" }, { "code": null, "e": 5568, "s": 5558, "text": "Marketing" }, { "code": null, "e": 5579, "s": 5568, "text": "Off-Campus" }, { "code": null, "e": 5590, "s": 5579, "text": "Internship" }, { "code": null, "e": 5612, "s": 5590, "text": "Interview Experiences" }, { "code": null, "e": 5626, "s": 5612, "text": "Goldman Sachs" }, { "code": null, "e": 5724, "s": 5626, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5770, "s": 5724, "text": "Microsoft Interview Experience for SWE Intern" }, { "code": null, "e": 5853, "s": 5770, "text": "Samsung R&D Bangalore (SRIB) Interview Experience | On- Campus for Internship 2021" }, { "code": null, "e": 5898, "s": 5853, "text": "Zoho Interview Experience (Off-Campus ) 2022" }, { "code": null, "e": 5947, "s": 5898, "text": "Google STEP Interview Experience Internship 2022" }, { "code": null, "e": 6005, "s": 5947, "text": "Microsoft Interview Experience for SWE Intern (On-Campus)" }, { "code": null, "e": 6032, "s": 6005, "text": "Amazon Interview Questions" }, { "code": null, "e": 6064, "s": 6032, "text": "TCS Digital Interview Questions" }, { "code": null, "e": 6134, "s": 6064, "text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022" }, { "code": null, "e": 6207, "s": 6134, "text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022" } ]
Python OpenCV: Meanshift
07 Aug, 2021 OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. The idea behind meanshift is that in meanshift algorithm every instance of the video is checked in the form of pixel distribution in that frame. We define an initial window, generally a square or a circle for which the positions are specified by ourself which identifies the area of maximum pixel distribution and tries to keep track of that area in the video so that when the video is running our tracking window also moves towards the region of maximum pixel distribution. The direction of movement depends upon the difference between the center of our tracking window and the centroid of all the k-pixels inside that window.Meanshift is a very useful method to keep track of a particular object inside a video. Meanshift can separate the static background of a video and the moving foreground object. Examples: 1. The tracking windows is tracking the football. 2. The tracking window is tracking the juggling ball. 3. The tracking window is tracking the football player. Python3 # Python program to demonstrate# meanshift import numpy as npimport cv2 # read videocap = cv2.VideoCapture('sample.mp4') # retrieve the very first# frame from the video_, frame = cap.read() # set the region for the# tracking window p, q, r, s# put values according to yourselfp, q, r, s = 150, 150, 460, 100track_window = (r, p, s, q) # create the region of interestr_o_i = frame[p:p + q, r:r + s] # converting BGR to HSV formathsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # apply mask on the HSV framemask = cv2.inRange(hsv, np.array((0., 61., 33.)), np.array((180., 255., 255.))) # get histogram for hsv channelroi = cv2.calcHist([hsv], [0], mask, [180], [0, 180]) # normalize the retrieved valuescv2.normalize(roi, roi, 0, 255, cv2.NORM_MINMAX) # termination criteria, either 15# iteration or by at least 2 pttermination = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT , 15, 2 ) while(True): _, frame = cap.read() frame = cv2.resize(frame, (1280, 720), fx = 0, fy = 0, interpolation = cv2.INTER_CUBIC) # convert BGR to HSV format hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) bp = cv2.calcBackProject([hsv], [0], roi, [0, 180], 1) # applying meanshift to get the new region _, track_window = cv2.meanShift(bp, track_window, termination) # Draw track window on the frame x, y, w, h = track_window vid = cv2.rectangle(frame, (x, y), (x + w, y + h), 255, 2) # show results cv2.imshow('tracker', vid) k = cv2.waitKey(1) & 0xff if k == ord('q'): break # release cap objectcap.release() # destroy all opened windowscv2.destroyAllWindows() Output: Some frames from the output video There are 2 main disadvantages of using the Meanshift for object tracking. The size of the tracking window remains the same irrespective of the distance of the object from the camera. The Window will track the object only when it is in the region of that object. So we must hardcode our position of the window carefully. Akanksha_Rai kk9826225 Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Aug, 2021" }, { "code": null, "e": 336, "s": 28, "text": "OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. " }, { "code": null, "e": 1140, "s": 336, "text": "The idea behind meanshift is that in meanshift algorithm every instance of the video is checked in the form of pixel distribution in that frame. We define an initial window, generally a square or a circle for which the positions are specified by ourself which identifies the area of maximum pixel distribution and tries to keep track of that area in the video so that when the video is running our tracking window also moves towards the region of maximum pixel distribution. The direction of movement depends upon the difference between the center of our tracking window and the centroid of all the k-pixels inside that window.Meanshift is a very useful method to keep track of a particular object inside a video. Meanshift can separate the static background of a video and the moving foreground object." }, { "code": null, "e": 1151, "s": 1140, "text": "Examples: " }, { "code": null, "e": 1203, "s": 1151, "text": "1. The tracking windows is tracking the football. " }, { "code": null, "e": 1258, "s": 1203, "text": "2. The tracking window is tracking the juggling ball. " }, { "code": null, "e": 1315, "s": 1258, "text": "3. The tracking window is tracking the football player. " }, { "code": null, "e": 1323, "s": 1315, "text": "Python3" }, { "code": "# Python program to demonstrate# meanshift import numpy as npimport cv2 # read videocap = cv2.VideoCapture('sample.mp4') # retrieve the very first# frame from the video_, frame = cap.read() # set the region for the# tracking window p, q, r, s# put values according to yourselfp, q, r, s = 150, 150, 460, 100track_window = (r, p, s, q) # create the region of interestr_o_i = frame[p:p + q, r:r + s] # converting BGR to HSV formathsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # apply mask on the HSV framemask = cv2.inRange(hsv, np.array((0., 61., 33.)), np.array((180., 255., 255.))) # get histogram for hsv channelroi = cv2.calcHist([hsv], [0], mask, [180], [0, 180]) # normalize the retrieved valuescv2.normalize(roi, roi, 0, 255, cv2.NORM_MINMAX) # termination criteria, either 15# iteration or by at least 2 pttermination = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT , 15, 2 ) while(True): _, frame = cap.read() frame = cv2.resize(frame, (1280, 720), fx = 0, fy = 0, interpolation = cv2.INTER_CUBIC) # convert BGR to HSV format hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) bp = cv2.calcBackProject([hsv], [0], roi, [0, 180], 1) # applying meanshift to get the new region _, track_window = cv2.meanShift(bp, track_window, termination) # Draw track window on the frame x, y, w, h = track_window vid = cv2.rectangle(frame, (x, y), (x + w, y + h), 255, 2) # show results cv2.imshow('tracker', vid) k = cv2.waitKey(1) & 0xff if k == ord('q'): break # release cap objectcap.release() # destroy all opened windowscv2.destroyAllWindows()", "e": 3385, "s": 1323, "text": null }, { "code": null, "e": 3427, "s": 3385, "text": "Output: Some frames from the output video" }, { "code": null, "e": 3504, "s": 3427, "text": "There are 2 main disadvantages of using the Meanshift for object tracking. " }, { "code": null, "e": 3613, "s": 3504, "text": "The size of the tracking window remains the same irrespective of the distance of the object from the camera." }, { "code": null, "e": 3751, "s": 3613, "text": "The Window will track the object only when it is in the region of that object. So we must hardcode our position of the window carefully. " }, { "code": null, "e": 3764, "s": 3751, "text": "Akanksha_Rai" }, { "code": null, "e": 3774, "s": 3764, "text": "kk9826225" }, { "code": null, "e": 3788, "s": 3774, "text": "Python-OpenCV" }, { "code": null, "e": 3795, "s": 3788, "text": "Python" }, { "code": null, "e": 3893, "s": 3795, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3925, "s": 3893, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3952, "s": 3925, "text": "Python Classes and Objects" }, { "code": null, "e": 3983, "s": 3952, "text": "Python | os.path.join() method" }, { "code": null, "e": 4006, "s": 3983, "text": "Introduction To PYTHON" }, { "code": null, "e": 4027, "s": 4006, "text": "Python OOPs Concepts" }, { "code": null, "e": 4083, "s": 4027, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4125, "s": 4083, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4167, "s": 4125, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4206, "s": 4167, "text": "Python | Get unique values from a list" } ]
How to Create a COVID-19 Tracker Android App to See Details of any City and State in India?
21 Jun, 2022 In the previous article, we have discussed How to create a COVID-19 Tracker Android App which shows only the Global Stats. In this article, we will learn how to create a COVID-19 Tracker Android App which will show the details of any city in any State in India. Details like – Total Active cases, Cured Cases, Deaths, and the total number of confirmed cases of any respective city. Here in this App, let’s track demo of 5 cities and one can change according to his/her needs. To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Go to app -> res -> values -> colors.xml section and set the colors for the app. These Colors are Used In the apps In various Places. <?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#024265</color> <color name="colorPrimaryDark">#024265</color> <color name="colorAccent">#05af9b</color> <color name="color_one">#fb7268</color> <color name="color_white">#ededf2</color> <color name="color_two">#E3E0E0</color> <color name="cases">#FFA726</color> <color name="recovered">#66BB6A</color> <color name="deaths">#EF5350</color> <color name="active">#29B6F6</color> </resources> Go to Gradle Scripts -> build.gradle (Module: app) section and import the following dependencies and click the “Sync Now” button to Sync the APP. To Learn More About Volley Library Click Here. implementation ‘com.android.volley:volley:1.1.1’ Now Go to the app -> manifests -> AndroidManifests.xml section and allow “Internet Permission” because this App will use Internet Permission. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.statewise"> <uses-permission android:name="android.permission.INTERNET"/> <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> Click on this URL- https://api.covid19india.org/state_district_wise.json It will Show Data of the whole Country and in this, We Are Going to fetch data from here Only. Go to app -> res -> layout -> activity_main.xmlAdd A TextView To the layout: To display GEEKSFORGEEKS at the top of the screen.Add A ListView To the Layout: To display the list of cities tracking details on the screen. Go to app -> res -> layout -> activity_main.xml Add A TextView To the layout: To display GEEKSFORGEEKS at the top of the screen. Add A ListView To the Layout: To display the list of cities tracking details on the screen. <?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"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="17dp" android:text="GEEKSFORGEEKS" android:textColor="@color/recovered" android:textSize="24sp" /> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="550dp" android:layout_alignParentTop="true" android:layout_alignParentBottom="true" android:layout_marginStart="10dp" android:layout_marginTop="60dp" android:layout_marginEnd="10dp" android:layout_marginBottom="10dp" /> </RelativeLayout> Output UI: Create A new Layout by right click on the layout folder inside res FolderThen Click Layout Resource File and Set the name testing.xmlClick Finish To saveClick testing.xml and Start Design UI Layout for the ListViewThe Drawable file used in testing.xml is “arrow upward“. Go to drawable -> New -> Vector Asset and search for “arrow upward” and add it to your file. Create A new Layout by right click on the layout folder inside res Folder Then Click Layout Resource File and Set the name testing.xml Click Finish To save Click testing.xml and Start Design UI Layout for the ListView The Drawable file used in testing.xml is “arrow upward“. Go to drawable -> New -> Vector Asset and search for “arrow upward” and add it to your file. <?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" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:background="@color/color_white" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:orientation="horizontal" android:weightSum="2"> <LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="center_vertical" android:layout_weight="1" android:orientation="vertical"> <!--Text view to display City name--> <TextView android:id="@+id/state" android:layout_width="210dp" android:layout_height="match_parent" android:gravity="center_vertical" android:text="City Name" android:textColor="@color/colorAccent" android:textSize="14sp" android:textStyle="bold" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <!--Text view to display Active Cases--> <TextView android:layout_width="107dp" android:layout_height="match_parent" android:gravity="center_horizontal" android:text="Active- " android:textStyle="bold" /> <!--Text view to display Active Cases in Numbers--> <TextView android:id="@+id/active" android:layout_width="72dp" android:layout_height="wrap_content" android:text="2323223 " android:textColor="@color/active" android:textStyle="bold" /> <!--Image view to display increase in Cases --> <ImageView android:layout_width="17dp" android:layout_height="match_parent" android:src="@drawable/change" /> <!--Text view to display Todays Active Cases in Numbers--> <TextView android:id="@+id/incactive" android:layout_width="wrap_content" android:layout_height="match_parent" android:gravity="center_horizontal" android:text="32" android:textColor="@color/active" android:textStyle="bold" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <!--Text view to display Cured Cases --> <TextView android:layout_width="107dp" android:layout_height="match_parent" android:gravity="center_horizontal" android:text="Cured- " android:textStyle="bold" /> <!--Text view to display Total Cured Cases in Numbers --> <TextView android:id="@+id/cured" android:layout_width="72dp" android:layout_height="wrap_content" android:text="2323223 " android:textColor="@color/recovered" android:textStyle="bold" /> <!--Image view to display increase in Cases --> <ImageView android:layout_width="18dp" android:layout_height="match_parent" android:src="@drawable/change" /> <!--Text view to display Todays Cured Cases in Numbers --> <TextView android:id="@+id/incurred" android:layout_width="wrap_content" android:layout_height="match_parent" android:gravity="center_horizontal" android:text="32" android:textColor="@color/recovered" android:textStyle="bold" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <!--Text view to display deths Cases --> <TextView android:layout_width="107dp" android:layout_height="match_parent" android:gravity="center_horizontal" android:text="death- " android:textStyle="bold" /> <!--Text view to display total death Cases in Numbers --> <TextView android:id="@+id/death" android:layout_width="72dp" android:layout_height="wrap_content" android:text="2323223 " android:textColor="@color/deaths" android:textStyle="bold" /> <!--Image view to display increase in Cases --> <ImageView android:layout_width="18dp" android:layout_height="match_parent" android:src="@drawable/change" /> <!--Text view to display todays death Cases in Numbers --> <TextView android:id="@+id/incdeath" android:layout_width="wrap_content" android:layout_height="match_parent" android:gravity="center" android:text="32" android:textColor="@color/deaths" android:textStyle="bold" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <!--Text view to display total Number of cases Cases --> <TextView android:layout_width="107dp" android:layout_height="match_parent" android:gravity="center_horizontal" android:text="total- " android:textStyle="bold" /> <!--Text view to display total Number of cases Cases in Numbers --> <TextView android:id="@+id/total" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="2323223 " android:textStyle="bold" /> </LinearLayout> </LinearLayout> </LinearLayout> </LinearLayout> <View android:layout_width="391dp" android:layout_height="6dp" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_alignParentEnd="true" android:layout_marginStart="11dp" android:layout_marginLeft="20dp" android:layout_marginTop="113dp" android:layout_marginEnd="10dp" android:layout_marginRight="20dp" android:background="@color/color_two" /> </RelativeLayout> Output UI: Create a new JAVA class name it as Model.javaUse getters and setters functions to create a function for the data you want to fetch from the website. Create a new JAVA class name it as Model.java Use getters and setters functions to create a function for the data you want to fetch from the website. public class Model { private String name, total, death, cured, active, incAct, incDec, incRec; public Model(String name, String total, String death, String cured, String active, String incAct, String incDec, String incRec) { this.name = name; this.total = total; this.death = death; this.cured = cured; this.active = active; this.incAct = incAct; this.incDec = incDec; this.incRec = incRec; } public String getIncAct() { return incAct; } public void setIncAct(String incAct) { this.incAct = incAct; } public String getIncDec() { return incDec; } public void setIncDec(String incDec) { this.incDec = incDec; } public String getIncRec() { return incRec; } public void setIncRec(String incRec) { this.incRec = incRec; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTotal() { return total; } public void setTotal(String total) { this.total = total; } public String getDeath() { return death; } public void setDeath(String death) { this.death = death; } public String getCured() { return cured; } public void setCured(String cured) { this.cured = cured; } public String getActive() { return active; } public void setActive(String active) { this.active = active; } } Now create a new JAVA Adapter Class to put the data that have fetched into a ListView that has created before. Java import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import java.util.List; // Create A Class Adapterpublic class Adapter extends ArrayAdapter<Model> { private Context context; private List<Model> modelList; public Adapter(Context context, List<Model> modelList) { super(context, R.layout.testing, modelList); this.context = context; this.modelList = modelList; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.testing, null,true); // In this step we connect the XML with Java File TextView state = view.findViewById(R.id.state); TextView active = view.findViewById(R.id.active); TextView cured = view.findViewById(R.id.cured); TextView death = view.findViewById(R.id.death); TextView total = view.findViewById(R.id.total); TextView incactive = view.findViewById(R.id.incactive); TextView incurred = view.findViewById(R.id.incurred); TextView incdeath = view.findViewById(R.id.incdeath); // Adding Data to modellist state.setText(modelList.get(position).getName()); active.setText(modelList.get(position).getActive()); cured.setText(modelList.get(position).getCured()); death.setText(modelList.get(position).getDeath()); total.setText(modelList.get(position).getTotal()); incactive.setText(modelList.get(position).getIncAct()); incurred.setText(modelList.get(position).getIncRec()); incdeath.setText(modelList.get(position).getIncDec()); return view; }} In this file, we are going to use the Volley library. Refer to the comments inside the code to understand the code. import android.os.Bundle; import android.widget.ListView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { ListView listView; public static List<Model> modelList = new ArrayList<>(); Model model; Adapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = findViewById(R.id.listView); fetchData(); } private void fetchData() { // The Link Through Which We Can Fetch Data String url = "https://api.covid19india.org/state_district_wise.json"; StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { try { // Creating JSON Object JSONObject object = new JSONObject(response); // From that object we are fetching data JSONObject object1 = object.getJSONObject("Uttar Pradesh"); JSONObject object2 = object1.getJSONObject("districtData"); JSONObject object3 = object2.getJSONObject("Prayagraj"); JSONObject object4 = object3.getJSONObject("delta"); String active = object3.getString("active"); String confirmed = object3.getString("confirmed"); String deceased = object3.getString("deceased"); String recovered = object3.getString("recovered"); String confInc = object4.getString("confirmed"); String confDec = object4.getString("deceased"); String confRec = object4.getString("recovered"); model = new Model("Prayagraj", confirmed, deceased, recovered, active, confInc, confDec, confRec); // placing data into the app using AdapterClass modelList.add(model); // Creating JSON Object object3 = object2.getJSONObject("Ballia"); // From that object we are fetching data active = object3.getString("active"); confirmed = object3.getString("confirmed"); deceased = object3.getString("deceased"); recovered = object3.getString("recovered"); object4 = object3.getJSONObject("delta"); confInc = object4.getString("confirmed"); confDec = object4.getString("deceased"); confRec = object4.getString("recovered"); model = new Model("Ballia", confirmed, deceased, recovered, active, confInc, confDec, confRec); // placing data into the app using AdapterClass modelList.add(model); // Creating JSON Object object3 = object2.getJSONObject("Lucknow"); // From that object we are fetching data active = object3.getString("active"); confirmed = object3.getString("confirmed"); deceased = object3.getString("deceased"); recovered = object3.getString("recovered"); object4 = object3.getJSONObject("delta"); confInc = object4.getString("confirmed"); confDec = object4.getString("deceased"); confRec = object4.getString("recovered"); model = new Model("Lucknow", confirmed, deceased, recovered, active, confInc, confDec, confRec); // placing data into the app using AdapterClass modelList.add(model); // Creating JSON Object object3 = object2.getJSONObject("Varanasi"); // From that object we are fetching data active = object3.getString("active"); confirmed = object3.getString("confirmed"); deceased = object3.getString("deceased"); recovered = object3.getString("recovered"); object4 = object3.getJSONObject("delta"); confInc = object4.getString("confirmed"); confDec = object4.getString("deceased"); confRec = object4.getString("recovered"); model = new Model("Varanasi", confirmed, deceased, recovered, active, confInc, confDec, confRec); // placing data into the app using AdapterClass modelList.add(model); // Creating JSON Object object3 = object2.getJSONObject("Agra"); // From that object we are fetching data active = object3.getString("active"); confirmed = object3.getString("confirmed"); deceased = object3.getString("deceased"); recovered = object3.getString("recovered"); object4 = object3.getJSONObject("delta"); confInc = object4.getString("confirmed"); confDec = object4.getString("deceased"); confRec = object4.getString("recovered"); model = new Model("Agra", confirmed, deceased, recovered, active, confInc, confDec, confRec); // placing data into the app using AdapterClass modelList.add(model); adapter = new Adapter(MainActivity.this, modelList); listView.setAdapter(adapter); // In case of error it will run } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // In case of error it will run Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show(); } }); RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(request); } } rkbhola5 android Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2022" }, { "code": null, "e": 528, "s": 52, "text": "In the previous article, we have discussed How to create a COVID-19 Tracker Android App which shows only the Global Stats. In this article, we will learn how to create a COVID-19 Tracker Android App which will show the details of any city in any State in India. Details like – Total Active cases, Cured Cases, Deaths, and the total number of confirmed cases of any respective city. Here in this App, let’s track demo of 5 cities and one can change according to his/her needs." }, { "code": null, "e": 690, "s": 528, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 771, "s": 690, "text": "Go to app -> res -> values -> colors.xml section and set the colors for the app." }, { "code": null, "e": 824, "s": 771, "text": "These Colors are Used In the apps In various Places." }, { "code": null, "e": 1334, "s": 824, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <color name=\"colorPrimary\">#024265</color>\n <color name=\"colorPrimaryDark\">#024265</color>\n <color name=\"colorAccent\">#05af9b</color>\n\n <color name=\"color_one\">#fb7268</color>\n <color name=\"color_white\">#ededf2</color>\n <color name=\"color_two\">#E3E0E0</color>\n\n <color name=\"cases\">#FFA726</color>\n <color name=\"recovered\">#66BB6A</color>\n <color name=\"deaths\">#EF5350</color>\n <color name=\"active\">#29B6F6</color>\n</resources>" }, { "code": null, "e": 1480, "s": 1334, "text": "Go to Gradle Scripts -> build.gradle (Module: app) section and import the following dependencies and click the “Sync Now” button to Sync the APP." }, { "code": null, "e": 1527, "s": 1480, "text": "To Learn More About Volley Library Click Here." }, { "code": null, "e": 1576, "s": 1527, "text": "implementation ‘com.android.volley:volley:1.1.1’" }, { "code": null, "e": 1718, "s": 1576, "text": "Now Go to the app -> manifests -> AndroidManifests.xml section and allow “Internet Permission” because this App will use Internet Permission." }, { "code": null, "e": 2500, "s": 1718, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.statewise\">\n <uses-permission android:name=\"android.permission.INTERNET\"/>\n\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\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n\n</manifest>" }, { "code": null, "e": 2573, "s": 2500, "text": "Click on this URL- https://api.covid19india.org/state_district_wise.json" }, { "code": null, "e": 2668, "s": 2573, "text": "It will Show Data of the whole Country and in this, We Are Going to fetch data from here Only." }, { "code": null, "e": 2887, "s": 2668, "text": "Go to app -> res -> layout -> activity_main.xmlAdd A TextView To the layout: To display GEEKSFORGEEKS at the top of the screen.Add A ListView To the Layout: To display the list of cities tracking details on the screen." }, { "code": null, "e": 2935, "s": 2887, "text": "Go to app -> res -> layout -> activity_main.xml" }, { "code": null, "e": 3016, "s": 2935, "text": "Add A TextView To the layout: To display GEEKSFORGEEKS at the top of the screen." }, { "code": null, "e": 3108, "s": 3016, "text": "Add A ListView To the Layout: To display the list of cities tracking details on the screen." }, { "code": null, "e": 4110, "s": 3108, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"17dp\"\n android:text=\"GEEKSFORGEEKS\"\n android:textColor=\"@color/recovered\"\n android:textSize=\"24sp\" />\n\n <ListView\n android:id=\"@+id/listView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"550dp\"\n android:layout_alignParentTop=\"true\"\n android:layout_alignParentBottom=\"true\"\n android:layout_marginStart=\"10dp\"\n android:layout_marginTop=\"60dp\"\n android:layout_marginEnd=\"10dp\"\n android:layout_marginBottom=\"10dp\" />\n \n</RelativeLayout>" }, { "code": null, "e": 4121, "s": 4110, "text": "Output UI:" }, { "code": null, "e": 4485, "s": 4121, "text": "Create A new Layout by right click on the layout folder inside res FolderThen Click Layout Resource File and Set the name testing.xmlClick Finish To saveClick testing.xml and Start Design UI Layout for the ListViewThe Drawable file used in testing.xml is “arrow upward“. Go to drawable -> New -> Vector Asset and search for “arrow upward” and add it to your file." }, { "code": null, "e": 4559, "s": 4485, "text": "Create A new Layout by right click on the layout folder inside res Folder" }, { "code": null, "e": 4620, "s": 4559, "text": "Then Click Layout Resource File and Set the name testing.xml" }, { "code": null, "e": 4641, "s": 4620, "text": "Click Finish To save" }, { "code": null, "e": 4703, "s": 4641, "text": "Click testing.xml and Start Design UI Layout for the ListView" }, { "code": null, "e": 4853, "s": 4703, "text": "The Drawable file used in testing.xml is “arrow upward“. Go to drawable -> New -> Vector Asset and search for “arrow upward” and add it to your file." }, { "code": null, "e": 13551, "s": 4853, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"10dp\"\n android:background=\"@color/color_white\"\n android:orientation=\"vertical\">\n\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"10dp\"\n android:orientation=\"horizontal\"\n android:weightSum=\"2\">\n\n <LinearLayout\n android:layout_width=\"wrap_content\"\n android:layout_height=\"match_parent\"\n android:layout_gravity=\"center_vertical\"\n android:layout_weight=\"1\"\n android:orientation=\"vertical\">\n\n <!--Text view to display City name-->\n <TextView\n android:id=\"@+id/state\"\n android:layout_width=\"210dp\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center_vertical\"\n android:text=\"City Name\"\n android:textColor=\"@color/colorAccent\"\n android:textSize=\"14sp\"\n android:textStyle=\"bold\" />\n </LinearLayout>\n\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_weight=\"1\"\n android:orientation=\"vertical\">\n\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"horizontal\">\n\n <!--Text view to display Active Cases-->\n <TextView\n android:layout_width=\"107dp\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center_horizontal\"\n android:text=\"Active- \"\n android:textStyle=\"bold\" />\n\n <!--Text view to display Active Cases in Numbers-->\n <TextView\n android:id=\"@+id/active\"\n android:layout_width=\"72dp\"\n android:layout_height=\"wrap_content\"\n android:text=\"2323223 \"\n android:textColor=\"@color/active\"\n android:textStyle=\"bold\" />\n\n <!--Image view to display increase in Cases -->\n <ImageView\n android:layout_width=\"17dp\"\n android:layout_height=\"match_parent\"\n android:src=\"@drawable/change\" />\n\n <!--Text view to display Todays Active Cases in Numbers-->\n <TextView\n android:id=\"@+id/incactive\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center_horizontal\"\n android:text=\"32\"\n android:textColor=\"@color/active\"\n android:textStyle=\"bold\" />\n </LinearLayout>\n\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"horizontal\">\n\n <!--Text view to display Cured Cases -->\n <TextView\n android:layout_width=\"107dp\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center_horizontal\"\n android:text=\"Cured- \"\n android:textStyle=\"bold\" />\n\n <!--Text view to display Total Cured Cases in Numbers -->\n <TextView\n android:id=\"@+id/cured\"\n android:layout_width=\"72dp\"\n android:layout_height=\"wrap_content\"\n android:text=\"2323223 \"\n android:textColor=\"@color/recovered\"\n android:textStyle=\"bold\" />\n\n <!--Image view to display increase in Cases -->\n <ImageView\n android:layout_width=\"18dp\"\n android:layout_height=\"match_parent\"\n android:src=\"@drawable/change\" />\n\n <!--Text view to display Todays Cured Cases in Numbers -->\n <TextView\n android:id=\"@+id/incurred\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center_horizontal\"\n android:text=\"32\"\n android:textColor=\"@color/recovered\"\n android:textStyle=\"bold\" />\n\n </LinearLayout>\n\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"horizontal\">\n\n <!--Text view to display deths Cases -->\n <TextView\n android:layout_width=\"107dp\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center_horizontal\"\n android:text=\"death- \"\n android:textStyle=\"bold\" />\n\n <!--Text view to display total death Cases in Numbers -->\n <TextView\n android:id=\"@+id/death\"\n android:layout_width=\"72dp\"\n android:layout_height=\"wrap_content\"\n android:text=\"2323223 \"\n android:textColor=\"@color/deaths\"\n android:textStyle=\"bold\" />\n\n <!--Image view to display increase in Cases -->\n <ImageView\n android:layout_width=\"18dp\"\n android:layout_height=\"match_parent\"\n android:src=\"@drawable/change\" />\n\n <!--Text view to display todays death Cases in Numbers -->\n <TextView\n android:id=\"@+id/incdeath\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center\"\n android:text=\"32\"\n android:textColor=\"@color/deaths\"\n android:textStyle=\"bold\" />\n\n </LinearLayout>\n\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"horizontal\">\n\n <!--Text view to display total Number of cases Cases -->\n <TextView\n android:layout_width=\"107dp\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center_horizontal\"\n android:text=\"total- \"\n android:textStyle=\"bold\" />\n\n <!--Text view to display total Number of cases Cases in Numbers -->\n <TextView\n android:id=\"@+id/total\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:text=\"2323223 \"\n android:textStyle=\"bold\" />\n\n </LinearLayout>\n\n </LinearLayout>\n\n </LinearLayout>\n\n </LinearLayout>\n\n <View\n android:layout_width=\"391dp\"\n android:layout_height=\"6dp\"\n android:layout_alignParentStart=\"true\"\n android:layout_alignParentTop=\"true\"\n android:layout_alignParentEnd=\"true\"\n android:layout_marginStart=\"11dp\"\n android:layout_marginLeft=\"20dp\"\n android:layout_marginTop=\"113dp\"\n android:layout_marginEnd=\"10dp\"\n android:layout_marginRight=\"20dp\"\n android:background=\"@color/color_two\" />\n\n</RelativeLayout>" }, { "code": null, "e": 13562, "s": 13551, "text": "Output UI:" }, { "code": null, "e": 13711, "s": 13562, "text": "Create a new JAVA class name it as Model.javaUse getters and setters functions to create a function for the data you want to fetch from the website." }, { "code": null, "e": 13757, "s": 13711, "text": "Create a new JAVA class name it as Model.java" }, { "code": null, "e": 13861, "s": 13757, "text": "Use getters and setters functions to create a function for the data you want to fetch from the website." }, { "code": null, "e": 15536, "s": 13861, "text": "public class Model {\n private String name, total, death, cured, active, incAct, incDec, incRec;\n\n public Model(String name, String total, String death, String cured,\n String active, String incAct, String incDec, String incRec)\n {\n this.name = name;\n this.total = total;\n this.death = death;\n this.cured = cured;\n this.active = active;\n this.incAct = incAct;\n this.incDec = incDec;\n this.incRec = incRec;\n }\n\n public String getIncAct() \n {\n return incAct;\n }\n\n public void setIncAct(String incAct) \n {\n this.incAct = incAct;\n }\n\n public String getIncDec() \n {\n return incDec;\n }\n\n public void setIncDec(String incDec) \n {\n this.incDec = incDec;\n }\n\n public String getIncRec() \n {\n return incRec;\n }\n\n public void setIncRec(String incRec)\n {\n this.incRec = incRec;\n }\n\n public String getName() \n {\n return name;\n }\n\n public void setName(String name)\n {\n this.name = name;\n }\n\n public String getTotal() \n {\n return total;\n }\n\n public void setTotal(String total)\n {\n this.total = total;\n }\n\n public String getDeath() \n {\n return death;\n }\n\n public void setDeath(String death) \n {\n this.death = death;\n }\n\n public String getCured() \n {\n return cured;\n }\n\n public void setCured(String cured)\n {\n this.cured = cured;\n }\n\n public String getActive()\n {\n return active;\n }\n\n public void setActive(String active)\n {\n this.active = active;\n }\n}\n\n" }, { "code": null, "e": 15647, "s": 15536, "text": "Now create a new JAVA Adapter Class to put the data that have fetched into a ListView that has created before." }, { "code": null, "e": 15652, "s": 15647, "text": "Java" }, { "code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import java.util.List; // Create A Class Adapterpublic class Adapter extends ArrayAdapter<Model> { private Context context; private List<Model> modelList; public Adapter(Context context, List<Model> modelList) { super(context, R.layout.testing, modelList); this.context = context; this.modelList = modelList; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.testing, null,true); // In this step we connect the XML with Java File TextView state = view.findViewById(R.id.state); TextView active = view.findViewById(R.id.active); TextView cured = view.findViewById(R.id.cured); TextView death = view.findViewById(R.id.death); TextView total = view.findViewById(R.id.total); TextView incactive = view.findViewById(R.id.incactive); TextView incurred = view.findViewById(R.id.incurred); TextView incdeath = view.findViewById(R.id.incdeath); // Adding Data to modellist state.setText(modelList.get(position).getName()); active.setText(modelList.get(position).getActive()); cured.setText(modelList.get(position).getCured()); death.setText(modelList.get(position).getDeath()); total.setText(modelList.get(position).getTotal()); incactive.setText(modelList.get(position).getIncAct()); incurred.setText(modelList.get(position).getIncRec()); incdeath.setText(modelList.get(position).getIncDec()); return view; }}", "e": 17548, "s": 15652, "text": null }, { "code": null, "e": 17664, "s": 17548, "text": "In this file, we are going to use the Volley library. Refer to the comments inside the code to understand the code." }, { "code": null, "e": 24753, "s": 17664, "text": "import android.os.Bundle;\nimport android.widget.ListView;\nimport android.widget.Toast;\nimport androidx.appcompat.app.AppCompatActivity;\nimport com.android.volley.Request;\nimport com.android.volley.RequestQueue;\nimport com.android.volley.Response;\nimport com.android.volley.VolleyError;\nimport com.android.volley.toolbox.StringRequest;\nimport com.android.volley.toolbox.Volley;\nimport org.json.JSONException;\nimport org.json.JSONObject;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MainActivity extends AppCompatActivity {\n\n ListView listView;\n\n public static List<Model> modelList = new ArrayList<>();\n Model model;\n Adapter adapter;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n listView = findViewById(R.id.listView);\n fetchData();\n\n }\n\n private void fetchData() {\n // The Link Through Which We Can Fetch Data\n String url = \"https://api.covid19india.org/state_district_wise.json\";\n\n StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {\n @Override\n public void onResponse(String response) {\n\n try {\n // Creating JSON Object\n JSONObject object = new JSONObject(response);\n\n // From that object we are fetching data\n JSONObject object1 = object.getJSONObject(\"Uttar Pradesh\");\n JSONObject object2 = object1.getJSONObject(\"districtData\");\n JSONObject object3 = object2.getJSONObject(\"Prayagraj\");\n JSONObject object4 = object3.getJSONObject(\"delta\");\n\n\n String active = object3.getString(\"active\");\n String confirmed = object3.getString(\"confirmed\");\n String deceased = object3.getString(\"deceased\");\n String recovered = object3.getString(\"recovered\");\n\n String confInc = object4.getString(\"confirmed\");\n String confDec = object4.getString(\"deceased\");\n String confRec = object4.getString(\"recovered\");\n\n model = new Model(\"Prayagraj\", confirmed, deceased, recovered, active,\n confInc, confDec, confRec);\n // placing data into the app using AdapterClass\n modelList.add(model);\n\n // Creating JSON Object\n object3 = object2.getJSONObject(\"Ballia\");\n\n // From that object we are fetching data\n active = object3.getString(\"active\");\n confirmed = object3.getString(\"confirmed\");\n deceased = object3.getString(\"deceased\");\n recovered = object3.getString(\"recovered\");\n object4 = object3.getJSONObject(\"delta\");\n confInc = object4.getString(\"confirmed\");\n confDec = object4.getString(\"deceased\");\n confRec = object4.getString(\"recovered\");\n\n model = new Model(\"Ballia\", confirmed, deceased, recovered, active,\n confInc, confDec, confRec);\n // placing data into the app using AdapterClass\n modelList.add(model);\n\n // Creating JSON Object\n object3 = object2.getJSONObject(\"Lucknow\");\n\n // From that object we are fetching data\n active = object3.getString(\"active\");\n confirmed = object3.getString(\"confirmed\");\n deceased = object3.getString(\"deceased\");\n recovered = object3.getString(\"recovered\");\n object4 = object3.getJSONObject(\"delta\");\n\n confInc = object4.getString(\"confirmed\");\n confDec = object4.getString(\"deceased\");\n confRec = object4.getString(\"recovered\");\n\n model = new Model(\"Lucknow\", confirmed, deceased, recovered, active,\n confInc, confDec, confRec);\n // placing data into the app using AdapterClass\n modelList.add(model);\n\n // Creating JSON Object\n object3 = object2.getJSONObject(\"Varanasi\");\n\n // From that object we are fetching data\n active = object3.getString(\"active\");\n confirmed = object3.getString(\"confirmed\");\n deceased = object3.getString(\"deceased\");\n recovered = object3.getString(\"recovered\");\n object4 = object3.getJSONObject(\"delta\");\n\n confInc = object4.getString(\"confirmed\");\n confDec = object4.getString(\"deceased\");\n confRec = object4.getString(\"recovered\");\n\n model = new Model(\"Varanasi\", confirmed, deceased, recovered, active,\n confInc, confDec, confRec);\n // placing data into the app using AdapterClass\n modelList.add(model);\n\n // Creating JSON Object\n object3 = object2.getJSONObject(\"Agra\");\n\n // From that object we are fetching data\n active = object3.getString(\"active\");\n confirmed = object3.getString(\"confirmed\");\n deceased = object3.getString(\"deceased\");\n recovered = object3.getString(\"recovered\");\n object4 = object3.getJSONObject(\"delta\");\n confInc = object4.getString(\"confirmed\");\n confDec = object4.getString(\"deceased\");\n confRec = object4.getString(\"recovered\");\n\n model = new Model(\"Agra\", confirmed, deceased, recovered, active,\n confInc, confDec, confRec);\n // placing data into the app using AdapterClass\n modelList.add(model);\n\n adapter = new Adapter(MainActivity.this, modelList);\n listView.setAdapter(adapter);\n\n // In case of error it will run\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n }\n }, new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n // In case of error it will run\n Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();\n }\n });\n\n RequestQueue requestQueue = Volley.newRequestQueue(this);\n requestQueue.add(request);\n }\n}" }, { "code": null, "e": 24762, "s": 24753, "text": "rkbhola5" }, { "code": null, "e": 24770, "s": 24762, "text": "android" }, { "code": null, "e": 24778, "s": 24770, "text": "Android" }, { "code": null, "e": 24783, "s": 24778, "text": "Java" }, { "code": null, "e": 24788, "s": 24783, "text": "Java" }, { "code": null, "e": 24796, "s": 24788, "text": "Android" } ]
ReactJS Onsen UI Page Component
28 Jun, 2021 ReactJS Onsen-UI is a popular front-end library with a set of React components that are designed to developing HTML5 hybrid and mobile web apps in a beautiful and efficient way. Page components are used for handling the entire page. The content can be scrolled. We can use the following approach in ReactJS to use the Onsen-UI Page Component. Page Props: contentStyle: It is used to specify the style of the page content. modifier: It is used to specify modifier names to specify custom styles. renderModal: It is a callback function that is used to render a modal that masks the current screen. renderToolbar: It is a callback function that is used to render the toolbar of the page. renderBottomToolbar: It is a callback function that is used to render the bottom toolbar of the page. renderFixed: It is a callback function that is used to render fixed content of the page. onInit: It is a callback function that is triggered right after the page is attached. onShow: It is a callback function that is triggered right after the page is shown. onHide: It is a callback function that is triggered after the page is hidden. onInfiniteScroll: It is a callback function that is triggered when scrolling to the bottom of the page. onDeviceBackButton: It is used as the custom handler for device back button. Preset Modifiers: material: It is used to show the material design. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install onsenui react-onsenui Step 3: After creating the ReactJS application, Install the required module using the following command: npm install onsenui react-onsenui Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react';import 'onsenui/css/onsen-css-components.css';import 'onsenui/css/onsenui.css';import { Page } from 'react-onsenui'; export default function App() { return ( <div style={{ display: 'block', width: 500, paddingLeft: 30 }}> <h6>ReactJS Onsen-UI Page Component</h6> <Page style={{ width: 400, height: 200, position: 'relative' }}> <div>I am sample Page Content</div> </Page> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://onsen.io/v2/api/react/Page.html Onsen-UI JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JavaScript | Promises How to fetch data from an API in ReactJS ? Axios in React: A Guide for Beginners How to redirect to another page in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jun, 2021" }, { "code": null, "e": 371, "s": 28, "text": "ReactJS Onsen-UI is a popular front-end library with a set of React components that are designed to developing HTML5 hybrid and mobile web apps in a beautiful and efficient way. Page components are used for handling the entire page. The content can be scrolled. We can use the following approach in ReactJS to use the Onsen-UI Page Component." }, { "code": null, "e": 383, "s": 371, "text": "Page Props:" }, { "code": null, "e": 450, "s": 383, "text": "contentStyle: It is used to specify the style of the page content." }, { "code": null, "e": 523, "s": 450, "text": "modifier: It is used to specify modifier names to specify custom styles." }, { "code": null, "e": 624, "s": 523, "text": "renderModal: It is a callback function that is used to render a modal that masks the current screen." }, { "code": null, "e": 713, "s": 624, "text": "renderToolbar: It is a callback function that is used to render the toolbar of the page." }, { "code": null, "e": 815, "s": 713, "text": "renderBottomToolbar: It is a callback function that is used to render the bottom toolbar of the page." }, { "code": null, "e": 904, "s": 815, "text": "renderFixed: It is a callback function that is used to render fixed content of the page." }, { "code": null, "e": 990, "s": 904, "text": "onInit: It is a callback function that is triggered right after the page is attached." }, { "code": null, "e": 1073, "s": 990, "text": "onShow: It is a callback function that is triggered right after the page is shown." }, { "code": null, "e": 1151, "s": 1073, "text": "onHide: It is a callback function that is triggered after the page is hidden." }, { "code": null, "e": 1255, "s": 1151, "text": "onInfiniteScroll: It is a callback function that is triggered when scrolling to the bottom of the page." }, { "code": null, "e": 1332, "s": 1255, "text": "onDeviceBackButton: It is used as the custom handler for device back button." }, { "code": null, "e": 1350, "s": 1332, "text": "Preset Modifiers:" }, { "code": null, "e": 1400, "s": 1350, "text": "material: It is used to show the material design." }, { "code": null, "e": 1452, "s": 1402, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 1547, "s": 1452, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 1611, "s": 1547, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 1643, "s": 1611, "text": "npx create-react-app foldername" }, { "code": null, "e": 1756, "s": 1643, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 1856, "s": 1756, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 1870, "s": 1856, "text": "cd foldername" }, { "code": null, "e": 2009, "s": 1870, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install onsenui react-onsenui " }, { "code": null, "e": 2114, "s": 2009, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 2149, "s": 2114, "text": "npm install onsenui react-onsenui " }, { "code": null, "e": 2201, "s": 2149, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 2219, "s": 2201, "text": "Project Structure" }, { "code": null, "e": 2349, "s": 2219, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 2356, "s": 2349, "text": "App.js" }, { "code": "import React from 'react';import 'onsenui/css/onsen-css-components.css';import 'onsenui/css/onsenui.css';import { Page } from 'react-onsenui'; export default function App() { return ( <div style={{ display: 'block', width: 500, paddingLeft: 30 }}> <h6>ReactJS Onsen-UI Page Component</h6> <Page style={{ width: 400, height: 200, position: 'relative' }}> <div>I am sample Page Content</div> </Page> </div> );}", "e": 2806, "s": 2356, "text": null }, { "code": null, "e": 2919, "s": 2806, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 2929, "s": 2919, "text": "npm start" }, { "code": null, "e": 3028, "s": 2929, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 3079, "s": 3028, "text": "Reference: https://onsen.io/v2/api/react/Page.html" }, { "code": null, "e": 3088, "s": 3079, "text": "Onsen-UI" }, { "code": null, "e": 3099, "s": 3088, "text": "JavaScript" }, { "code": null, "e": 3107, "s": 3099, "text": "ReactJS" }, { "code": null, "e": 3124, "s": 3107, "text": "Web Technologies" }, { "code": null, "e": 3222, "s": 3124, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3283, "s": 3222, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3323, "s": 3283, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3365, "s": 3323, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3406, "s": 3365, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3428, "s": 3406, "text": "JavaScript | Promises" }, { "code": null, "e": 3471, "s": 3428, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 3509, "s": 3471, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 3554, "s": 3509, "text": "How to redirect to another page in ReactJS ?" } ]
Proof that Path Selection Decision problem is NP-Complete
16 Jun, 2020 Prerequisite – NP-CompletenessThe decision problem of path selection problem asks if it is possible to select at least k paths from the given paths of a graph such that no two selected paths share any vertex. To prove that a problem is NP-Complete, we need to show that it is both NP and NP-Hard. We use PSP to denote our path selection decision problem. The PSP belongs to NP :We prove this by constructing a polynomial time verifier for the problem. If any problem is in NP, then, given a ‘certificate’ (a solution) to the problem and an instance of the problem (a graph G and a positive integer k, in this case), we will be able to verify (check whether the solution given is correct or not) the certificate in polynomial time. The certificate for PSP is a set of paths P’. These are independent paths with no common edges. We can check whether there are k paths which are independent for the given a graph G(V, E)) and paths P in the following manner: Check if P' is a subset of P If not, the given solution is wrong The number of paths in P' is at least k If not, the given solution is wrong Initialize a list of boolean with length |V| for each path p in P' for each vertex in p check if it is marked True in our list If so, the given solution is wrong Else, marks the vertex as True Since no vertex was marked twice, given solution is correct. The above verifier is polytime since: Checking P’ is a subset of P can be done in O(|P|).Checking number of paths in P’ can be done in O(|P’|)Checking all the paths are disjoint can be done in O(|V|) Checking P’ is a subset of P can be done in O(|P|). Checking number of paths in P’ can be done in O(|P’|) Checking all the paths are disjoint can be done in O(|V|) Hence, total time complexity :Therefore, the PSP has polynomial time verifiability and hence belongs to the NP Class. The Clique Decision Problem belongs to NP-Hard :To prove that PSP is NP Hard, we take some problem which has already been proven to be NP Hard (Independent Set in our case), and show that this problem can be reduced to the PSP in polynomial time. Since we know Independent set is NP complete, hence it is also NP hard. Given a IS instance – G=(V, E) and k We construct the PSP instance in the following manner: We create a new graph G’. For every vertex vi in G: We denote a path by Pi for vi.Let e1, e2, ..., er be the edges connected to vi. We introduce a vertex for each such edge in G’. Further, we introduce a pair of vertices in G’ – si, ti. We denote a path by Pi for vi. Let e1, e2, ..., er be the edges connected to vi. We introduce a vertex for each such edge in G’. Further, we introduce a pair of vertices in G’ – si, ti. Thus, We can clearly see that the above reduction is polytime(with complexity = O(|V|+|E|)) as we are essentially iterating over all the vertex and the edges in our initial graph. Proof :Proof that the Independent Set problem reduces to the Path Selection Problem. To prove that our reduction is correct we prove the following two arguments. (i) YES, instance for IS => Yes instance for PSPWe have, YES instance for IS. For a graph G=(V, E) there exist an independent set of size at least k.There exist at least k vertices that don’t share any edge.There exist at least k paths that don’t share any node in the instance of PSP. Since we are defining the vertices of G to be analogous to paths in the instance of PSP and edges of G to be analogous to vertices in those paths. And any of these path sharing nodes would mean that some two vertices in the independent set share a common edge which is never possible.Yes, instance for PSP. For a graph G=(V, E) there exist an independent set of size at least k. There exist at least k vertices that don’t share any edge. There exist at least k paths that don’t share any node in the instance of PSP. Since we are defining the vertices of G to be analogous to paths in the instance of PSP and edges of G to be analogous to vertices in those paths. And any of these path sharing nodes would mean that some two vertices in the independent set share a common edge which is never possible. Yes, instance for PSP. (ii) YES, instance for PSP => Yes instance for ISETP: No instance for IS => No instance for PSP. (Proof by contrapositive.). We know that whenever there exist an independent set of size at least k, there exist an independent set of size exactly k(This can be done by taking the subset of size k from the bigger set). Hence, the contrapositive is also true. (i.e, Whenever there cannot exist an independent set of size exactly k, there cannot exist an independent set of size at least k). We have No instance of IS. For a graph G=(V, E) there cannot exist an independent set of size k.It is not possible to find k vertices of G that don’t share any edge.Every set S of vertices of size k would contain vi and vj that share an edge.Since we are defining the vertices of G to be analogous to paths in the instance of PSP and edges of G to be analogous to vertices in those paths, every k size set of Paths in instance of PSP would share a node.There cannot exist k paths that don’t share any node in the instance of PSP.No instance for PSP. For a graph G=(V, E) there cannot exist an independent set of size k. It is not possible to find k vertices of G that don’t share any edge. Every set S of vertices of size k would contain vi and vj that share an edge. Since we are defining the vertices of G to be analogous to paths in the instance of PSP and edges of G to be analogous to vertices in those paths, every k size set of Paths in instance of PSP would share a node. There cannot exist k paths that don’t share any node in the instance of PSP. No instance for PSP. Hence, for a particular instance, the IS problem is reduced to the PSP. Therefore PSP is NP-Hard. Thus, The Path Selection Decision Problem is NP and NP-Hard. Therefore, the Path Selection Decision problem is NP-Complete. Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Boyer-Moore Majority Voting Algorithm Variation of Turing Machine Halting Problem in Theory of Computation Decidable and Undecidable problems in Theory of Computation Post Correspondence Problem NPDA for accepting the language L = {wwR | w ∈ (a,b)*} Pushdown Automata Acceptance by Final State Program to construct a DFA which accept the language L = {anbm | n mod 2=0, m≥1} Undecidability and Reducibility in TOC Arden's Theorem in Theory of Computation
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Jun, 2020" }, { "code": null, "e": 263, "s": 54, "text": "Prerequisite – NP-CompletenessThe decision problem of path selection problem asks if it is possible to select at least k paths from the given paths of a graph such that no two selected paths share any vertex." }, { "code": null, "e": 409, "s": 263, "text": "To prove that a problem is NP-Complete, we need to show that it is both NP and NP-Hard. We use PSP to denote our path selection decision problem." }, { "code": null, "e": 785, "s": 409, "text": "The PSP belongs to NP :We prove this by constructing a polynomial time verifier for the problem. If any problem is in NP, then, given a ‘certificate’ (a solution) to the problem and an instance of the problem (a graph G and a positive integer k, in this case), we will be able to verify (check whether the solution given is correct or not) the certificate in polynomial time." }, { "code": null, "e": 1010, "s": 785, "text": "The certificate for PSP is a set of paths P’. These are independent paths with no common edges. We can check whether there are k paths which are independent for the given a graph G(V, E)) and paths P in the following manner:" }, { "code": null, "e": 1436, "s": 1010, "text": "Check if P' is a subset of P\nIf not, the given solution is wrong\nThe number of paths in P' is at least k\nIf not, the given solution is wrong\n\nInitialize a list of boolean with length |V|\nfor each path p in P'\n for each vertex in p\n check if it is marked True in our list\n If so, the given solution is wrong\n Else, marks the vertex as True\n\nSince no vertex was marked twice,\ngiven solution is correct.\n" }, { "code": null, "e": 1474, "s": 1436, "text": "The above verifier is polytime since:" }, { "code": null, "e": 1636, "s": 1474, "text": "Checking P’ is a subset of P can be done in O(|P|).Checking number of paths in P’ can be done in O(|P’|)Checking all the paths are disjoint can be done in O(|V|)" }, { "code": null, "e": 1688, "s": 1636, "text": "Checking P’ is a subset of P can be done in O(|P|)." }, { "code": null, "e": 1742, "s": 1688, "text": "Checking number of paths in P’ can be done in O(|P’|)" }, { "code": null, "e": 1800, "s": 1742, "text": "Checking all the paths are disjoint can be done in O(|V|)" }, { "code": null, "e": 1918, "s": 1800, "text": "Hence, total time complexity :Therefore, the PSP has polynomial time verifiability and hence belongs to the NP Class." }, { "code": null, "e": 2237, "s": 1918, "text": "The Clique Decision Problem belongs to NP-Hard :To prove that PSP is NP Hard, we take some problem which has already been proven to be NP Hard (Independent Set in our case), and show that this problem can be reduced to the PSP in polynomial time. Since we know Independent set is NP complete, hence it is also NP hard." }, { "code": null, "e": 2259, "s": 2237, "text": "Given a IS instance –" }, { "code": null, "e": 2275, "s": 2259, "text": "G=(V, E) and k " }, { "code": null, "e": 2330, "s": 2275, "text": "We construct the PSP instance in the following manner:" }, { "code": null, "e": 2382, "s": 2330, "text": "We create a new graph G’. For every vertex vi in G:" }, { "code": null, "e": 2567, "s": 2382, "text": "We denote a path by Pi for vi.Let e1, e2, ..., er be the edges connected to vi. We introduce a vertex for each such edge in G’. Further, we introduce a pair of vertices in G’ – si, ti." }, { "code": null, "e": 2598, "s": 2567, "text": "We denote a path by Pi for vi." }, { "code": null, "e": 2753, "s": 2598, "text": "Let e1, e2, ..., er be the edges connected to vi. We introduce a vertex for each such edge in G’. Further, we introduce a pair of vertices in G’ – si, ti." }, { "code": null, "e": 2759, "s": 2753, "text": "Thus," }, { "code": null, "e": 2933, "s": 2759, "text": "We can clearly see that the above reduction is polytime(with complexity = O(|V|+|E|)) as we are essentially iterating over all the vertex and the edges in our initial graph." }, { "code": null, "e": 3095, "s": 2933, "text": "Proof :Proof that the Independent Set problem reduces to the Path Selection Problem. To prove that our reduction is correct we prove the following two arguments." }, { "code": null, "e": 3173, "s": 3095, "text": "(i) YES, instance for IS => Yes instance for PSPWe have, YES instance for IS." }, { "code": null, "e": 3688, "s": 3173, "text": "For a graph G=(V, E) there exist an independent set of size at least k.There exist at least k vertices that don’t share any edge.There exist at least k paths that don’t share any node in the instance of PSP. Since we are defining the vertices of G to be analogous to paths in the instance of PSP and edges of G to be analogous to vertices in those paths. And any of these path sharing nodes would mean that some two vertices in the independent set share a common edge which is never possible.Yes, instance for PSP." }, { "code": null, "e": 3760, "s": 3688, "text": "For a graph G=(V, E) there exist an independent set of size at least k." }, { "code": null, "e": 3819, "s": 3760, "text": "There exist at least k vertices that don’t share any edge." }, { "code": null, "e": 4183, "s": 3819, "text": "There exist at least k paths that don’t share any node in the instance of PSP. Since we are defining the vertices of G to be analogous to paths in the instance of PSP and edges of G to be analogous to vertices in those paths. And any of these path sharing nodes would mean that some two vertices in the independent set share a common edge which is never possible." }, { "code": null, "e": 4206, "s": 4183, "text": "Yes, instance for PSP." }, { "code": null, "e": 4331, "s": 4206, "text": "(ii) YES, instance for PSP => Yes instance for ISETP: No instance for IS => No instance for PSP. (Proof by contrapositive.)." }, { "code": null, "e": 4694, "s": 4331, "text": "We know that whenever there exist an independent set of size at least k, there exist an independent set of size exactly k(This can be done by taking the subset of size k from the bigger set). Hence, the contrapositive is also true. (i.e, Whenever there cannot exist an independent set of size exactly k, there cannot exist an independent set of size at least k)." }, { "code": null, "e": 4721, "s": 4694, "text": "We have No instance of IS." }, { "code": null, "e": 5244, "s": 4721, "text": "For a graph G=(V, E) there cannot exist an independent set of size k.It is not possible to find k vertices of G that don’t share any edge.Every set S of vertices of size k would contain vi and vj that share an edge.Since we are defining the vertices of G to be analogous to paths in the instance of PSP and edges of G to be analogous to vertices in those paths, every k size set of Paths in instance of PSP would share a node.There cannot exist k paths that don’t share any node in the instance of PSP.No instance for PSP." }, { "code": null, "e": 5314, "s": 5244, "text": "For a graph G=(V, E) there cannot exist an independent set of size k." }, { "code": null, "e": 5384, "s": 5314, "text": "It is not possible to find k vertices of G that don’t share any edge." }, { "code": null, "e": 5462, "s": 5384, "text": "Every set S of vertices of size k would contain vi and vj that share an edge." }, { "code": null, "e": 5674, "s": 5462, "text": "Since we are defining the vertices of G to be analogous to paths in the instance of PSP and edges of G to be analogous to vertices in those paths, every k size set of Paths in instance of PSP would share a node." }, { "code": null, "e": 5751, "s": 5674, "text": "There cannot exist k paths that don’t share any node in the instance of PSP." }, { "code": null, "e": 5772, "s": 5751, "text": "No instance for PSP." }, { "code": null, "e": 5870, "s": 5772, "text": "Hence, for a particular instance, the IS problem is reduced to the PSP. Therefore PSP is NP-Hard." }, { "code": null, "e": 5994, "s": 5870, "text": "Thus, The Path Selection Decision Problem is NP and NP-Hard. Therefore, the Path Selection Decision problem is NP-Complete." }, { "code": null, "e": 6027, "s": 5994, "text": "Theory of Computation & Automata" }, { "code": null, "e": 6125, "s": 6027, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6163, "s": 6125, "text": "Boyer-Moore Majority Voting Algorithm" }, { "code": null, "e": 6191, "s": 6163, "text": "Variation of Turing Machine" }, { "code": null, "e": 6232, "s": 6191, "text": "Halting Problem in Theory of Computation" }, { "code": null, "e": 6292, "s": 6232, "text": "Decidable and Undecidable problems in Theory of Computation" }, { "code": null, "e": 6320, "s": 6292, "text": "Post Correspondence Problem" }, { "code": null, "e": 6375, "s": 6320, "text": "NPDA for accepting the language L = {wwR | w ∈ (a,b)*}" }, { "code": null, "e": 6419, "s": 6375, "text": "Pushdown Automata Acceptance by Final State" }, { "code": null, "e": 6500, "s": 6419, "text": "Program to construct a DFA which accept the language L = {anbm | n mod 2=0, m≥1}" }, { "code": null, "e": 6539, "s": 6500, "text": "Undecidability and Reducibility in TOC" } ]
TreeSet descendingIterator() method in Java with Examples
18 Aug, 2021 The descendingIterator() method of java.util.TreeSet<E> class is used to return an iterator over the elements in this set in descending order.Syntax: public Iterator descendingIterator() Return Value: This method returns an iterator over the elements in this set in descending order.Below are the examples to illustrate the descendingIterator() methodExample 1: Java // Java program to demonstrate// descendingIterator() method// for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // create tree set object TreeSet<Integer> treeadd = new TreeSet<Integer>(); // populate the TreeSet using add() method treeadd.add(10); treeadd.add(20); treeadd.add(30); treeadd.add(40); // Print the TreeSet System.out.println("TreeSet: " + treeadd); // create descending iterator // using descendingIterator() method Iterator<Integer> iterator = treeadd.descendingIterator(); System.out.println("\nValues using DescendingIterator:"); // printing the integrated value while (iterator.hasNext()) { System.out.println("Value : " + iterator.next()); } } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } }} TreeSet: [10, 20, 30, 40] Values using DescendingIterator: Value : 40 Value : 30 Value : 20 Value : 10 Example 2: Java // Java program to demonstrate// descendingIterator() method// for String value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // create tree set object TreeSet<String> treeadd = new TreeSet<String>(); // populate the TreeSet using add() method treeadd.add("A"); treeadd.add("B"); treeadd.add("C"); treeadd.add("D"); // Print the TreeSet System.out.println("TreeSet: " + treeadd); // create descending iterator // using descendingIterator() method Iterator<String> iterator = treeadd.descendingIterator(); System.out.println("\nValues using DescendingIterator:"); // printing the integrated value while (iterator.hasNext()) { System.out.println("Value : " + iterator.next()); } } catch (Exception e) { System.out.println("Exception thrown : " + e); } }} TreeSet: [A, B, C, D] Values using DescendingIterator: Value : D Value : C Value : B Value : A kapoorsagar226 Java - util package Java-Collections Java-Functions java-treeset Articles Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Complexity and Space Complexity SQL Interview Questions Understanding "extern" keyword in C SQL | Views Java Tutorial Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Aug, 2021" }, { "code": null, "e": 180, "s": 28, "text": "The descendingIterator() method of java.util.TreeSet<E> class is used to return an iterator over the elements in this set in descending order.Syntax: " }, { "code": null, "e": 217, "s": 180, "text": "public Iterator descendingIterator()" }, { "code": null, "e": 394, "s": 217, "text": "Return Value: This method returns an iterator over the elements in this set in descending order.Below are the examples to illustrate the descendingIterator() methodExample 1: " }, { "code": null, "e": 399, "s": 394, "text": "Java" }, { "code": "// Java program to demonstrate// descendingIterator() method// for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // create tree set object TreeSet<Integer> treeadd = new TreeSet<Integer>(); // populate the TreeSet using add() method treeadd.add(10); treeadd.add(20); treeadd.add(30); treeadd.add(40); // Print the TreeSet System.out.println(\"TreeSet: \" + treeadd); // create descending iterator // using descendingIterator() method Iterator<Integer> iterator = treeadd.descendingIterator(); System.out.println(\"\\nValues using DescendingIterator:\"); // printing the integrated value while (iterator.hasNext()) { System.out.println(\"Value : \" + iterator.next()); } } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 1516, "s": 399, "text": null }, { "code": null, "e": 1620, "s": 1516, "text": "TreeSet: [10, 20, 30, 40]\n\nValues using DescendingIterator:\nValue : 40\nValue : 30\nValue : 20\nValue : 10" }, { "code": null, "e": 1635, "s": 1622, "text": "Example 2: " }, { "code": null, "e": 1640, "s": 1635, "text": "Java" }, { "code": "// Java program to demonstrate// descendingIterator() method// for String value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // create tree set object TreeSet<String> treeadd = new TreeSet<String>(); // populate the TreeSet using add() method treeadd.add(\"A\"); treeadd.add(\"B\"); treeadd.add(\"C\"); treeadd.add(\"D\"); // Print the TreeSet System.out.println(\"TreeSet: \" + treeadd); // create descending iterator // using descendingIterator() method Iterator<String> iterator = treeadd.descendingIterator(); System.out.println(\"\\nValues using DescendingIterator:\"); // printing the integrated value while (iterator.hasNext()) { System.out.println(\"Value : \" + iterator.next()); } } catch (Exception e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 2746, "s": 1640, "text": null }, { "code": null, "e": 2842, "s": 2746, "text": "TreeSet: [A, B, C, D]\n\nValues using DescendingIterator:\nValue : D\nValue : C\nValue : B\nValue : A" }, { "code": null, "e": 2859, "s": 2844, "text": "kapoorsagar226" }, { "code": null, "e": 2879, "s": 2859, "text": "Java - util package" }, { "code": null, "e": 2896, "s": 2879, "text": "Java-Collections" }, { "code": null, "e": 2911, "s": 2896, "text": "Java-Functions" }, { "code": null, "e": 2924, "s": 2911, "text": "java-treeset" }, { "code": null, "e": 2933, "s": 2924, "text": "Articles" }, { "code": null, "e": 2938, "s": 2933, "text": "Java" }, { "code": null, "e": 2943, "s": 2938, "text": "Java" }, { "code": null, "e": 2960, "s": 2943, "text": "Java-Collections" }, { "code": null, "e": 3058, "s": 2960, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3095, "s": 3058, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 3119, "s": 3095, "text": "SQL Interview Questions" }, { "code": null, "e": 3155, "s": 3119, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 3167, "s": 3155, "text": "SQL | Views" }, { "code": null, "e": 3181, "s": 3167, "text": "Java Tutorial" }, { "code": null, "e": 3196, "s": 3181, "text": "Arrays in Java" }, { "code": null, "e": 3240, "s": 3196, "text": "Split() String method in Java with examples" }, { "code": null, "e": 3276, "s": 3240, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 3301, "s": 3276, "text": "Reverse a string in Java" } ]
Replace all occurrences of a string with space
28 May, 2022 Given a string and a substring, the task is to replace all occurrences of the substring with space. We also need to remove trailing and leading spaces created due to this. Examples: Input: str = “LIELIEILIEAMLIECOOL”, sub = “LIE” Output: I AM COOL By replacing all occurrences of Sub in Str with empty spaces, we extract the secret message as I AM COOL. Input: str = “XYZAXYZBXYZC”, sub = “XYZ” Output: ABC By replacing all occurrences of Sub in Str with empty spaces, we extract the secret message as ABC. Approach: In the given string Str, replace all occurrences of Sub with empty spaces. Remove unwanted empty spaces in start and end of the string. Print the modified string. Below is the implementation of the above approach: C++ Java Python3 C# PHP // C++ implementation to extract// the secret message#include <bits/stdc++.h>using namespace std; // Trim method implementation to remove// trailing and leading white-spacesstring trim(const string &s){ auto start = s.begin(); while (start != s.end() && isspace(*start)) start++; auto end = s.end(); do { end--; } while (distance(start, end) > 0 && isspace(*end)); return string(start, end + 1);} // Function to extract the secret messagestring extractSecretMessage(string str, string sub){ // Replacing all occurrences of // Sub in Str by empty spaces size_t pos; while ((pos = str.find(sub)) != string::npos) str.replace(pos, 3, " "); // Removing unwanted spaces in the // start and end of the string str = trim(str); return str;} // Driver codeint main(int argc, char const *argv[]){ string str = "LIELIEILIEAMLIECOOL"; string sub = "LIE"; cout << extractSecretMessage(str, sub) << endl; return 0;} // This code is contributed by// sanjeev2552 // Java implementation to extract the secret messageimport java.io.*;import java.util.*; class GFG { // Function to extract the secret message static String extractSecretMessage(String Str, String Sub) { // Replacing all occurrences of // Sub in Str by empty spaces Str = Str.replaceAll(Sub, " "); // Removing unwanted spaces in the // start and end of the string Str = Str.trim(); return Str; } // Driver code public static void main(String args[]) { String Str = "LIELIEILIEAMLIECOOL"; String Sub = "LIE"; System.out.println(extractSecretMessage(Str, Sub)); }} # Python3 implementation to extract# the secret message # Function to extract the secret messagedef extractSecretMessage(Str, Sub): # Replacing all occurrences of # Sub in Str by empty spaces Str= Str.replace(Sub, " ") # Removing unwanted spaces in the # start and end of the string return Str.strip() # Driver codeStr = "LIELIEILIEAMLIECOOL"Sub = "LIE"print(extractSecretMessage(Str, Sub)) # This code is contributed# by ihritik // C# implementation to extract the// secret messageusing System; class GFG{ // Function to extract the secret messagestatic string extractSecretMessage(string Str, string Sub){ // Replacing all occurrences of // Sub in Str by empty spaces Str = Str.Replace(Sub, " "); // Removing unwanted spaces in the // start and end of the string Str = Str.Trim(); return Str;} // Driver codepublic static void Main(){ string Str = "LIELIEILIEAMLIECOOL"; string Sub = "LIE"; Console.WriteLine(extractSecretMessage(Str, Sub));}} // This code is contributed by Ryuga <?php// PHP implementation to extract the// secret message // Function to extract the secret messagefunction extractSecretMessage($Str, $Sub){ // Replacing all occurrences of // Sub in Str by empty spaces $Str = str_replace($Sub, " ", $Str); // Removing unwanted spaces in the // start and end of the string return trim($Str);} // Driver code$Str = "LIELIEILIEAMLIECOOL";$Sub = "LIE";echo extractSecretMessage($Str, $Sub); // This code is contributed// by ihritik?> I AM COOL Time Complexity: O(N), as we are using replace function which will cost us O(N) time.Auxiliary Space: O(1), as we are not using any extra space. ankthon ihritik sanjeev2552 rohitsingh07052 Java-Strings Java Programs Strings Java-Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate Over the Characters of a String in Java How to Convert Char to String in Java? How to Get Elements By Index from HashSet in Java? Java Program to Write into a File How to Write Data into Excel Sheet using Java? Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Different Methods to Reverse a String in C++
[ { "code": null, "e": 53, "s": 25, "text": "\n28 May, 2022" }, { "code": null, "e": 235, "s": 53, "text": "Given a string and a substring, the task is to replace all occurrences of the substring with space. We also need to remove trailing and leading spaces created due to this. Examples:" }, { "code": null, "e": 560, "s": 235, "text": "Input: str = “LIELIEILIEAMLIECOOL”, sub = “LIE” Output: I AM COOL By replacing all occurrences of Sub in Str with empty spaces, we extract the secret message as I AM COOL. Input: str = “XYZAXYZBXYZC”, sub = “XYZ” Output: ABC By replacing all occurrences of Sub in Str with empty spaces, we extract the secret message as ABC." }, { "code": null, "e": 570, "s": 560, "text": "Approach:" }, { "code": null, "e": 645, "s": 570, "text": "In the given string Str, replace all occurrences of Sub with empty spaces." }, { "code": null, "e": 706, "s": 645, "text": "Remove unwanted empty spaces in start and end of the string." }, { "code": null, "e": 733, "s": 706, "text": "Print the modified string." }, { "code": null, "e": 785, "s": 733, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 789, "s": 785, "text": "C++" }, { "code": null, "e": 794, "s": 789, "text": "Java" }, { "code": null, "e": 802, "s": 794, "text": "Python3" }, { "code": null, "e": 805, "s": 802, "text": "C#" }, { "code": null, "e": 809, "s": 805, "text": "PHP" }, { "code": "// C++ implementation to extract// the secret message#include <bits/stdc++.h>using namespace std; // Trim method implementation to remove// trailing and leading white-spacesstring trim(const string &s){ auto start = s.begin(); while (start != s.end() && isspace(*start)) start++; auto end = s.end(); do { end--; } while (distance(start, end) > 0 && isspace(*end)); return string(start, end + 1);} // Function to extract the secret messagestring extractSecretMessage(string str, string sub){ // Replacing all occurrences of // Sub in Str by empty spaces size_t pos; while ((pos = str.find(sub)) != string::npos) str.replace(pos, 3, \" \"); // Removing unwanted spaces in the // start and end of the string str = trim(str); return str;} // Driver codeint main(int argc, char const *argv[]){ string str = \"LIELIEILIEAMLIECOOL\"; string sub = \"LIE\"; cout << extractSecretMessage(str, sub) << endl; return 0;} // This code is contributed by// sanjeev2552", "e": 1902, "s": 809, "text": null }, { "code": "// Java implementation to extract the secret messageimport java.io.*;import java.util.*; class GFG { // Function to extract the secret message static String extractSecretMessage(String Str, String Sub) { // Replacing all occurrences of // Sub in Str by empty spaces Str = Str.replaceAll(Sub, \" \"); // Removing unwanted spaces in the // start and end of the string Str = Str.trim(); return Str; } // Driver code public static void main(String args[]) { String Str = \"LIELIEILIEAMLIECOOL\"; String Sub = \"LIE\"; System.out.println(extractSecretMessage(Str, Sub)); }}", "e": 2563, "s": 1902, "text": null }, { "code": "# Python3 implementation to extract# the secret message # Function to extract the secret messagedef extractSecretMessage(Str, Sub): # Replacing all occurrences of # Sub in Str by empty spaces Str= Str.replace(Sub, \" \") # Removing unwanted spaces in the # start and end of the string return Str.strip() # Driver codeStr = \"LIELIEILIEAMLIECOOL\"Sub = \"LIE\"print(extractSecretMessage(Str, Sub)) # This code is contributed# by ihritik", "e": 3018, "s": 2563, "text": null }, { "code": "// C# implementation to extract the// secret messageusing System; class GFG{ // Function to extract the secret messagestatic string extractSecretMessage(string Str, string Sub){ // Replacing all occurrences of // Sub in Str by empty spaces Str = Str.Replace(Sub, \" \"); // Removing unwanted spaces in the // start and end of the string Str = Str.Trim(); return Str;} // Driver codepublic static void Main(){ string Str = \"LIELIEILIEAMLIECOOL\"; string Sub = \"LIE\"; Console.WriteLine(extractSecretMessage(Str, Sub));}} // This code is contributed by Ryuga", "e": 3637, "s": 3018, "text": null }, { "code": "<?php// PHP implementation to extract the// secret message // Function to extract the secret messagefunction extractSecretMessage($Str, $Sub){ // Replacing all occurrences of // Sub in Str by empty spaces $Str = str_replace($Sub, \" \", $Str); // Removing unwanted spaces in the // start and end of the string return trim($Str);} // Driver code$Str = \"LIELIEILIEAMLIECOOL\";$Sub = \"LIE\";echo extractSecretMessage($Str, $Sub); // This code is contributed// by ihritik?>", "e": 4127, "s": 3637, "text": null }, { "code": null, "e": 4137, "s": 4127, "text": "I AM COOL" }, { "code": null, "e": 4283, "s": 4137, "text": "Time Complexity: O(N), as we are using replace function which will cost us O(N) time.Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 4291, "s": 4283, "text": "ankthon" }, { "code": null, "e": 4299, "s": 4291, "text": "ihritik" }, { "code": null, "e": 4311, "s": 4299, "text": "sanjeev2552" }, { "code": null, "e": 4327, "s": 4311, "text": "rohitsingh07052" }, { "code": null, "e": 4340, "s": 4327, "text": "Java-Strings" }, { "code": null, "e": 4354, "s": 4340, "text": "Java Programs" }, { "code": null, "e": 4362, "s": 4354, "text": "Strings" }, { "code": null, "e": 4375, "s": 4362, "text": "Java-Strings" }, { "code": null, "e": 4383, "s": 4375, "text": "Strings" }, { "code": null, "e": 4481, "s": 4383, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4529, "s": 4481, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 4568, "s": 4529, "text": "How to Convert Char to String in Java?" }, { "code": null, "e": 4619, "s": 4568, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 4653, "s": 4619, "text": "Java Program to Write into a File" }, { "code": null, "e": 4700, "s": 4653, "text": "How to Write Data into Excel Sheet using Java?" }, { "code": null, "e": 4746, "s": 4700, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 4771, "s": 4746, "text": "Reverse a string in Java" }, { "code": null, "e": 4831, "s": 4771, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 4846, "s": 4831, "text": "C++ Data Types" } ]
Minimum operations to make the MEX of the given set equal to x
08 Mar, 2022 Given a set of n integers, perform minimum number of operations (you can insert/delete elements into/from the set) to make the MEX of the set equal to x (that is given). Note:- The MEX of a set of integers is the minimum non-negative integer that doesn’t exist in it. For example, the MEX of the set {0, 2, 4} is 1 and the MEX of the set {1, 2, 3} is 0. Examples : Input : n = 5, x = 3 0 4 5 6 7 Output : 2 The MEX of the set {0, 4, 5, 6, 7} is 1 which is not equal to 3. So, we should add 1 and 2 to the set. After adding 1 and 2, the set becomes {0, 1, 2, 4, 5, 6, 7} and 3 is the minimum non-negative integer that doesn't exist in it. So, the MEX of this set is 3 which is equal to x i.e. 3. So, the output of this example is 2 as we inserted 1 and 2 in the set. Input : n = 1, x = 0 1 Output : 0 In this example, the MEX of the given set {1} is already 0. So, we do not need to perform any operation. So, the output is 0. Approach: The approach is to see that in the final set all the elements less than x should exist, x shouldn’t exist and any element greater than x doesn’t matter. So, we will count the number of elements less than x that don’t exist in the initial set and add this to the answer. If x exists we will add 1 to the answer because x should be removed.Below is the implementation of above approach: C++ Java Python C# PHP Javascript // CPP program to perform minimal number// of operations to make the MEX of the// set equal to the given number x.#include <bits/stdc++.h>using namespace std; // function to find minimum number of// operations requiredint minOpeartions(int arr[], int n, int x){ int k = x, i = 0; while (n--) { // if the element is less than x. if (arr[n] < x) k--; // if the element equals to x. if (arr[n] == x) k++; } return k;} // driver functionint main(){ int arr[] = { 0, 4, 5, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; // output cout << minOpeartions(arr, n, x) << endl;} // Java program to perform minimal number// of operations to make the MEX of the// set equal to the given number x.import java.io.*; class GFG { // function to find minimum number of // operations required static int minOpeartions(int arr[], int n, int x) { int k = x, i = 0; n--; while (n > -1) { // if the element is less than x. if (arr[n] < x) k--; // if the element equals to x. if (arr[n] == x) k++; n--; } return k; } // driver function public static void main(String args[]) { int arr[] = { 0, 4, 5, 6, 7 }; int n = arr.length; int x = 3; // output System.out.println(minOpeartions(arr, n, x)); }} /* This code is contributed by Nikita Tiwari.*/ # Python 3 program to perform minimal number# of operations to make the MEX of the# set equal to the given number x. # function to find minimum number of# operations requireddef minOpeartions(arr, n, x) : k = x i = 0 n = n-1 while (n>-1) : # if the element is less than x. if (arr[n] < x) : k = k - 1 # if the element equals to x. if (arr[n] == x) : k = k + 1 n = n - 1 return k # driver functionarr = [ 0, 4, 5, 6, 7 ]n = len(arr)x = 3 # outputprint( minOpeartions(arr, n, x)) # This code is contributed by Nikita Tiwari. // C# program to perform minimal number// of operations to make the MEX of the// set equal to the given number x.using System; class GFG { // function to find minimum number // of operations required static int minOpeartions(int[] arr, int n, int x) { int k = x; n--; while (n > -1) { // if the element is less // than x. if (arr[n] < x) k--; // if the element equals // to x. if (arr[n] == x) k++; n--; } return k; } // driver function public static void Main() { int[] arr = { 0, 4, 5, 6, 7 }; int n = arr.Length; int x = 3; // output Console.WriteLine( minOpeartions(arr, n, x)); }} // This code is contributed by vt_m. <?php// PHP program to perform minimal// number of operations to make// the MEX of the set equal to// the given number x. // function to find minimum number// of operations requiredfunction minOpeartions( $arr, $n, $x){ $k = $x; $i = 0; while ($n--) { // if the element is // less than x. if ($arr[$n] < $x) $k--; // if the element equals to x. if ($arr[$n] == $x) $k++; } return $k;} // Driver Code$arr = array(0, 4, 5, 6, 7);$n = count($arr);$x = 3; echo minOpeartions($arr, $n, $x) ; // This code is contributed by anuj_67.?> <script> // Javascript program to perform minimal number // of operations to make the MEX of the // set equal to the given number x. // function to find minimum number of // operations required function minOpeartions(arr, n, x) { let k = x, i = 0; while (n-- > 0) { // if the element is less than x. if (arr[n] < x) k--; // if the element equals to x. if (arr[n] == x) k++; } return k; } let arr = [ 0, 4, 5, 6, 7 ]; let n = arr.length; let x = 3; // output document.write(minOpeartions(arr, n, x)); </script> Output : 2 Time Complexity: O(n)Auxiliary Space: O(1) vt_m suresh07 singhh3010 Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Mar, 2022" }, { "code": null, "e": 421, "s": 54, "text": "Given a set of n integers, perform minimum number of operations (you can insert/delete elements into/from the set) to make the MEX of the set equal to x (that is given). Note:- The MEX of a set of integers is the minimum non-negative integer that doesn’t exist in it. For example, the MEX of the set {0, 2, 4} is 1 and the MEX of the set {1, 2, 3} is 0. Examples : " }, { "code": null, "e": 1003, "s": 421, "text": "Input : n = 5, x = 3\n 0 4 5 6 7\nOutput : 2\nThe MEX of the set {0, 4, 5, 6, 7} is 1 which is \nnot equal to 3. So, we should add 1 and 2 to the\nset. After adding 1 and 2, the set becomes \n{0, 1, 2, 4, 5, 6, 7} and 3 is the minimum\nnon-negative integer that doesn't exist in it.\nSo, the MEX of this set is 3 which is equal to\nx i.e. 3. So, the output of this example is 2 \nas we inserted 1 and 2 in the set.\n\nInput : n = 1, x = 0\n 1\nOutput : 0\nIn this example, the MEX of the given set {1}\nis already 0. So, we do not need to perform \nany operation. So, the output is 0." }, { "code": null, "e": 1401, "s": 1005, "text": "Approach: The approach is to see that in the final set all the elements less than x should exist, x shouldn’t exist and any element greater than x doesn’t matter. So, we will count the number of elements less than x that don’t exist in the initial set and add this to the answer. If x exists we will add 1 to the answer because x should be removed.Below is the implementation of above approach: " }, { "code": null, "e": 1405, "s": 1401, "text": "C++" }, { "code": null, "e": 1410, "s": 1405, "text": "Java" }, { "code": null, "e": 1417, "s": 1410, "text": "Python" }, { "code": null, "e": 1420, "s": 1417, "text": "C#" }, { "code": null, "e": 1424, "s": 1420, "text": "PHP" }, { "code": null, "e": 1435, "s": 1424, "text": "Javascript" }, { "code": "// CPP program to perform minimal number// of operations to make the MEX of the// set equal to the given number x.#include <bits/stdc++.h>using namespace std; // function to find minimum number of// operations requiredint minOpeartions(int arr[], int n, int x){ int k = x, i = 0; while (n--) { // if the element is less than x. if (arr[n] < x) k--; // if the element equals to x. if (arr[n] == x) k++; } return k;} // driver functionint main(){ int arr[] = { 0, 4, 5, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; // output cout << minOpeartions(arr, n, x) << endl;}", "e": 2092, "s": 1435, "text": null }, { "code": "// Java program to perform minimal number// of operations to make the MEX of the// set equal to the given number x.import java.io.*; class GFG { // function to find minimum number of // operations required static int minOpeartions(int arr[], int n, int x) { int k = x, i = 0; n--; while (n > -1) { // if the element is less than x. if (arr[n] < x) k--; // if the element equals to x. if (arr[n] == x) k++; n--; } return k; } // driver function public static void main(String args[]) { int arr[] = { 0, 4, 5, 6, 7 }; int n = arr.length; int x = 3; // output System.out.println(minOpeartions(arr, n, x)); }} /* This code is contributed by Nikita Tiwari.*/", "e": 2937, "s": 2092, "text": null }, { "code": "# Python 3 program to perform minimal number# of operations to make the MEX of the# set equal to the given number x. # function to find minimum number of# operations requireddef minOpeartions(arr, n, x) : k = x i = 0 n = n-1 while (n>-1) : # if the element is less than x. if (arr[n] < x) : k = k - 1 # if the element equals to x. if (arr[n] == x) : k = k + 1 n = n - 1 return k # driver functionarr = [ 0, 4, 5, 6, 7 ]n = len(arr)x = 3 # outputprint( minOpeartions(arr, n, x)) # This code is contributed by Nikita Tiwari.", "e": 3559, "s": 2937, "text": null }, { "code": "// C# program to perform minimal number// of operations to make the MEX of the// set equal to the given number x.using System; class GFG { // function to find minimum number // of operations required static int minOpeartions(int[] arr, int n, int x) { int k = x; n--; while (n > -1) { // if the element is less // than x. if (arr[n] < x) k--; // if the element equals // to x. if (arr[n] == x) k++; n--; } return k; } // driver function public static void Main() { int[] arr = { 0, 4, 5, 6, 7 }; int n = arr.Length; int x = 3; // output Console.WriteLine( minOpeartions(arr, n, x)); }} // This code is contributed by vt_m.", "e": 4440, "s": 3559, "text": null }, { "code": "<?php// PHP program to perform minimal// number of operations to make// the MEX of the set equal to// the given number x. // function to find minimum number// of operations requiredfunction minOpeartions( $arr, $n, $x){ $k = $x; $i = 0; while ($n--) { // if the element is // less than x. if ($arr[$n] < $x) $k--; // if the element equals to x. if ($arr[$n] == $x) $k++; } return $k;} // Driver Code$arr = array(0, 4, 5, 6, 7);$n = count($arr);$x = 3; echo minOpeartions($arr, $n, $x) ; // This code is contributed by anuj_67.?>", "e": 5043, "s": 4440, "text": null }, { "code": "<script> // Javascript program to perform minimal number // of operations to make the MEX of the // set equal to the given number x. // function to find minimum number of // operations required function minOpeartions(arr, n, x) { let k = x, i = 0; while (n-- > 0) { // if the element is less than x. if (arr[n] < x) k--; // if the element equals to x. if (arr[n] == x) k++; } return k; } let arr = [ 0, 4, 5, 6, 7 ]; let n = arr.length; let x = 3; // output document.write(minOpeartions(arr, n, x)); </script>", "e": 5707, "s": 5043, "text": null }, { "code": null, "e": 5717, "s": 5707, "text": "Output : " }, { "code": null, "e": 5719, "s": 5717, "text": "2" }, { "code": null, "e": 5763, "s": 5719, "text": "Time Complexity: O(n)Auxiliary Space: O(1) " }, { "code": null, "e": 5768, "s": 5763, "text": "vt_m" }, { "code": null, "e": 5777, "s": 5768, "text": "suresh07" }, { "code": null, "e": 5788, "s": 5777, "text": "singhh3010" }, { "code": null, "e": 5795, "s": 5788, "text": "Arrays" }, { "code": null, "e": 5802, "s": 5795, "text": "Arrays" } ]
numpy string operations | strip() function
17 Jan, 2019 numpy.core.defchararray.strip(arr, chars=None) is another function for doing string operations in numpy. It returns a copy with the leading and trailing characters removed for each element in arr. Parameters:arr : array_like of str or unicode.char : [str or unicode, optional] the set of characters to be removed. If omitted or None, it removes whitespace. The chars argument is not a prefix or suffix; it is all combinations of its values which we want to strip. Returns : [ndarray] Output array of str or unicode, depending on input type. Code #1 : # Python program explaining# numpy.char.strip() method import numpy as geek # input arrays in_arr = geek.array(['Sun', ' Moon ', 'Star'])print ("Input array : ", in_arr) out_arr = geek.char.strip(in_arr) # whitespace removed from arr[1] # as we have set chars = Noneprint ("Output array: ", out_arr) Input array : ['Sun' ' Moon ' 'Star'] Output array: ['Sun' 'Moon' 'Star'] Code #2 : # Python program explaining# numpy.char.strip() method import numpy as geek # input arrays in_arr = geek.array(['Sun', ' Moon ', 'Star'])print ("Input array : ", in_arr) out_arr = geek.char.strip(in_arr, chars ='Sun') # 'Sun' removed from arr[0] as we have set chars = Sunprint ("Output array: ", out_arr) Input array : ['Sun' ' Moon ' 'Star'] Output array: ['' ' Moon ' 'tar'] Code #3 : # Python program explaining# numpy.char.strip() method import numpy as geek # input arrays in_arr = geek.array([ 'Geeks', 'For', 'Geeks'] )print ("Input array : ", in_arr) out_arr = geek.char.strip(in_arr, chars ='G') #'G' removed from arr[0] and arr[2]# as we have set chars ='G'print ("Output array: ", out_arr) Input array : ['Geeks' 'For' 'Geeks'] Output array: ['eeks' 'For' 'eeks'] Python numpy-String Operation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jan, 2019" }, { "code": null, "e": 225, "s": 28, "text": "numpy.core.defchararray.strip(arr, chars=None) is another function for doing string operations in numpy. It returns a copy with the leading and trailing characters removed for each element in arr." }, { "code": null, "e": 492, "s": 225, "text": "Parameters:arr : array_like of str or unicode.char : [str or unicode, optional] the set of characters to be removed. If omitted or None, it removes whitespace. The chars argument is not a prefix or suffix; it is all combinations of its values which we want to strip." }, { "code": null, "e": 569, "s": 492, "text": "Returns : [ndarray] Output array of str or unicode, depending on input type." }, { "code": null, "e": 579, "s": 569, "text": "Code #1 :" }, { "code": "# Python program explaining# numpy.char.strip() method import numpy as geek # input arrays in_arr = geek.array(['Sun', ' Moon ', 'Star'])print (\"Input array : \", in_arr) out_arr = geek.char.strip(in_arr) # whitespace removed from arr[1] # as we have set chars = Noneprint (\"Output array: \", out_arr) ", "e": 889, "s": 579, "text": null }, { "code": null, "e": 966, "s": 889, "text": "Input array : ['Sun' ' Moon ' 'Star']\nOutput array: ['Sun' 'Moon' 'Star']\n" }, { "code": null, "e": 977, "s": 966, "text": " Code #2 :" }, { "code": "# Python program explaining# numpy.char.strip() method import numpy as geek # input arrays in_arr = geek.array(['Sun', ' Moon ', 'Star'])print (\"Input array : \", in_arr) out_arr = geek.char.strip(in_arr, chars ='Sun') # 'Sun' removed from arr[0] as we have set chars = Sunprint (\"Output array: \", out_arr) ", "e": 1293, "s": 977, "text": null }, { "code": null, "e": 1368, "s": 1293, "text": "Input array : ['Sun' ' Moon ' 'Star']\nOutput array: ['' ' Moon ' 'tar']\n" }, { "code": null, "e": 1379, "s": 1368, "text": " Code #3 :" }, { "code": "# Python program explaining# numpy.char.strip() method import numpy as geek # input arrays in_arr = geek.array([ 'Geeks', 'For', 'Geeks'] )print (\"Input array : \", in_arr) out_arr = geek.char.strip(in_arr, chars ='G') #'G' removed from arr[0] and arr[2]# as we have set chars ='G'print (\"Output array: \", out_arr) ", "e": 1700, "s": 1379, "text": null }, { "code": null, "e": 1777, "s": 1700, "text": "Input array : ['Geeks' 'For' 'Geeks']\nOutput array: ['eeks' 'For' 'eeks']\n" }, { "code": null, "e": 1807, "s": 1777, "text": "Python numpy-String Operation" }, { "code": null, "e": 1820, "s": 1807, "text": "Python-numpy" }, { "code": null, "e": 1827, "s": 1820, "text": "Python" } ]
What is stdClass in PHP?
01 Aug, 2021 The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified. But, if object type is converted/type-casted an instance of stdClass is created, if it is not NULL. If it is NULL, the new instance will be empty. Uses: The stdClass directly access the members by calling them. It is useful in dynamic object. It is used to set dynamic properties etc. Program 1: Using array to storing data <?php // Array definition of an employee$employee_detail_array = array( "name" => "John Doe", "position" => "Software Engineer", "address" => "53, nth street, city", "status" => "best"); // Display the array contentprint_r($employee_detail_array);?> Array ( [name] => John Doe [position] => Software Engineer [address] => 53, nth street, city [status] => best ) Program 2: Using stdClass instead of array to store employee details (dynamic properties) <?php // Object-styled definition of an employee$employee_object = new stdClass;$employee_object->name = "John Doe";$employee_object->position = "Software Engineer";$employee_object->address = "53, nth street, city";$employee_object->status = "Best"; // Display the employee contentsprint_r($employee_object);?> stdClass Object ( [name] => John Doe [position] => Software Engineer [address] => 53, nth street, city [status] => Best ) Note: The type casting of array into object and object to array is possible. Program 3: Converting array into object <?php // Aarray definition of an employee$employee_detail_array = array( "name" => "John Doe", "position" => "Software Engineer", "address" => "53, nth street, city", "status" => "best"); // type casting from array to object$employee = (object) $employee_detail_array; print_r($employee);?> stdClass Object ( [name] => John Doe [position] => Software Engineer [address] => 53, nth street, city [status] => best ) Program 4: Converting object properties into array <?php // Object-styled definition of an employee$employee_object = new stdClass;$employee_object->name = "John Doe";$employee_object->position = "Software Engineer";$employee_object->address = "53, nth street, city";$employee_object->status = "Best"; // The object is converted into array // using type casting$employee_array = (array) $employee_object; // Display the result in arrayprint_r($employee_array);?> Array ( [name] => John Doe [position] => Software Engineer [address] => 53, nth street, city [status] => Best ) PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. Picked PHP PHP Programs PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Aug, 2021" }, { "code": null, "e": 433, "s": 54, "text": "The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified. But, if object type is converted/type-casted an instance of stdClass is created, if it is not NULL. If it is NULL, the new instance will be empty." }, { "code": null, "e": 439, "s": 433, "text": "Uses:" }, { "code": null, "e": 497, "s": 439, "text": "The stdClass directly access the members by calling them." }, { "code": null, "e": 529, "s": 497, "text": "It is useful in dynamic object." }, { "code": null, "e": 571, "s": 529, "text": "It is used to set dynamic properties etc." }, { "code": null, "e": 610, "s": 571, "text": "Program 1: Using array to storing data" }, { "code": "<?php // Array definition of an employee$employee_detail_array = array( \"name\" => \"John Doe\", \"position\" => \"Software Engineer\", \"address\" => \"53, nth street, city\", \"status\" => \"best\"); // Display the array contentprint_r($employee_detail_array);?>", "e": 878, "s": 610, "text": null }, { "code": null, "e": 1007, "s": 878, "text": "Array\n(\n [name] => John Doe\n [position] => Software Engineer\n [address] => 53, nth street, city\n [status] => best\n)\n" }, { "code": null, "e": 1097, "s": 1007, "text": "Program 2: Using stdClass instead of array to store employee details (dynamic properties)" }, { "code": "<?php // Object-styled definition of an employee$employee_object = new stdClass;$employee_object->name = \"John Doe\";$employee_object->position = \"Software Engineer\";$employee_object->address = \"53, nth street, city\";$employee_object->status = \"Best\"; // Display the employee contentsprint_r($employee_object);?>", "e": 1419, "s": 1097, "text": null }, { "code": null, "e": 1558, "s": 1419, "text": "stdClass Object\n(\n [name] => John Doe\n [position] => Software Engineer\n [address] => 53, nth street, city\n [status] => Best\n)\n" }, { "code": null, "e": 1635, "s": 1558, "text": "Note: The type casting of array into object and object to array is possible." }, { "code": null, "e": 1675, "s": 1635, "text": "Program 3: Converting array into object" }, { "code": "<?php // Aarray definition of an employee$employee_detail_array = array( \"name\" => \"John Doe\", \"position\" => \"Software Engineer\", \"address\" => \"53, nth street, city\", \"status\" => \"best\"); // type casting from array to object$employee = (object) $employee_detail_array; print_r($employee);?>", "e": 1985, "s": 1675, "text": null }, { "code": null, "e": 2124, "s": 1985, "text": "stdClass Object\n(\n [name] => John Doe\n [position] => Software Engineer\n [address] => 53, nth street, city\n [status] => best\n)\n" }, { "code": null, "e": 2175, "s": 2124, "text": "Program 4: Converting object properties into array" }, { "code": "<?php // Object-styled definition of an employee$employee_object = new stdClass;$employee_object->name = \"John Doe\";$employee_object->position = \"Software Engineer\";$employee_object->address = \"53, nth street, city\";$employee_object->status = \"Best\"; // The object is converted into array // using type casting$employee_array = (array) $employee_object; // Display the result in arrayprint_r($employee_array);?>", "e": 2594, "s": 2175, "text": null }, { "code": null, "e": 2723, "s": 2594, "text": "Array\n(\n [name] => John Doe\n [position] => Software Engineer\n [address] => 53, nth street, city\n [status] => Best\n)\n" }, { "code": null, "e": 2892, "s": 2723, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 2899, "s": 2892, "text": "Picked" }, { "code": null, "e": 2903, "s": 2899, "text": "PHP" }, { "code": null, "e": 2916, "s": 2903, "text": "PHP Programs" }, { "code": null, "e": 2920, "s": 2916, "text": "PHP" } ]
ReactJS Functional Components
30 Jun, 2022 Functional components are some of the more common components that will come across while working in React. These are simply JavaScript functions. We can create a functional component to React by writing a JavaScript function. These functions may or may not receive data as parameters. In the functional Components, the return value is the JSX code to render to the DOM tree.Example: Program to demonstrate the creation of functional components. Filepath- src/index.js: Open your React project directory and edit the index.js file from src folder: Javascript import React from 'react';import ReactDOM from 'react-dom';import Demo from './App'; ReactDOM.render( <React.StrictMode> <Demo /> </React.StrictMode>, document.getElementById('root')); Filepath- src/App.js: Open your React project directory and edit the App.js file from src folder: javascript import React from 'react';import ReactDOM from 'react-dom'; const Demo=()=>{ return <h1>Welcome to GeeksforGeeks</h1>;} export default Demo; Output: Different ways of calling the functional component: We can call the functions in java script in other ways as following: Calling the function by using name of the function followed by the Parentheses. Javascript import React from 'react';import ReactDOM from 'react-dom/client'; function Parentheses() { return ( <h1> As usual we can call the function using name of the function followed by Parentheses </h1>); } const root = ReactDOM.createRoot(document.getElementById('root'));root.render(Parentheses()); Calling the function using the functional component Javascript import React from 'react';import ReactDOM from 'react-dom/client'; function Comp() { return ( <h1> As usual we can call the function using component call</h1>); } const root = ReactDOM.createRoot(document.getElementById('root'));root.render(<Comp/>); Example: We can also use a functional component into another component. The below program is to demonstrates the use of functional components in other components. Filepath- src index.js: Open your React project directory and edit the Index.js file from src folder Javascript import React from 'react';import ReactDOM from 'react-dom';import Welcome from './App'; ReactDOM.render( <React.StrictMode> <Welcome /> </React.StrictMode>, document.getElementById('root')); Filepath- src App.js: Open your React project directory and edit the App.js file from src folder: javascript import React from 'react'; const Welcome=()=>{return ( <h1>Welcome to GeeksforGeeks</h1> );} const functionExample=()=>{ return ( <Welcome/> );} export default functionExample; Output: Functional components lack a significant amount of features as compared to class-based components. The gap is made up with the help of a special ReactJS concept called “hooks”. Hooks are special functions that allow ReactJS features to be used in functional components. Functional components do not have access to dedicated state variables like class-based components. The only “state” that a functional component effectively has access to are the props passed to it from its parent component. ReactJS has access to a special hook called useState() that can be used for giving the illusion of working with the state in functional components. The useState() is used to initialize only one state variable to initialize multiple state variables, multiple useState() declarations are required. The first value returned is the initial value of the state variable, while the second value returned is a reference to the function that updates it. When the state variable needs to be updated, it can be done by calling the update function and by updating the state variable directly inside it. Example: Program to demonstrate the use of useState() hook. Filepath- src/index.js: Open your React project directory and edit the Index.js file from src folder: Javascript import React from 'react';import ReactDOM from 'react-dom';import Example from './App'; ReactDOM.render( <React.StrictMode> <Example /> </React.StrictMode>, document.getElementById('root')); Filepath- src/App.js: Open your React project directory and edit the App.js file from src folder: javascript import React, { useState } from 'react'; const Example=()=> { const [change, setChange] = useState(true); return ( <div> <button onClick = {() => setChange(!change)}> Click Here! </button> {change?<h1>Welcome to GeeksforGeeks</h1>: <h1>A Computer Science Portal for Geeks</h1>} </div> ); } export default Example; Output: Functional components do not have access to lifecycle functions like class-based components do since lifecycle functions need to be defined within the boundaries of a class. If lifecycle functions need to be used with functional components, a special React hook called useEffect() needs to be used. It is worth noting that useEffect() isn’t an exact duplicate of the lifecycle functions – it works and behaves in a slightly different manner. Example: Program to demonstrate the use of useEffect() hook. Filepath- src/index.js: Open your React project directory and edit the index.js file from src folder: Javascript import React from 'react';import ReactDOM from 'react-dom';import Example from './App'; ReactDOM.render( <React.StrictMode> <Example /> </React.StrictMode>, document.getElementById('root')); Filepath- src/App.js: Open your React project directory and edit the App.js file from src folder: javascript import React, { useEffect } from 'react'; const Example=()=> { useEffect(() => { console.log("Mounting..."); }); return ( <h1> Geeks....! </h1> );} export default Example; Output: Data is passed from the parent component to the child components in the form of props. ReactJS does not allow a component to modify its own props as a rule. The only way to modify the props is to change the props being passed to the child component. This is generally done by passing a reference of a function in the parent component to the child component. Props have more significance in functional components for the simple reason that functional components do not have access to a state, unlike class-based components. Example: Program to demonstrate the use of props. Filepatje- src/index.js: Open your React project directory and edit the Index.js file from src folder: Javascript import React from 'react';import ReactDOM from 'react-dom';import Example from './App'; ReactDOM.render( <React.StrictMode> <Example /> </React.StrictMode>, document.getElementById('root')); Filepath- src/App.js: Open your React project directory and edit the App.js file from src folder: javascript import React, { useState } from 'react';import props from 'prop-types'; const Example=()=> { return( <h1>{props.data}</h1> ); } function propsExample() { const [change, setChange] = useState(true); return ( <div> <button onClick = {() => setChange(!change)}> Click Here! </button> {change? <Example data="Welcome to GeeksforGeeks"/>: <Example data="A Computer Science Portal for Geeks"/>} </div> ); } export default Example; Output: shubhamyadav4 varshagumber28 nikhiljugale007 sushruthkontham nikhatkhann11 react-js ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? Axios in React: A Guide for Beginners ReactJS setState() How to pass data from one component to other component in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2022" }, { "code": null, "e": 498, "s": 52, "text": "Functional components are some of the more common components that will come across while working in React. These are simply JavaScript functions. We can create a functional component to React by writing a JavaScript function. These functions may or may not receive data as parameters. In the functional Components, the return value is the JSX code to render to the DOM tree.Example: Program to demonstrate the creation of functional components. " }, { "code": null, "e": 600, "s": 498, "text": "Filepath- src/index.js: Open your React project directory and edit the index.js file from src folder:" }, { "code": null, "e": 611, "s": 600, "text": "Javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom';import Demo from './App'; ReactDOM.render( <React.StrictMode> <Demo /> </React.StrictMode>, document.getElementById('root'));", "e": 802, "s": 611, "text": null }, { "code": null, "e": 900, "s": 802, "text": "Filepath- src/App.js: Open your React project directory and edit the App.js file from src folder:" }, { "code": null, "e": 911, "s": 900, "text": "javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom'; const Demo=()=>{ return <h1>Welcome to GeeksforGeeks</h1>;} export default Demo;", "e": 1053, "s": 911, "text": null }, { "code": null, "e": 1062, "s": 1053, "text": "Output: " }, { "code": null, "e": 1114, "s": 1062, "text": "Different ways of calling the functional component:" }, { "code": null, "e": 1183, "s": 1114, "text": "We can call the functions in java script in other ways as following:" }, { "code": null, "e": 1263, "s": 1183, "text": "Calling the function by using name of the function followed by the Parentheses." }, { "code": null, "e": 1274, "s": 1263, "text": "Javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom/client'; function Parentheses() { return ( <h1> As usual we can call the function using name of the function followed by Parentheses </h1>); } const root = ReactDOM.createRoot(document.getElementById('root'));root.render(Parentheses());", "e": 1572, "s": 1274, "text": null }, { "code": null, "e": 1624, "s": 1572, "text": "Calling the function using the functional component" }, { "code": null, "e": 1635, "s": 1624, "text": "Javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom/client'; function Comp() { return ( <h1> As usual we can call the function using component call</h1>); } const root = ReactDOM.createRoot(document.getElementById('root'));root.render(<Comp/>);", "e": 1888, "s": 1635, "text": null }, { "code": null, "e": 2052, "s": 1888, "text": "Example: We can also use a functional component into another component. The below program is to demonstrates the use of functional components in other components. " }, { "code": null, "e": 2153, "s": 2052, "text": "Filepath- src index.js: Open your React project directory and edit the Index.js file from src folder" }, { "code": null, "e": 2164, "s": 2153, "text": "Javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom';import Welcome from './App'; ReactDOM.render( <React.StrictMode> <Welcome /> </React.StrictMode>, document.getElementById('root'));", "e": 2361, "s": 2164, "text": null }, { "code": null, "e": 2459, "s": 2361, "text": "Filepath- src App.js: Open your React project directory and edit the App.js file from src folder:" }, { "code": null, "e": 2470, "s": 2459, "text": "javascript" }, { "code": "import React from 'react'; const Welcome=()=>{return ( <h1>Welcome to GeeksforGeeks</h1> );} const functionExample=()=>{ return ( <Welcome/> );} export default functionExample;", "e": 2662, "s": 2470, "text": null }, { "code": null, "e": 2671, "s": 2662, "text": "Output: " }, { "code": null, "e": 2942, "s": 2671, "text": "Functional components lack a significant amount of features as compared to class-based components. The gap is made up with the help of a special ReactJS concept called “hooks”. Hooks are special functions that allow ReactJS features to be used in functional components. " }, { "code": null, "e": 3758, "s": 2942, "text": "Functional components do not have access to dedicated state variables like class-based components. The only “state” that a functional component effectively has access to are the props passed to it from its parent component. ReactJS has access to a special hook called useState() that can be used for giving the illusion of working with the state in functional components. The useState() is used to initialize only one state variable to initialize multiple state variables, multiple useState() declarations are required. The first value returned is the initial value of the state variable, while the second value returned is a reference to the function that updates it. When the state variable needs to be updated, it can be done by calling the update function and by updating the state variable directly inside it. " }, { "code": null, "e": 3818, "s": 3758, "text": "Example: Program to demonstrate the use of useState() hook." }, { "code": null, "e": 3920, "s": 3818, "text": "Filepath- src/index.js: Open your React project directory and edit the Index.js file from src folder:" }, { "code": null, "e": 3931, "s": 3920, "text": "Javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom';import Example from './App'; ReactDOM.render( <React.StrictMode> <Example /> </React.StrictMode>, document.getElementById('root'));", "e": 4128, "s": 3931, "text": null }, { "code": null, "e": 4226, "s": 4128, "text": "Filepath- src/App.js: Open your React project directory and edit the App.js file from src folder:" }, { "code": null, "e": 4237, "s": 4226, "text": "javascript" }, { "code": "import React, { useState } from 'react'; const Example=()=> { const [change, setChange] = useState(true); return ( <div> <button onClick = {() => setChange(!change)}> Click Here! </button> {change?<h1>Welcome to GeeksforGeeks</h1>: <h1>A Computer Science Portal for Geeks</h1>} </div> ); } export default Example;", "e": 4630, "s": 4237, "text": null }, { "code": null, "e": 4639, "s": 4630, "text": "Output: " }, { "code": null, "e": 5082, "s": 4639, "text": "Functional components do not have access to lifecycle functions like class-based components do since lifecycle functions need to be defined within the boundaries of a class. If lifecycle functions need to be used with functional components, a special React hook called useEffect() needs to be used. It is worth noting that useEffect() isn’t an exact duplicate of the lifecycle functions – it works and behaves in a slightly different manner. " }, { "code": null, "e": 5143, "s": 5082, "text": "Example: Program to demonstrate the use of useEffect() hook." }, { "code": null, "e": 5245, "s": 5143, "text": "Filepath- src/index.js: Open your React project directory and edit the index.js file from src folder:" }, { "code": null, "e": 5256, "s": 5245, "text": "Javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom';import Example from './App'; ReactDOM.render( <React.StrictMode> <Example /> </React.StrictMode>, document.getElementById('root'));", "e": 5453, "s": 5256, "text": null }, { "code": null, "e": 5551, "s": 5453, "text": "Filepath- src/App.js: Open your React project directory and edit the App.js file from src folder:" }, { "code": null, "e": 5562, "s": 5551, "text": "javascript" }, { "code": "import React, { useEffect } from 'react'; const Example=()=> { useEffect(() => { console.log(\"Mounting...\"); }); return ( <h1> Geeks....! </h1> );} export default Example;", "e": 5766, "s": 5562, "text": null }, { "code": null, "e": 5774, "s": 5766, "text": "Output:" }, { "code": null, "e": 6297, "s": 5774, "text": "Data is passed from the parent component to the child components in the form of props. ReactJS does not allow a component to modify its own props as a rule. The only way to modify the props is to change the props being passed to the child component. This is generally done by passing a reference of a function in the parent component to the child component. Props have more significance in functional components for the simple reason that functional components do not have access to a state, unlike class-based components." }, { "code": null, "e": 6347, "s": 6297, "text": "Example: Program to demonstrate the use of props." }, { "code": null, "e": 6450, "s": 6347, "text": "Filepatje- src/index.js: Open your React project directory and edit the Index.js file from src folder:" }, { "code": null, "e": 6461, "s": 6450, "text": "Javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom';import Example from './App'; ReactDOM.render( <React.StrictMode> <Example /> </React.StrictMode>, document.getElementById('root'));", "e": 6658, "s": 6461, "text": null }, { "code": null, "e": 6756, "s": 6658, "text": "Filepath- src/App.js: Open your React project directory and edit the App.js file from src folder:" }, { "code": null, "e": 6767, "s": 6756, "text": "javascript" }, { "code": "import React, { useState } from 'react';import props from 'prop-types'; const Example=()=> { return( <h1>{props.data}</h1> ); } function propsExample() { const [change, setChange] = useState(true); return ( <div> <button onClick = {() => setChange(!change)}> Click Here! </button> {change? <Example data=\"Welcome to GeeksforGeeks\"/>: <Example data=\"A Computer Science Portal for Geeks\"/>} </div> ); } export default Example;", "e": 7309, "s": 6767, "text": null }, { "code": null, "e": 7318, "s": 7309, "text": "Output: " }, { "code": null, "e": 7332, "s": 7318, "text": "shubhamyadav4" }, { "code": null, "e": 7347, "s": 7332, "text": "varshagumber28" }, { "code": null, "e": 7363, "s": 7347, "text": "nikhiljugale007" }, { "code": null, "e": 7379, "s": 7363, "text": "sushruthkontham" }, { "code": null, "e": 7393, "s": 7379, "text": "nikhatkhann11" }, { "code": null, "e": 7402, "s": 7393, "text": "react-js" }, { "code": null, "e": 7410, "s": 7402, "text": "ReactJS" }, { "code": null, "e": 7427, "s": 7410, "text": "Web Technologies" }, { "code": null, "e": 7525, "s": 7427, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7568, "s": 7525, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 7613, "s": 7568, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 7651, "s": 7613, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 7670, "s": 7651, "text": "ReactJS setState()" }, { "code": null, "e": 7738, "s": 7670, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 7800, "s": 7738, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 7833, "s": 7800, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 7894, "s": 7833, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7944, "s": 7894, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python | Pandas Index.unique()
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 Index.unique() function return unique values in the index. Uniques are returned in order of appearance, this does NOT sort. Syntax: Index.unique(level=None) Parameters :level : Only return values from specified level (for MultiIndex) Returns : Index without duplicates Example #1: Use Index.unique() function to return unique values in the index. # importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Harry', 'Mike', 'Arther', 'Nick', 'Harry', 'Arther'], name ='Student') # Print the Indexprint(idx) Output : Let’s find all the unique values in the Index. # find unique values in the indexidx.unique() Output :The function has returned a new index having all the unique values of the original index. Example #2: Use Index.unique() function to find the unique values in the index # importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index([21, 10, 30, 40, 50, 10, 50]) # Print the Indexprint(idx) Output : Let’s find all the unique values in the index # for finding the unique values in the indexidx.unique() Output :The function has returned a new index that contains all of the unique values in the original index. Python pandas-indexing Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Dec, 2018" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 373, "s": 242, "text": "Pandas Index.unique() function return unique values in the index. Uniques are returned in order of appearance, this does NOT sort." }, { "code": null, "e": 406, "s": 373, "text": "Syntax: Index.unique(level=None)" }, { "code": null, "e": 483, "s": 406, "text": "Parameters :level : Only return values from specified level (for MultiIndex)" }, { "code": null, "e": 518, "s": 483, "text": "Returns : Index without duplicates" }, { "code": null, "e": 596, "s": 518, "text": "Example #1: Use Index.unique() function to return unique values in the index." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Harry', 'Mike', 'Arther', 'Nick', 'Harry', 'Arther'], name ='Student') # Print the Indexprint(idx)", "e": 793, "s": 596, "text": null }, { "code": null, "e": 802, "s": 793, "text": "Output :" }, { "code": null, "e": 849, "s": 802, "text": "Let’s find all the unique values in the Index." }, { "code": "# find unique values in the indexidx.unique()", "e": 895, "s": 849, "text": null }, { "code": null, "e": 1072, "s": 895, "text": "Output :The function has returned a new index having all the unique values of the original index. Example #2: Use Index.unique() function to find the unique values in the index" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index([21, 10, 30, 40, 50, 10, 50]) # Print the Indexprint(idx)", "e": 1211, "s": 1072, "text": null }, { "code": null, "e": 1220, "s": 1211, "text": "Output :" }, { "code": null, "e": 1266, "s": 1220, "text": "Let’s find all the unique values in the index" }, { "code": "# for finding the unique values in the indexidx.unique()", "e": 1323, "s": 1266, "text": null }, { "code": null, "e": 1431, "s": 1323, "text": "Output :The function has returned a new index that contains all of the unique values in the original index." }, { "code": null, "e": 1454, "s": 1431, "text": "Python pandas-indexing" }, { "code": null, "e": 1468, "s": 1454, "text": "Python-pandas" }, { "code": null, "e": 1475, "s": 1468, "text": "Python" } ]
if-else statement in java
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. Following is the syntax of an if...else statement − if(Boolean_expression) { // Executes when the Boolean expression is true }else { // Executes when the Boolean expression is false } If the boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed. public class Test { public static void main(String args[]) { int x = 30; if( x < 20 ) { System.out.print("This is if statement"); }else { System.out.print("This is else statement"); } } } This will produce the following result − This is else statement An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement. When using if, else if, else statements there are a few points to keep in mind. An if can have zero or one else's and it must come after any else if's. An if can have zero or one else's and it must come after any else if's. An if can have zero to many else if's and they must come before the else. An if can have zero to many else if's and they must come before the else. Once an else if succeeds, none of the remaining else if's or else's will be tested. Once an else if succeeds, none of the remaining else if's or else's will be tested. Following is the syntax of an if...else statement − if(Boolean_expression 1) { // Executes when the Boolean expression 1 is true }else if(Boolean_expression 2) { // Executes when the Boolean expression 2 is true }else if(Boolean_expression 3) { // Executes when the Boolean expression 3 is true }else { // Executes when the none of the above condition is true. } public class Test { public static void main(String args[]) { int x = 30; if( x == 10 ) { System.out.print("Value of X is 10"); }else if( x == 20 ) { System.out.print("Value of X is 20"); }else if( x == 30 ) { System.out.print("Value of X is 30"); }else { System.out.print("This is else statement"); } } } This will produce the following result − Value of X is 30
[ { "code": null, "e": 2627, "s": 2511, "text": "An if statement can be followed by an optional else statement, which executes when the Boolean expression is false." }, { "code": null, "e": 2679, "s": 2627, "text": "Following is the syntax of an if...else statement −" }, { "code": null, "e": 2818, "s": 2679, "text": "if(Boolean_expression) {\n // Executes when the Boolean expression is true\n}else {\n // Executes when the Boolean expression is false\n}\n" }, { "code": null, "e": 2954, "s": 2818, "text": "If the boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed." }, { "code": null, "e": 3192, "s": 2954, "text": "public class Test {\n\n public static void main(String args[]) {\n int x = 30;\n\n if( x < 20 ) {\n System.out.print(\"This is if statement\");\n }else {\n System.out.print(\"This is else statement\");\n }\n }\n}" }, { "code": null, "e": 3233, "s": 3192, "text": "This will produce the following result −" }, { "code": null, "e": 3257, "s": 3233, "text": "This is else statement\n" }, { "code": null, "e": 3415, "s": 3257, "text": "An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement." }, { "code": null, "e": 3495, "s": 3415, "text": "When using if, else if, else statements there are a few points to keep in mind." }, { "code": null, "e": 3567, "s": 3495, "text": "An if can have zero or one else's and it must come after any else if's." }, { "code": null, "e": 3639, "s": 3567, "text": "An if can have zero or one else's and it must come after any else if's." }, { "code": null, "e": 3713, "s": 3639, "text": "An if can have zero to many else if's and they must come before the else." }, { "code": null, "e": 3787, "s": 3713, "text": "An if can have zero to many else if's and they must come before the else." }, { "code": null, "e": 3871, "s": 3787, "text": "Once an else if succeeds, none of the remaining else if's or else's will be tested." }, { "code": null, "e": 3955, "s": 3871, "text": "Once an else if succeeds, none of the remaining else if's or else's will be tested." }, { "code": null, "e": 4007, "s": 3955, "text": "Following is the syntax of an if...else statement −" }, { "code": null, "e": 4331, "s": 4007, "text": "if(Boolean_expression 1) {\n // Executes when the Boolean expression 1 is true\n}else if(Boolean_expression 2) {\n // Executes when the Boolean expression 2 is true\n}else if(Boolean_expression 3) {\n // Executes when the Boolean expression 3 is true\n}else {\n // Executes when the none of the above condition is true.\n}\n" }, { "code": null, "e": 4716, "s": 4331, "text": "public class Test {\n\n public static void main(String args[]) {\n int x = 30;\n\n if( x == 10 ) {\n System.out.print(\"Value of X is 10\");\n }else if( x == 20 ) {\n System.out.print(\"Value of X is 20\");\n }else if( x == 30 ) {\n System.out.print(\"Value of X is 30\");\n }else {\n System.out.print(\"This is else statement\");\n }\n }\n}" }, { "code": null, "e": 4757, "s": 4716, "text": "This will produce the following result −" } ]
Decimal Struct in C#
15 Feb, 2019 In C#, Decimal Struct class is used to represent a decimal floating-point number. The range of decimal numbers is +79,228,162,514,264,337,593,543,950,335 to -79,228,162,514,264,337,593,543,950,335. Due to its wide range, it is generally used for financial calculations which required large numbers of significant integral and fractional digits and no round-off errors. You can also perform the mathematical operations on Decimal type like addition, subtraction, division, multiplication, etc. Example: // C# program to illustrate the// use of MaxValue and MinValue fieldusing System; public class GFG { // Main method static public void Main() { // Display the Minimum and Maximum values Console.WriteLine("Display Maximum value "+ "of Decimal: {0}", Decimal.MaxValue); Console.WriteLine("Display Minimum value of "+ "Decimal: {0}", Decimal.MinValue); }} Display Maximum value of Decimal: 79228162514264337593543950335 Display Minimum value of Decimal: -79228162514264337593543950335 Example: // C# program to illustrate the// use of Add(Decimal, Decimal)// methodusing System; class GFG { // Main method static public void Main() { // Addition of two Decimal values // Using Add() method Decimal val1 = 349; Decimal val2 = 590; Decimal result; result = Decimal.Add(val1, val2); // Display the result Console.WriteLine("Addition is: {0}", result); }} Addition is: 939 Example: // C# program to illustrate the// use of Decrement and Increment// operatorusing System; class GFG { static public void Main() { Decimal myval1 = 1000; Decimal myval2 = 10000; // Using Decrement operator we decrease myval1 by 1 Console.WriteLine("My value 1 is: {0}", myval1); Console.WriteLine("Decrease myval1 by 1:{0}", --myval1); Console.WriteLine(); // Using Increment operator we increase myval2 by 1 Console.WriteLine("My value 2 is: {0}", myval2); Console.WriteLine("Increase myval2 by 1:{0}", ++myval2); }} My value 1 is: 1000 Decrease myval1 by 1:999 My value 2 is: 10000 Increase myval2 by 1:10001 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.decimal?view=netframework-4.7.2 CSharp-Decimal-Struct C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Multiple inheritance using interfaces Introduction to .NET Framework Differences Between .NET Core and .NET Framework C# | Delegates C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method C# | Arrays Extension Method in C# C# | List Class
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Feb, 2019" }, { "code": null, "e": 521, "s": 28, "text": "In C#, Decimal Struct class is used to represent a decimal floating-point number. The range of decimal numbers is +79,228,162,514,264,337,593,543,950,335 to -79,228,162,514,264,337,593,543,950,335. Due to its wide range, it is generally used for financial calculations which required large numbers of significant integral and fractional digits and no round-off errors. You can also perform the mathematical operations on Decimal type like addition, subtraction, division, multiplication, etc." }, { "code": null, "e": 530, "s": 521, "text": "Example:" }, { "code": "// C# program to illustrate the// use of MaxValue and MinValue fieldusing System; public class GFG { // Main method static public void Main() { // Display the Minimum and Maximum values Console.WriteLine(\"Display Maximum value \"+ \"of Decimal: {0}\", Decimal.MaxValue); Console.WriteLine(\"Display Minimum value of \"+ \"Decimal: {0}\", Decimal.MinValue); }}", "e": 956, "s": 530, "text": null }, { "code": null, "e": 1086, "s": 956, "text": "Display Maximum value of Decimal: 79228162514264337593543950335\nDisplay Minimum value of Decimal: -79228162514264337593543950335\n" }, { "code": null, "e": 1095, "s": 1086, "text": "Example:" }, { "code": "// C# program to illustrate the// use of Add(Decimal, Decimal)// methodusing System; class GFG { // Main method static public void Main() { // Addition of two Decimal values // Using Add() method Decimal val1 = 349; Decimal val2 = 590; Decimal result; result = Decimal.Add(val1, val2); // Display the result Console.WriteLine(\"Addition is: {0}\", result); }}", "e": 1528, "s": 1095, "text": null }, { "code": null, "e": 1546, "s": 1528, "text": "Addition is: 939\n" }, { "code": null, "e": 1555, "s": 1546, "text": "Example:" }, { "code": "// C# program to illustrate the// use of Decrement and Increment// operatorusing System; class GFG { static public void Main() { Decimal myval1 = 1000; Decimal myval2 = 10000; // Using Decrement operator we decrease myval1 by 1 Console.WriteLine(\"My value 1 is: {0}\", myval1); Console.WriteLine(\"Decrease myval1 by 1:{0}\", --myval1); Console.WriteLine(); // Using Increment operator we increase myval2 by 1 Console.WriteLine(\"My value 2 is: {0}\", myval2); Console.WriteLine(\"Increase myval2 by 1:{0}\", ++myval2); }}", "e": 2150, "s": 1555, "text": null }, { "code": null, "e": 2245, "s": 2150, "text": "My value 1 is: 1000\nDecrease myval1 by 1:999\n\nMy value 2 is: 10000\nIncrease myval2 by 1:10001\n" }, { "code": null, "e": 2256, "s": 2245, "text": "Reference:" }, { "code": null, "e": 2339, "s": 2256, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.decimal?view=netframework-4.7.2" }, { "code": null, "e": 2361, "s": 2339, "text": "CSharp-Decimal-Struct" }, { "code": null, "e": 2364, "s": 2361, "text": "C#" }, { "code": null, "e": 2462, "s": 2364, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2490, "s": 2462, "text": "C# Dictionary with examples" }, { "code": null, "e": 2533, "s": 2490, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 2564, "s": 2533, "text": "Introduction to .NET Framework" }, { "code": null, "e": 2613, "s": 2564, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 2628, "s": 2613, "text": "C# | Delegates" }, { "code": null, "e": 2668, "s": 2628, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 2690, "s": 2668, "text": "C# | Replace() Method" }, { "code": null, "e": 2702, "s": 2690, "text": "C# | Arrays" }, { "code": null, "e": 2725, "s": 2702, "text": "Extension Method in C#" } ]
Button in Android using Jetpack Compose
08 Sep, 2021 Jetpack Compose is a new toolkit provided by Google. This is useful for designing beautiful UI designs. A Button is a UI component in Android which is used to navigate between different screens. With the help of a button, the user can interact with your app and perform multiple actions inside your application. In this article, we will take a look at the implementation of buttons in Android using Jetpack compose. Attribute Description Step 1: Create a New Project. To create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose. Step 2: Working with the MainActivity.kt file Navigate to the app > java > your app’s package name and open the MainActivity.kt file. Inside that file add the below code to it. Comments are added inside the code to understand the code in more detail. Kotlin import android.graphics.drawable.shapes.Shapeimport android.media.Imageimport android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.Imageimport androidx.compose.foundation.Textimport androidx.compose.foundation.layout.*import androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.text.KeyboardOptionsimport androidx.compose.material.*import androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.AccountCircleimport androidx.compose.material.icons.filled.Infoimport androidx.compose.material.icons.filled.Phoneimport androidx.compose.runtime.*import androidx.compose.runtime.savedinstancestate.savedInstanceStateimport androidx.compose.ui.Alignmentimport androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.platform.setContentimport androidx.compose.ui.res.imageResourceimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport com.example.gfgapp.ui.GFGAppThemeimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.SolidColorimport androidx.compose.ui.platform.ContextAmbientimport androidx.compose.ui.res.colorResourceimport androidx.compose.ui.text.TextStyleimport androidx.compose.ui.text.font.FontFamilyimport androidx.compose.ui.text.input.*import androidx.compose.ui.unit.Dpimport androidx.compose.ui.unit.TextUnit class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { GFGAppTheme { // A surface container using the 'background' // color from the theme Surface(color = MaterialTheme.colors.background) { // at below line we are calling // our function for button. MyButton(); } } } }} // @Preview function is use to see preview// for our composable function in preview section.@Preview(showBackground = true)@Composablefun DefaultPreview() { GFGAppTheme { // we are passing our composable // function to display its preview. MyButton(); }} @Composablefun MyButton() { Column( // we are using column to align our // imageview to center of the screen. modifier = Modifier.fillMaxWidth().fillMaxHeight(), // below line is used for specifying // vertical arrangement. verticalArrangement = Arrangement.Center, // below line is used for specifying // horizontal arrangement. horizontalAlignment = Alignment.CenterHorizontally, ) { // below line is use to get // the context for our app. val context = ContextAmbient.current // below line is use to create a button. Button( // below line is use to add onclick // parameter for our button onclick onClick = { // when user is clicking the button // we are displaying a toast message. Toast.makeText(context, "Welcome to Geeks for Geeks", Toast.LENGTH_LONG).show() }, // in below line we are using modifier // which is use to add padding to our button modifier = Modifier.padding(all = Dp(10F)), // below line is use to set or // button as enable or disable. enabled = true, // below line is use to // add border to our button. border = BorderStroke(width = 1.dp, brush = SolidColor(Color.Blue)), // below line is use to add shape for our button. shape = MaterialTheme.shapes.medium, ) // below line is use to // add text on our button { Text(text = "Geeks for Geeks", color = Color.White) } }} chardieaj Android-Jetpack Technical Scripter 2020 Android Kotlin Technical Scripter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components How to Communicate Between Fragments in Android? Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android How to Add Views Dynamically and Store Data in Arraylist in Android? Android UI Layouts Kotlin Array How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Sep, 2021" }, { "code": null, "e": 445, "s": 28, "text": "Jetpack Compose is a new toolkit provided by Google. This is useful for designing beautiful UI designs. A Button is a UI component in Android which is used to navigate between different screens. With the help of a button, the user can interact with your app and perform multiple actions inside your application. In this article, we will take a look at the implementation of buttons in Android using Jetpack compose. " }, { "code": null, "e": 455, "s": 445, "text": "Attribute" }, { "code": null, "e": 467, "s": 455, "text": "Description" }, { "code": null, "e": 497, "s": 467, "text": "Step 1: Create a New Project." }, { "code": null, "e": 657, "s": 497, "text": "To create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose." }, { "code": null, "e": 703, "s": 657, "text": "Step 2: Working with the MainActivity.kt file" }, { "code": null, "e": 908, "s": 703, "text": "Navigate to the app > java > your app’s package name and open the MainActivity.kt file. Inside that file add the below code to it. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 915, "s": 908, "text": "Kotlin" }, { "code": "import android.graphics.drawable.shapes.Shapeimport android.media.Imageimport android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.Imageimport androidx.compose.foundation.Textimport androidx.compose.foundation.layout.*import androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.text.KeyboardOptionsimport androidx.compose.material.*import androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.AccountCircleimport androidx.compose.material.icons.filled.Infoimport androidx.compose.material.icons.filled.Phoneimport androidx.compose.runtime.*import androidx.compose.runtime.savedinstancestate.savedInstanceStateimport androidx.compose.ui.Alignmentimport androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.platform.setContentimport androidx.compose.ui.res.imageResourceimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport com.example.gfgapp.ui.GFGAppThemeimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.SolidColorimport androidx.compose.ui.platform.ContextAmbientimport androidx.compose.ui.res.colorResourceimport androidx.compose.ui.text.TextStyleimport androidx.compose.ui.text.font.FontFamilyimport androidx.compose.ui.text.input.*import androidx.compose.ui.unit.Dpimport androidx.compose.ui.unit.TextUnit class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { GFGAppTheme { // A surface container using the 'background' // color from the theme Surface(color = MaterialTheme.colors.background) { // at below line we are calling // our function for button. MyButton(); } } } }} // @Preview function is use to see preview// for our composable function in preview section.@Preview(showBackground = true)@Composablefun DefaultPreview() { GFGAppTheme { // we are passing our composable // function to display its preview. MyButton(); }} @Composablefun MyButton() { Column( // we are using column to align our // imageview to center of the screen. modifier = Modifier.fillMaxWidth().fillMaxHeight(), // below line is used for specifying // vertical arrangement. verticalArrangement = Arrangement.Center, // below line is used for specifying // horizontal arrangement. horizontalAlignment = Alignment.CenterHorizontally, ) { // below line is use to get // the context for our app. val context = ContextAmbient.current // below line is use to create a button. Button( // below line is use to add onclick // parameter for our button onclick onClick = { // when user is clicking the button // we are displaying a toast message. Toast.makeText(context, \"Welcome to Geeks for Geeks\", Toast.LENGTH_LONG).show() }, // in below line we are using modifier // which is use to add padding to our button modifier = Modifier.padding(all = Dp(10F)), // below line is use to set or // button as enable or disable. enabled = true, // below line is use to // add border to our button. border = BorderStroke(width = 1.dp, brush = SolidColor(Color.Blue)), // below line is use to add shape for our button. shape = MaterialTheme.shapes.medium, ) // below line is use to // add text on our button { Text(text = \"Geeks for Geeks\", color = Color.White) } }}", "e": 5053, "s": 915, "text": null }, { "code": null, "e": 5068, "s": 5058, "text": "chardieaj" }, { "code": null, "e": 5084, "s": 5068, "text": "Android-Jetpack" }, { "code": null, "e": 5108, "s": 5084, "text": "Technical Scripter 2020" }, { "code": null, "e": 5116, "s": 5108, "text": "Android" }, { "code": null, "e": 5123, "s": 5116, "text": "Kotlin" }, { "code": null, "e": 5142, "s": 5123, "text": "Technical Scripter" }, { "code": null, "e": 5150, "s": 5142, "text": "Android" }, { "code": null, "e": 5248, "s": 5150, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5317, "s": 5248, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 5349, "s": 5317, "text": "Android SDK and it's Components" }, { "code": null, "e": 5398, "s": 5349, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 5437, "s": 5398, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 5479, "s": 5437, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 5548, "s": 5479, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 5567, "s": 5548, "text": "Android UI Layouts" }, { "code": null, "e": 5580, "s": 5567, "text": "Kotlin Array" }, { "code": null, "e": 5629, "s": 5580, "text": "How to Communicate Between Fragments in Android?" } ]
Multi-dimensional lists in Python
09 Dec, 2018 There can be more than one additional dimension to lists in Python. Keeping in mind that a list can hold other lists, that basic principle can be applied over and over. Multi-dimensional lists are the lists within lists. Usually, a dictionary will be the better choice rather than a multi-dimensional list in Python. Approach 1: # Python program to demonstrate printing# of complete multidimensional lista = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]print(a) [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]] Approach 2: Accessing with the help of loop. # Python program to demonstrate printing# of complete multidimensional list row# by row.a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]for record in a: print(record) [2, 4, 6, 8, 10] [3, 6, 9, 12, 15] [4, 8, 12, 16, 20] Approach 3: Accessing using square brackets.Example: # Python program to demonstrate that we# can access multidimensional list using# square bracketsa = [ [2, 4, 6, 8 ], [ 1, 3, 5, 7 ], [ 8, 6, 4, 2 ], [ 7, 5, 3, 1 ] ] for i in range(len(a)) : for j in range(len(a[i])) : print(a[i][j], end=" ") print() 2 4 6 8 1 3 5 7 8 6 4 2 7 5 3 1 # Python program to create a m x n matrix# with all 0sm = 4n = 5 a = [[0 for x in range(n)] for x in range(m)]print(a) [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] 1. append(): Adds an element at the end of the list.Example: # Adding a sublist a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]a.append([5, 10, 15, 20, 25])print(a) [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [5, 10, 15, 20, 25]] 2. extend(): Add the elements of a list (or any iterable), to the end of the current list. # Extending a sublist a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]a[0].extend([12, 14, 16, 18])print(a) [[2, 4, 6, 8, 10, 12, 14, 16, 18], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]] 3. reverse(): Reverses the order of the list. # Reversing a sublist a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]a[2].reverse()print(a) [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [20, 16, 12, 8, 4]] Picked Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Dec, 2018" }, { "code": null, "e": 371, "s": 54, "text": "There can be more than one additional dimension to lists in Python. Keeping in mind that a list can hold other lists, that basic principle can be applied over and over. Multi-dimensional lists are the lists within lists. Usually, a dictionary will be the better choice rather than a multi-dimensional list in Python." }, { "code": null, "e": 383, "s": 371, "text": "Approach 1:" }, { "code": "# Python program to demonstrate printing# of complete multidimensional lista = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]print(a)", "e": 528, "s": 383, "text": null }, { "code": null, "e": 587, "s": 528, "text": "[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]\n" }, { "code": null, "e": 632, "s": 587, "text": "Approach 2: Accessing with the help of loop." }, { "code": "# Python program to demonstrate printing# of complete multidimensional list row# by row.a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]for record in a: print(record)", "e": 815, "s": 632, "text": null }, { "code": null, "e": 870, "s": 815, "text": "[2, 4, 6, 8, 10]\n[3, 6, 9, 12, 15]\n[4, 8, 12, 16, 20]\n" }, { "code": null, "e": 923, "s": 870, "text": "Approach 3: Accessing using square brackets.Example:" }, { "code": "# Python program to demonstrate that we# can access multidimensional list using# square bracketsa = [ [2, 4, 6, 8 ], [ 1, 3, 5, 7 ], [ 8, 6, 4, 2 ], [ 7, 5, 3, 1 ] ] for i in range(len(a)) : for j in range(len(a[i])) : print(a[i][j], end=\" \") print() ", "e": 1215, "s": 923, "text": null }, { "code": null, "e": 1251, "s": 1215, "text": "2 4 6 8 \n1 3 5 7 \n8 6 4 2 \n7 5 3 1\n" }, { "code": "# Python program to create a m x n matrix# with all 0sm = 4n = 5 a = [[0 for x in range(n)] for x in range(m)]print(a)", "e": 1371, "s": 1251, "text": null }, { "code": null, "e": 1441, "s": 1371, "text": "[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]\n" }, { "code": null, "e": 1502, "s": 1441, "text": "1. append(): Adds an element at the end of the list.Example:" }, { "code": "# Adding a sublist a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]a.append([5, 10, 15, 20, 25])print(a)", "e": 1621, "s": 1502, "text": null }, { "code": null, "e": 1701, "s": 1621, "text": "[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [5, 10, 15, 20, 25]]\n" }, { "code": null, "e": 1792, "s": 1701, "text": "2. extend(): Add the elements of a list (or any iterable), to the end of the current list." }, { "code": "# Extending a sublist a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]a[0].extend([12, 14, 16, 18])print(a)", "e": 1915, "s": 1792, "text": null }, { "code": null, "e": 1990, "s": 1915, "text": "[[2, 4, 6, 8, 10, 12, 14, 16, 18], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]\n" }, { "code": null, "e": 2036, "s": 1990, "text": "3. reverse(): Reverses the order of the list." }, { "code": "# Reversing a sublist a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]a[2].reverse()print(a)", "e": 2144, "s": 2036, "text": null }, { "code": null, "e": 2203, "s": 2144, "text": "[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [20, 16, 12, 8, 4]]\n" }, { "code": null, "e": 2210, "s": 2203, "text": "Picked" }, { "code": null, "e": 2231, "s": 2210, "text": "Python list-programs" }, { "code": null, "e": 2243, "s": 2231, "text": "python-list" }, { "code": null, "e": 2250, "s": 2243, "text": "Python" }, { "code": null, "e": 2262, "s": 2250, "text": "python-list" }, { "code": null, "e": 2360, "s": 2262, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2402, "s": 2360, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2424, "s": 2402, "text": "Enumerate() in Python" }, { "code": null, "e": 2450, "s": 2424, "text": "Python String | replace()" }, { "code": null, "e": 2482, "s": 2450, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2511, "s": 2482, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2538, "s": 2511, "text": "Python Classes and Objects" }, { "code": null, "e": 2559, "s": 2538, "text": "Python OOPs Concepts" }, { "code": null, "e": 2595, "s": 2559, "text": "Convert integer to string in Python" }, { "code": null, "e": 2618, "s": 2595, "text": "Introduction To PYTHON" } ]
p5.js | mouseWheel() Function
29 Jan, 2020 The mouseWheel() function is invoked whenever a mouse or touchpad scroll causes a vertical mouse wheel event. This event can be accessed to determine the properties of the scroll. The delta property returns the amount of the scroll that took place. This value can be positive or negative depending on the direction of the scroll. The callback function may have to end with the “return false;” statement to prevent any default behaviors that may be associated with scrolling on different browsers. Syntax: mouseWheel( event ) Parameters: This function accepts a single parameter as mentioned above and described below: event: This is an optional WheelEvent callback argument, that can be used to access scroll details. Below examples illustrate the mouseWheel() function in p5.js: Example 1: Using the scroll event to change the color when scrolled let red = 0; function setup() { createCanvas(750, 300); textSize(24);} function draw() { clear(); // Apply fill based on the // red component fill(red, 0, 0) text("Scroll the mouse wheel to " + "change the red component" + " of the color", 20, 20); circle(150, 150, 200);} function mouseWheel(event) { // Change the red value according // to the scroll delta value red += event.delta;} Output: Example 2: Displaying the scroll properties let scrollDelta = 0; function setup() { createCanvas(500, 200); textSize(24); text("Scroll the mouse to see the" + " scroll details.", 10, 20);} function mouseWheel(event) { scrollDelta = event.delta; clear(); deltaString = "Current mouse delta is: " + scrollDelta; text(deltaString, 10, 20); if (scrollDelta > 0) { text("You are scrolling downwards", 10, 40); } else { text("You are scrolling upwards", 10, 40); }} Output: Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ Reference: https://p5js.org/reference/#/p5/mouseWheel JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property How to append HTML code to a div using JavaScript ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jan, 2020" }, { "code": null, "e": 358, "s": 28, "text": "The mouseWheel() function is invoked whenever a mouse or touchpad scroll causes a vertical mouse wheel event. This event can be accessed to determine the properties of the scroll. The delta property returns the amount of the scroll that took place. This value can be positive or negative depending on the direction of the scroll." }, { "code": null, "e": 525, "s": 358, "text": "The callback function may have to end with the “return false;” statement to prevent any default behaviors that may be associated with scrolling on different browsers." }, { "code": null, "e": 533, "s": 525, "text": "Syntax:" }, { "code": null, "e": 553, "s": 533, "text": "mouseWheel( event )" }, { "code": null, "e": 646, "s": 553, "text": "Parameters: This function accepts a single parameter as mentioned above and described below:" }, { "code": null, "e": 746, "s": 646, "text": "event: This is an optional WheelEvent callback argument, that can be used to access scroll details." }, { "code": null, "e": 808, "s": 746, "text": "Below examples illustrate the mouseWheel() function in p5.js:" }, { "code": null, "e": 876, "s": 808, "text": "Example 1: Using the scroll event to change the color when scrolled" }, { "code": "let red = 0; function setup() { createCanvas(750, 300); textSize(24);} function draw() { clear(); // Apply fill based on the // red component fill(red, 0, 0) text(\"Scroll the mouse wheel to \" + \"change the red component\" + \" of the color\", 20, 20); circle(150, 150, 200);} function mouseWheel(event) { // Change the red value according // to the scroll delta value red += event.delta;}", "e": 1337, "s": 876, "text": null }, { "code": null, "e": 1345, "s": 1337, "text": "Output:" }, { "code": null, "e": 1389, "s": 1345, "text": "Example 2: Displaying the scroll properties" }, { "code": "let scrollDelta = 0; function setup() { createCanvas(500, 200); textSize(24); text(\"Scroll the mouse to see the\" + \" scroll details.\", 10, 20);} function mouseWheel(event) { scrollDelta = event.delta; clear(); deltaString = \"Current mouse delta is: \" + scrollDelta; text(deltaString, 10, 20); if (scrollDelta > 0) { text(\"You are scrolling downwards\", 10, 40); } else { text(\"You are scrolling upwards\", 10, 40); }}", "e": 1893, "s": 1389, "text": null }, { "code": null, "e": 1901, "s": 1893, "text": "Output:" }, { "code": null, "e": 2038, "s": 1901, "text": "Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/" }, { "code": null, "e": 2092, "s": 2038, "text": "Reference: https://p5js.org/reference/#/p5/mouseWheel" }, { "code": null, "e": 2109, "s": 2092, "text": "JavaScript-p5.js" }, { "code": null, "e": 2120, "s": 2109, "text": "JavaScript" }, { "code": null, "e": 2137, "s": 2120, "text": "Web Technologies" }, { "code": null, "e": 2235, "s": 2137, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2296, "s": 2235, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2368, "s": 2296, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2408, "s": 2368, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2461, "s": 2408, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2513, "s": 2461, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 2575, "s": 2513, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2608, "s": 2575, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2669, "s": 2608, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2719, "s": 2669, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
MySQL | LEAD() and LAG() Function
04 Sep, 2021 The LEAD() and LAG() function in MySQL are used to get preceding and succeeding value of any row within its partition. These functions are termed as nonaggregate Window functions. The Window functions are those functions which perform operations for each row of the partition or window. These functions produce the result for each query row unlikely to the aggregate functions that group them and results in a single row. The row on which operation occur is termed as current row. The set of rows which are related to current row or using which function operates on current row is termed as Window. The LAG() function is used to get value from row that precedes the current row. The LEAD() function is used to get value from row that succeeds the current row. Syntax: For LEAD() function- LEAD(expr, N, default) OVER (Window_specification | Window_name) For LAG() function- LAG(expr, N, default) OVER (Window_specification | Window_name) The N and default argument in the function is optional. Parameters used: expr: It can be a column or any bulit-in function.N: It is a positive value which determine number of rows preceding/succeeding the current row. If it is omitted in query then its default value is 1.default: It is the default value return by function in-case no row precedes/succeedes the current row by N rows. If it is missing then it is by default NULL.OVER(): It defines how rows are partitioned into groups. If OVER() is empty then function compute result using all rows.Window_specification: It consist of query partition clause which determines how the query rows are partitioned and ordered.Window_name: If window is specified elsewhere in the query then it is referenced using this Window_name. expr: It can be a column or any bulit-in function. N: It is a positive value which determine number of rows preceding/succeeding the current row. If it is omitted in query then its default value is 1. default: It is the default value return by function in-case no row precedes/succeedes the current row by N rows. If it is missing then it is by default NULL. OVER(): It defines how rows are partitioned into groups. If OVER() is empty then function compute result using all rows. Window_specification: It consist of query partition clause which determines how the query rows are partitioned and ordered. Window_name: If window is specified elsewhere in the query then it is referenced using this Window_name. Example: Consider a “contest” table:- In the above table, “c_id” represents contest id and “start_date” and “end_date” represents starting and ending date of contest respectively. Problem description: We have to find number of days a contest will collapse with the next contest i.e no. of days on which both contests are held. Query: Select c_id, start_date, end_date, end_date - lead (start_date) over (order by start_date) + 1 as 'no_of_days' from contest; In the above query “end_date” return ending date of the current contest and lead(start_date) return next contest starting date. So, the difference between these dates plus 1 will return no. of days the contest will collide. Here, window specification is given by “order by” clause, which represent that lead() function will operate on table order by their “start_date” in increasing order. Since their is no partition clause so, whole table is taken as a single window. Output: Since, there is no contest after contest 7 i.e (c_id=7). So, lead(start_date) returns NULL value. Note:The LEAD() and LAG() function are always used with OVER(). Missing of an over clause will raise an error. nidhi_biet gabaa406 ruhelaa48 adnanirshad158 DBMS-SQL mysql SQL-Functions SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL Trigger | Student Database SQL Interview Questions SQL | Views Difference between DELETE, DROP and TRUNCATE Window functions in SQL MySQL | Group_CONCAT() Function SQL | GROUP BY Difference between DDL and DML in DBMS
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Sep, 2021" }, { "code": null, "e": 208, "s": 28, "text": "The LEAD() and LAG() function in MySQL are used to get preceding and succeeding value of any row within its partition. These functions are termed as nonaggregate Window functions." }, { "code": null, "e": 450, "s": 208, "text": "The Window functions are those functions which perform operations for each row of the partition or window. These functions produce the result for each query row unlikely to the aggregate functions that group them and results in a single row." }, { "code": null, "e": 509, "s": 450, "text": "The row on which operation occur is termed as current row." }, { "code": null, "e": 627, "s": 509, "text": "The set of rows which are related to current row or using which function operates on current row is termed as Window." }, { "code": null, "e": 707, "s": 627, "text": "The LAG() function is used to get value from row that precedes the current row." }, { "code": null, "e": 788, "s": 707, "text": "The LEAD() function is used to get value from row that succeeds the current row." }, { "code": null, "e": 819, "s": 788, "text": "Syntax: For LEAD() function- " }, { "code": null, "e": 895, "s": 819, "text": "LEAD(expr, N, default) \n OVER (Window_specification | Window_name)" }, { "code": null, "e": 917, "s": 895, "text": "For LAG() function- " }, { "code": null, "e": 992, "s": 917, "text": "LAG(expr, N, default) \n OVER (Window_specification | Window_name)" }, { "code": null, "e": 1048, "s": 992, "text": "The N and default argument in the function is optional." }, { "code": null, "e": 1067, "s": 1048, "text": "Parameters used: " }, { "code": null, "e": 1771, "s": 1067, "text": "expr: It can be a column or any bulit-in function.N: It is a positive value which determine number of rows preceding/succeeding the current row. If it is omitted in query then its default value is 1.default: It is the default value return by function in-case no row precedes/succeedes the current row by N rows. If it is missing then it is by default NULL.OVER(): It defines how rows are partitioned into groups. If OVER() is empty then function compute result using all rows.Window_specification: It consist of query partition clause which determines how the query rows are partitioned and ordered.Window_name: If window is specified elsewhere in the query then it is referenced using this Window_name." }, { "code": null, "e": 1822, "s": 1771, "text": "expr: It can be a column or any bulit-in function." }, { "code": null, "e": 1972, "s": 1822, "text": "N: It is a positive value which determine number of rows preceding/succeeding the current row. If it is omitted in query then its default value is 1." }, { "code": null, "e": 2130, "s": 1972, "text": "default: It is the default value return by function in-case no row precedes/succeedes the current row by N rows. If it is missing then it is by default NULL." }, { "code": null, "e": 2251, "s": 2130, "text": "OVER(): It defines how rows are partitioned into groups. If OVER() is empty then function compute result using all rows." }, { "code": null, "e": 2375, "s": 2251, "text": "Window_specification: It consist of query partition clause which determines how the query rows are partitioned and ordered." }, { "code": null, "e": 2480, "s": 2375, "text": "Window_name: If window is specified elsewhere in the query then it is referenced using this Window_name." }, { "code": null, "e": 2520, "s": 2480, "text": "Example: Consider a “contest” table:- " }, { "code": null, "e": 2664, "s": 2520, "text": "In the above table, “c_id” represents contest id and “start_date” and “end_date” represents starting and ending date of contest respectively. " }, { "code": null, "e": 2811, "s": 2664, "text": "Problem description: We have to find number of days a contest will collapse with the next contest i.e no. of days on which both contests are held." }, { "code": null, "e": 2820, "s": 2811, "text": " Query: " }, { "code": null, "e": 2999, "s": 2820, "text": "Select c_id, start_date, end_date, \n end_date - lead (start_date) \n over (order by start_date) \n + 1 as 'no_of_days' \n from contest;" }, { "code": null, "e": 3224, "s": 2999, "text": " In the above query “end_date” return ending date of the current contest and lead(start_date) return next contest starting date. So, the difference between these dates plus 1 will return no. of days the contest will collide." }, { "code": null, "e": 3471, "s": 3224, "text": " Here, window specification is given by “order by” clause, which represent that lead() function will operate on table order by their “start_date” in increasing order. Since their is no partition clause so, whole table is taken as a single window." }, { "code": null, "e": 3479, "s": 3471, "text": "Output:" }, { "code": null, "e": 3579, "s": 3481, "text": "Since, there is no contest after contest 7 i.e (c_id=7). So, lead(start_date) returns NULL value." }, { "code": null, "e": 3691, "s": 3579, "text": "Note:The LEAD() and LAG() function are always used with OVER(). Missing of an over clause will raise an error. " }, { "code": null, "e": 3702, "s": 3691, "text": "nidhi_biet" }, { "code": null, "e": 3711, "s": 3702, "text": "gabaa406" }, { "code": null, "e": 3721, "s": 3711, "text": "ruhelaa48" }, { "code": null, "e": 3736, "s": 3721, "text": "adnanirshad158" }, { "code": null, "e": 3745, "s": 3736, "text": "DBMS-SQL" }, { "code": null, "e": 3751, "s": 3745, "text": "mysql" }, { "code": null, "e": 3765, "s": 3751, "text": "SQL-Functions" }, { "code": null, "e": 3769, "s": 3765, "text": "SQL" }, { "code": null, "e": 3773, "s": 3769, "text": "SQL" }, { "code": null, "e": 3871, "s": 3773, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3882, "s": 3871, "text": "CTE in SQL" }, { "code": null, "e": 3948, "s": 3882, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 3979, "s": 3948, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 4003, "s": 3979, "text": "SQL Interview Questions" }, { "code": null, "e": 4015, "s": 4003, "text": "SQL | Views" }, { "code": null, "e": 4060, "s": 4015, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 4084, "s": 4060, "text": "Window functions in SQL" }, { "code": null, "e": 4116, "s": 4084, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 4131, "s": 4116, "text": "SQL | GROUP BY" } ]
pandas.merge_asof() function in Python
14 Aug, 2020 This method is used to perform an asof merge. This is similar to a left-join except that we match on nearest key rather than equal keys. Both DataFrames must be sorted by the key. Syntax : pandas.merge_asof(left, right, on=None, left_on=None, right_on=None, left_index=False, right_index=False, by=None, left_by=None, right_by=None, suffixes=(‘_x’, ‘_y’), tolerance=None, allow_exact_matches=True, direction=’backward’, ) Parameters : left, right : DataFrame on : label, Field name to join on. Must be found in both DataFrames. left_on : label, Field name to join on in left DataFrame. right_on : label, Field name to join on in right DataFrame. left_index : boolean, Use the index of the left DataFrame as the join key. right_index : boolean, Use the index of the right DataFrame as the join key. Below is the implementation of the above method with some examples : Example 1 : Python3 # importing packageimport pandas # creating dataleft = pandas.DataFrame({'a': [1, 5, 10], 'left_val': ['a', 'b', 'c']}) right = pandas.DataFrame({'a': [1, 2, 3, 6, 7], 'right_val': [1, 2, 3, 6, 7]}) # view dataprint(left)print(right) # applying merge_asof on dataprint(pandas.merge_asof(left, right, on='a'))print(pandas.merge_asof(left, right, on='a', allow_exact_matches=False)) Output: Example 2 : Python3 # importing packageimport pandas # creating dataleft = pandas.DataFrame({'a': [1, 5, 10], 'left_val': ['a', 'b', 'c']}) right = pandas.DataFrame({'a': [1, 2, 3, 6, 7], 'right_val': [1, 2, 3, 6, 7]}) # view dataprint(left)print(right) # applying merge_asof on dataprint(pandas.merge_asof(left, right, on='a', direction='forward'))print(pandas.merge_asof(left, right, on='a', direction='nearest')) Output : Example 3 : Python3 # importing packageimport pandas # creating dataleft = pandas.DataFrame({'left_val': ['a', 'b', 'c']}, index=[1, 5, 10]) right = pandas.DataFrame({'right_val': [1, 2, 3, 6, 7]}, index=[1, 2, 3, 6, 7]) # view dataprint(left)print(right) # applying merge_asof on dataprint(pandas.merge_asof(left, right, left_index=True, right_index=True)) Output: Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Aug, 2020" }, { "code": null, "e": 208, "s": 28, "text": "This method is used to perform an asof merge. This is similar to a left-join except that we match on nearest key rather than equal keys. Both DataFrames must be sorted by the key." }, { "code": null, "e": 450, "s": 208, "text": "Syntax : pandas.merge_asof(left, right, on=None, left_on=None, right_on=None, left_index=False, right_index=False, by=None, left_by=None, right_by=None, suffixes=(‘_x’, ‘_y’), tolerance=None, allow_exact_matches=True, direction=’backward’, )" }, { "code": null, "e": 463, "s": 450, "text": "Parameters :" }, { "code": null, "e": 487, "s": 463, "text": "left, right : DataFrame" }, { "code": null, "e": 556, "s": 487, "text": "on : label, Field name to join on. Must be found in both DataFrames." }, { "code": null, "e": 614, "s": 556, "text": "left_on : label, Field name to join on in left DataFrame." }, { "code": null, "e": 674, "s": 614, "text": "right_on : label, Field name to join on in right DataFrame." }, { "code": null, "e": 749, "s": 674, "text": "left_index : boolean, Use the index of the left DataFrame as the join key." }, { "code": null, "e": 826, "s": 749, "text": "right_index : boolean, Use the index of the right DataFrame as the join key." }, { "code": null, "e": 895, "s": 826, "text": "Below is the implementation of the above method with some examples :" }, { "code": null, "e": 907, "s": 895, "text": "Example 1 :" }, { "code": null, "e": 915, "s": 907, "text": "Python3" }, { "code": "# importing packageimport pandas # creating dataleft = pandas.DataFrame({'a': [1, 5, 10], 'left_val': ['a', 'b', 'c']}) right = pandas.DataFrame({'a': [1, 2, 3, 6, 7], 'right_val': [1, 2, 3, 6, 7]}) # view dataprint(left)print(right) # applying merge_asof on dataprint(pandas.merge_asof(left, right, on='a'))print(pandas.merge_asof(left, right, on='a', allow_exact_matches=False))", "e": 1374, "s": 915, "text": null }, { "code": null, "e": 1382, "s": 1374, "text": "Output:" }, { "code": null, "e": 1394, "s": 1382, "text": "Example 2 :" }, { "code": null, "e": 1402, "s": 1394, "text": "Python3" }, { "code": "# importing packageimport pandas # creating dataleft = pandas.DataFrame({'a': [1, 5, 10], 'left_val': ['a', 'b', 'c']}) right = pandas.DataFrame({'a': [1, 2, 3, 6, 7], 'right_val': [1, 2, 3, 6, 7]}) # view dataprint(left)print(right) # applying merge_asof on dataprint(pandas.merge_asof(left, right, on='a', direction='forward'))print(pandas.merge_asof(left, right, on='a', direction='nearest'))", "e": 1899, "s": 1402, "text": null }, { "code": null, "e": 1908, "s": 1899, "text": "Output :" }, { "code": null, "e": 1920, "s": 1908, "text": "Example 3 :" }, { "code": null, "e": 1928, "s": 1920, "text": "Python3" }, { "code": "# importing packageimport pandas # creating dataleft = pandas.DataFrame({'left_val': ['a', 'b', 'c']}, index=[1, 5, 10]) right = pandas.DataFrame({'right_val': [1, 2, 3, 6, 7]}, index=[1, 2, 3, 6, 7]) # view dataprint(left)print(right) # applying merge_asof on dataprint(pandas.merge_asof(left, right, left_index=True, right_index=True))", "e": 2343, "s": 1928, "text": null }, { "code": null, "e": 2351, "s": 2343, "text": "Output:" }, { "code": null, "e": 2383, "s": 2351, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 2397, "s": 2383, "text": "Python-pandas" }, { "code": null, "e": 2404, "s": 2397, "text": "Python" } ]
Automate Data Imports with Python | by Eser Saygın | Towards Data Science
Data import plays a pivotal role in data science. Knowing how to do it prevents the possibility of failure of the model. To achieve this, various methods, which differ depends on the data types (e.g. .csv, .txt, .json), are possible. Getting the data into the python environment one of the essential steps in building a model. In some circumstances, we have to load data without using API or SQL databases. In this tutorial, I will cover how to automate the data loading in Python. Compiling this might be a bit tricky. Besides, it’s possible to find a straightforward way to do it. But I want to show you my convoluted way. So let’s get started. Before we start, let’s import the requisite libraries using the following commands. In due course, I will explain why we need these modules. import pandas as pdimport osfrom os import listdirfrom os.path import isfile,joinimport csv The below image shows the data folder that contains several data file types. Keep in mind that file names. We will use them to create variable names. Routinely, I‘d’ rather assign my working directory as a file path. This provides me to combine file path and folder names swiftly. #assign working directory to variablefile_path=os.getcwd()#setting path for data folderdata_path=file_path+'\\'+'data' This step is crucial because we’re going to generate variable names from the file names. There are two different codes to extract file names. The first one is with extensions and the other one without extensions. We use “listdir” and “isfile” methods to get the file names. The “listdir” method is to get the list of all files in the specified directory. In our code, the directory is “data_path” that we assigned our working directory shortly before. So, the “isfile” method to check whether the file is existing in that folder. # extracting file names without extensionsfile_names=[".".join(f.split(".")[:-1]) for f in listdir(data_path) if isfile (join(data_path,f))] # extracting file names with extensionsfull_file_names=[f for f in listdir(data_path) if isfile (join(data_path,f))]#checking file names and extensionsprint(file_names)print(full_file_names) So far, everything is working fine. Now it is time to detect which delimiter is used in the files as the separator. To do that, we need the “sniff” method provided by the “Sniffer” class. This class is used to deduce the format of a csv file. #creating a dictionary with file names and their extensionsdict_del={}delimit=[]for i in range(len(file_names)): delimit.append(i)t=0for s in full_file_names: with open(data_path+'\\'+s, newline='', encoding="utf8") as csvfile: dialect = csv.Sniffer().sniff(csvfile.read(1024)) csvfile.seek(0) reader = csv.reader(csvfile, dialect) delimit[t]=dialect.delimiter dict_del[s]=delimit[t] t+=1 As you notice, we built a dictionary and a list. The list that is named “delimit” is used to store the delimiters. We use a for loop syntax to easily replace the random values with extracted delimiters via indexing. And the dictionary contains file names (as keys) and the delimiters (as values). Let’s check what we have; #checking dictionary and delimitersprint(dict_del)print(delimit) It is time to use the “globals()” method to create variables. Some sources (link) say it is dangerous due to it is global. This method can cause confusion, so please read carefully! #creating global variables depend on file namesz=0files_ready=[]for f,r in zip(file_names,full_file_names): globals()[f]=pd.read_csv(data_path+'\\'+r,sep=dict_del[r]) files_ready.append(f) z+=1 If you notice, variables are created separately for each file name. We are done! Let’s make sure it works. #checking data filesprint(files_ready)bank.head()deacit.head()netflix_titles.head() Voila! We loaded all files and assigned them a variable. Lastly, let’s perform a double-check with a new data file. I just saved a .txt file. (PSA) And I wonder if it works or not. #checking the new fileprint(files_ready)PSA.head() Everything seems to be working alright. As I said before, I don’t claim that these are the only and easy options to achieve this goal. This tutorial is the way I created to automate the process. Feel free to develop the code. :) Pros: Just run the code and load several files in a short time. You don’t need to think about variable names. You don’t miss out on any new files. Cons: I tested for the codes only csv and txt files. There could be an easier way. Please go check it out :) Useful Links To learn how to use split() function (Link) os.path.join and os.path.isfile (Link) The data import is grunt work at its essence, but it is still the essential component of building a data model. There are many more methods you can find and use. Building your method will improve your coding skills. I hope this guide was useful to you. Thanks for reading until the end.
[ { "code": null, "e": 406, "s": 172, "text": "Data import plays a pivotal role in data science. Knowing how to do it prevents the possibility of failure of the model. To achieve this, various methods, which differ depends on the data types (e.g. .csv, .txt, .json), are possible." }, { "code": null, "e": 819, "s": 406, "text": "Getting the data into the python environment one of the essential steps in building a model. In some circumstances, we have to load data without using API or SQL databases. In this tutorial, I will cover how to automate the data loading in Python. Compiling this might be a bit tricky. Besides, it’s possible to find a straightforward way to do it. But I want to show you my convoluted way. So let’s get started." }, { "code": null, "e": 960, "s": 819, "text": "Before we start, let’s import the requisite libraries using the following commands. In due course, I will explain why we need these modules." }, { "code": null, "e": 1052, "s": 960, "text": "import pandas as pdimport osfrom os import listdirfrom os.path import isfile,joinimport csv" }, { "code": null, "e": 1202, "s": 1052, "text": "The below image shows the data folder that contains several data file types. Keep in mind that file names. We will use them to create variable names." }, { "code": null, "e": 1333, "s": 1202, "text": "Routinely, I‘d’ rather assign my working directory as a file path. This provides me to combine file path and folder names swiftly." }, { "code": null, "e": 1452, "s": 1333, "text": "#assign working directory to variablefile_path=os.getcwd()#setting path for data folderdata_path=file_path+'\\\\'+'data'" }, { "code": null, "e": 1982, "s": 1452, "text": "This step is crucial because we’re going to generate variable names from the file names. There are two different codes to extract file names. The first one is with extensions and the other one without extensions. We use “listdir” and “isfile” methods to get the file names. The “listdir” method is to get the list of all files in the specified directory. In our code, the directory is “data_path” that we assigned our working directory shortly before. So, the “isfile” method to check whether the file is existing in that folder." }, { "code": null, "e": 2314, "s": 1982, "text": "# extracting file names without extensionsfile_names=[\".\".join(f.split(\".\")[:-1]) for f in listdir(data_path) if isfile (join(data_path,f))] # extracting file names with extensionsfull_file_names=[f for f in listdir(data_path) if isfile (join(data_path,f))]#checking file names and extensionsprint(file_names)print(full_file_names)" }, { "code": null, "e": 2557, "s": 2314, "text": "So far, everything is working fine. Now it is time to detect which delimiter is used in the files as the separator. To do that, we need the “sniff” method provided by the “Sniffer” class. This class is used to deduce the format of a csv file." }, { "code": null, "e": 2994, "s": 2557, "text": "#creating a dictionary with file names and their extensionsdict_del={}delimit=[]for i in range(len(file_names)): delimit.append(i)t=0for s in full_file_names: with open(data_path+'\\\\'+s, newline='', encoding=\"utf8\") as csvfile: dialect = csv.Sniffer().sniff(csvfile.read(1024)) csvfile.seek(0) reader = csv.reader(csvfile, dialect) delimit[t]=dialect.delimiter dict_del[s]=delimit[t] t+=1" }, { "code": null, "e": 3317, "s": 2994, "text": "As you notice, we built a dictionary and a list. The list that is named “delimit” is used to store the delimiters. We use a for loop syntax to easily replace the random values with extracted delimiters via indexing. And the dictionary contains file names (as keys) and the delimiters (as values). Let’s check what we have;" }, { "code": null, "e": 3382, "s": 3317, "text": "#checking dictionary and delimitersprint(dict_del)print(delimit)" }, { "code": null, "e": 3564, "s": 3382, "text": "It is time to use the “globals()” method to create variables. Some sources (link) say it is dangerous due to it is global. This method can cause confusion, so please read carefully!" }, { "code": null, "e": 3775, "s": 3564, "text": "#creating global variables depend on file namesz=0files_ready=[]for f,r in zip(file_names,full_file_names): globals()[f]=pd.read_csv(data_path+'\\\\'+r,sep=dict_del[r]) files_ready.append(f) z+=1" }, { "code": null, "e": 3882, "s": 3775, "text": "If you notice, variables are created separately for each file name. We are done! Let’s make sure it works." }, { "code": null, "e": 3966, "s": 3882, "text": "#checking data filesprint(files_ready)bank.head()deacit.head()netflix_titles.head()" }, { "code": null, "e": 4023, "s": 3966, "text": "Voila! We loaded all files and assigned them a variable." }, { "code": null, "e": 4114, "s": 4023, "text": "Lastly, let’s perform a double-check with a new data file. I just saved a .txt file. (PSA)" }, { "code": null, "e": 4147, "s": 4114, "text": "And I wonder if it works or not." }, { "code": null, "e": 4198, "s": 4147, "text": "#checking the new fileprint(files_ready)PSA.head()" }, { "code": null, "e": 4238, "s": 4198, "text": "Everything seems to be working alright." }, { "code": null, "e": 4427, "s": 4238, "text": "As I said before, I don’t claim that these are the only and easy options to achieve this goal. This tutorial is the way I created to automate the process. Feel free to develop the code. :)" }, { "code": null, "e": 4433, "s": 4427, "text": "Pros:" }, { "code": null, "e": 4491, "s": 4433, "text": "Just run the code and load several files in a short time." }, { "code": null, "e": 4537, "s": 4491, "text": "You don’t need to think about variable names." }, { "code": null, "e": 4574, "s": 4537, "text": "You don’t miss out on any new files." }, { "code": null, "e": 4580, "s": 4574, "text": "Cons:" }, { "code": null, "e": 4627, "s": 4580, "text": "I tested for the codes only csv and txt files." }, { "code": null, "e": 4683, "s": 4627, "text": "There could be an easier way. Please go check it out :)" }, { "code": null, "e": 4696, "s": 4683, "text": "Useful Links" }, { "code": null, "e": 4740, "s": 4696, "text": "To learn how to use split() function (Link)" }, { "code": null, "e": 4779, "s": 4740, "text": "os.path.join and os.path.isfile (Link)" }, { "code": null, "e": 4941, "s": 4779, "text": "The data import is grunt work at its essence, but it is still the essential component of building a data model. There are many more methods you can find and use." } ]
How to draw a dashed line on a Tkinter canvas?
To draw a dashed line on a Tkinter canvas, we can use the dash parameter of create_line() method. Import the tkinter library and create an instance of tkinter frame. Import the tkinter library and create an instance of tkinter frame. Set the size of the frame using geometry method. Set the size of the frame using geometry method. Create a Canvas widget and set its height and width. Create a Canvas widget and set its height and width. Next, use the create_line function and pass the coordinates of the line (x1, y1) and (x2, y2). Next, use the create_line function and pass the coordinates of the line (x1, y1) and (x2, y2). To get a dashed line, use the dash parameter dash=(5,1) for 5px dash followed by 1px space. To get a dashed line, use the dash parameter dash=(5,1) for 5px dash followed by 1px space. You can set the color and width of the dashed lines using the fill and width parameters. You can set the color and width of the dashed lines using the fill and width parameters. Finally, run the mainloop of the application window. Finally, run the mainloop of the application window. # Import the library from tkinter import * # Create an instance of window win = Tk() # Set the geometry of the window win.geometry("700x350") C1 = Canvas(win, width=600, height=400) # Coordinates of the line coordinates = 100,150,550,150 # Draw a dashed vertical line, 5px dash and 1px space C1.create_line(coordinates, dash=(5,1)) C1.pack() win.mainloop() It will produce the following output − Note: Dash patterns are system-dependent. You may get different outputs on Windows and Linux based systems. Windows doesn't support the same dash patterns as Linux.
[ { "code": null, "e": 1160, "s": 1062, "text": "To draw a dashed line on a Tkinter canvas, we can use the dash parameter of create_line() method." }, { "code": null, "e": 1228, "s": 1160, "text": "Import the tkinter library and create an instance of tkinter frame." }, { "code": null, "e": 1296, "s": 1228, "text": "Import the tkinter library and create an instance of tkinter frame." }, { "code": null, "e": 1345, "s": 1296, "text": "Set the size of the frame using geometry method." }, { "code": null, "e": 1394, "s": 1345, "text": "Set the size of the frame using geometry method." }, { "code": null, "e": 1447, "s": 1394, "text": "Create a Canvas widget and set its height and width." }, { "code": null, "e": 1500, "s": 1447, "text": "Create a Canvas widget and set its height and width." }, { "code": null, "e": 1595, "s": 1500, "text": "Next, use the create_line function and pass the coordinates of the line (x1, y1) and (x2, y2)." }, { "code": null, "e": 1690, "s": 1595, "text": "Next, use the create_line function and pass the coordinates of the line (x1, y1) and (x2, y2)." }, { "code": null, "e": 1782, "s": 1690, "text": "To get a dashed line, use the dash parameter dash=(5,1) for 5px dash followed by 1px space." }, { "code": null, "e": 1874, "s": 1782, "text": "To get a dashed line, use the dash parameter dash=(5,1) for 5px dash followed by 1px space." }, { "code": null, "e": 1963, "s": 1874, "text": "You can set the color and width of the dashed lines using the fill and width parameters." }, { "code": null, "e": 2052, "s": 1963, "text": "You can set the color and width of the dashed lines using the fill and width parameters." }, { "code": null, "e": 2105, "s": 2052, "text": "Finally, run the mainloop of the application window." }, { "code": null, "e": 2158, "s": 2105, "text": "Finally, run the mainloop of the application window." }, { "code": null, "e": 2521, "s": 2158, "text": "# Import the library\nfrom tkinter import *\n\n# Create an instance of window\nwin = Tk()\n\n# Set the geometry of the window\nwin.geometry(\"700x350\")\n\nC1 = Canvas(win, width=600, height=400)\n\n# Coordinates of the line\ncoordinates = 100,150,550,150\n\n# Draw a dashed vertical line, 5px dash and 1px space\nC1.create_line(coordinates, dash=(5,1))\nC1.pack()\n\nwin.mainloop()" }, { "code": null, "e": 2560, "s": 2521, "text": "It will produce the following output −" }, { "code": null, "e": 2725, "s": 2560, "text": "Note: Dash patterns are system-dependent. You may get different outputs on Windows and Linux based systems. Windows doesn't support the same dash patterns as Linux." } ]
Convert an Object into a Matrix in R Programming - as.matrix() Function - GeeksforGeeks
27 Oct, 2021 as.matrix() function in R Programming Language is used to convert an object into a Matrix. Syntax: as.matrix(x) Parameters: x: Object to be converted R # R program to convert an object to matrix # Creating a vectorx <- c(1:9) # Calling as.matrix() Functionas.matrix(x) Output: [, 1] [1, ] 1 [2, ] 2 [3, ] 3 [4, ] 4 [5, ] 5 [6, ] 6 [7, ] 7 [8, ] 8 [9, ] 9 R # R program to convert an object to matrix # Calling pre-defined data setBOD # Calling as.matrix() Functionas.matrix(BOD) Output: Time demand 1 1 8.3 2 2 10.3 3 3 19.0 4 4 16.0 5 5 15.6 6 7 19.8 Time demand [1, ] 1 8.3 [2, ] 2 10.3 [3, ] 3 19.0 [4, ] 4 16.0 [5, ] 5 15.6 [6, ] 7 19.8 kumar_satyam R Matrix-Function R Object-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? How to import an Excel File into R ? Replace Specific Characters in String in R R - if statement Time Series Analysis in R
[ { "code": null, "e": 25242, "s": 25214, "text": "\n27 Oct, 2021" }, { "code": null, "e": 25333, "s": 25242, "text": "as.matrix() function in R Programming Language is used to convert an object into a Matrix." }, { "code": null, "e": 25354, "s": 25333, "text": "Syntax: as.matrix(x)" }, { "code": null, "e": 25367, "s": 25354, "text": "Parameters: " }, { "code": null, "e": 25393, "s": 25367, "text": "x: Object to be converted" }, { "code": null, "e": 25395, "s": 25393, "text": "R" }, { "code": "# R program to convert an object to matrix # Creating a vectorx <- c(1:9) # Calling as.matrix() Functionas.matrix(x)", "e": 25512, "s": 25395, "text": null }, { "code": null, "e": 25521, "s": 25512, "text": "Output: " }, { "code": null, "e": 25641, "s": 25521, "text": " [, 1]\n [1, ] 1\n [2, ] 2\n [3, ] 3\n [4, ] 4\n [5, ] 5\n [6, ] 6\n [7, ] 7\n [8, ] 8\n [9, ] 9" }, { "code": null, "e": 25643, "s": 25641, "text": "R" }, { "code": "# R program to convert an object to matrix # Calling pre-defined data setBOD # Calling as.matrix() Functionas.matrix(BOD)", "e": 25765, "s": 25643, "text": null }, { "code": null, "e": 25774, "s": 25765, "text": "Output: " }, { "code": null, "e": 25997, "s": 25774, "text": " Time demand\n1 1 8.3\n2 2 10.3\n3 3 19.0\n4 4 16.0\n5 5 15.6\n6 7 19.8\n Time demand\n[1, ] 1 8.3\n[2, ] 2 10.3\n[3, ] 3 19.0\n[4, ] 4 16.0\n[5, ] 5 15.6\n[6, ] 7 19.8" }, { "code": null, "e": 26010, "s": 25997, "text": "kumar_satyam" }, { "code": null, "e": 26028, "s": 26010, "text": "R Matrix-Function" }, { "code": null, "e": 26046, "s": 26028, "text": "R Object-Function" }, { "code": null, "e": 26057, "s": 26046, "text": "R Language" }, { "code": null, "e": 26155, "s": 26057, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26207, "s": 26155, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26245, "s": 26207, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26280, "s": 26245, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26338, "s": 26280, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 26387, "s": 26338, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 26437, "s": 26387, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 26474, "s": 26437, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 26517, "s": 26474, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 26534, "s": 26517, "text": "R - if statement" } ]
Raw string literal in C++ program
In this article, we will be discussing the raw string literal in C++, its meaning, and examples. There are escape characters in C++ like “\n” or “\t”. When we try to print the escape characters, it will not display on the output. To show the escape characters on the output screen we use a raw string literal by using R”(String with escape characters)”. After using R in the front of the string the escape character will be displayed on the output. Let’s understand this with the help of an example Live Demo #include <iostream> using namespace std; int main(){ string str = "tutorials\npoint\n" ; // A Raw string string str_R = R"(tutorials\npoint\n)"; cout <<"String is: "<<str << endl; cout <<"Raw String is: "<<str_R; return 0; } If we run the above code it will generate the following output − String is: tutorials point Raw String is: tutorials\npoint\n Live Demo #include <iostream> using namespace std; int main(){ string str = "tutorials\ttoint\t" ; // A Raw string string str_R = R"(tutorials\tpoint\t)"; cout <<"String is: "<<str << endl; cout <<"Raw String is: "<<str_R; return 0; } If we run the above code it will generate the following output − String is: tutorials toint Raw String is: tutorials\tpoint\t
[ { "code": null, "e": 1159, "s": 1062, "text": "In this article, we will be discussing the raw string literal in C++, its meaning, and examples." }, { "code": null, "e": 1511, "s": 1159, "text": "There are escape characters in C++ like “\\n” or “\\t”. When we try to print the escape characters, it will not display on the output. To show the escape characters on the output screen we use a raw string literal by using R”(String with escape characters)”. After using R in the front of the string the escape character will be displayed on the output." }, { "code": null, "e": 1561, "s": 1511, "text": "Let’s understand this with the help of an example" }, { "code": null, "e": 1572, "s": 1561, "text": " Live Demo" }, { "code": null, "e": 1815, "s": 1572, "text": "#include <iostream>\nusing namespace std;\nint main(){\n string str = \"tutorials\\npoint\\n\" ;\n // A Raw string\n string str_R = R\"(tutorials\\npoint\\n)\";\n cout <<\"String is: \"<<str << endl;\n cout <<\"Raw String is: \"<<str_R;\n return 0;\n}" }, { "code": null, "e": 1880, "s": 1815, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 1941, "s": 1880, "text": "String is: tutorials\npoint\nRaw String is: tutorials\\npoint\\n" }, { "code": null, "e": 1952, "s": 1941, "text": " Live Demo" }, { "code": null, "e": 2195, "s": 1952, "text": "#include <iostream>\nusing namespace std;\nint main(){\n string str = \"tutorials\\ttoint\\t\" ;\n // A Raw string\n string str_R = R\"(tutorials\\tpoint\\t)\";\n cout <<\"String is: \"<<str << endl;\n cout <<\"Raw String is: \"<<str_R;\n return 0;\n}" }, { "code": null, "e": 2260, "s": 2195, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 2321, "s": 2260, "text": "String is: tutorials toint\nRaw String is: tutorials\\tpoint\\t" } ]
35 Questions To Test Your Knowledge of Python Sets | by GreekDataGuy | Towards Data Science
In my pursuit of interview algorithm mastery, I’ve found it useful to dig into Python’s basic data structures. This is my personal list of questions I wrote to evaluate my knowledge of Python sets. How well do you know python sets? No. A set is not an ordered data structure, so order is not maintained. Look what happens when we convert the list [3,2,1] to a set. It becomes {1,2,3}. a = set([3,2,1])a #=> {1, 2, 3} This can be done with the issubset() method. a = {4,5}b = {1,2,3,4,5}a.issubset(b) #=> Trueb.issubset(a)#=> False A set, s1, is a subset of s2 if all elements of s1 are in s2. The operators <= will return True if all elements of the 1st set exist in the 2nd set (aka. is a subset). a = {'a','b'}b = {'a','b','c'}a <= b#=> Trueb <= a #=> False Yes. Because a set contains all elements in itself, it is indeed a subset of itself. This is important to understand when we contrast “subset” with “proper subset” later. a = {10,20}a.issubset(a) #=> True Like other types of iterables, we can check if a value exists in a set with the in operator. s = {5,7,9}5 in s#=> True6 in s#=> False We can again use the in operator, but this time prefaced by not. s = {'x','y''z'}'w' not in s#=> True'x' not in s#=> False A set is an unordered collection of unique objects. Duplicate values are removed when any object is converted to a set. set([1,1,1,3,5])#=> {1, 3, 5} In my personal experience, I use sets because they make operations like finding intersections, unions and differences easy. A proper subset is a subset of a set, not equal to itself. {1,2,3} is a proper subset of {1,2,3,4}. {1,2,3} is not a proper subset of {1,2,3}, but it is a subset. We can check if a set is a proper subset of another set using the < operator. {1,2,3} < {1,2,3,4}#=> True{1,2,3} < {1,2,3}#=> False Unlike lists, we can’t use the + operator to add elements to a set. {1,2,3} + {4}#=> TypeError: unsupported operand type(s) for +: 'set' and 'set' Use the add method to add elements. s = {'a','b','c'}s.add('d')s#=> {'a', 'b', 'c', 'd'} The copy() method makes a shallow copy of a set. s1 = {'a','b','c'}s2 = s1.copy()s2 #=> {'c', 'b', 'a'} A set, s1 is a superset of another set, s2, if all values in s2 can be found in s1. You can check if a set is a superset of another set with the issuperset() method. a = {10,20,30}b = {10,20}a.issuperset(b) #=> Trueb.issuperset(a) #=> False In addition to issuperset(), we can check if a set is a superset using the >= comparison operators. a = {10,20,30}b = {10,20}a >= b #=> Trueb >= a #=> False Because all the values in a set, s1, are in s1, it is a superset of itself. Though it is not a proper superset. a = {10,20,30}a.issuperset(a) #=> True A set, s1 is a proper superset of another set, s2, if all the values in s2 are in s1, and s1 != s2. This can be checked with the > operator. a = {10,20,30}b = {10,20}c = {10,20}a > b #=> Trueb > c #=> False Calling the list constructor, list(), on a set converts a set to a list. But note that order is not guaranteed. a = {4,2,3}list(a)#=> [2, 3, 4] A set can be iterated over like any other iterator with a loop. But note again, order is not guaranteed. s = {'a','b','c','d','e'}for i in s: print(i) #=> b#=> c#=> e#=> d#=> a The number of elements in a set can be returned with the len() function. s = {'a','b','c','d','e'}len(s)#=> 5 A set can be created using set notation with curly braces like, {...}, example: {1,2,3}#=> {1, 2, 3} Or with the set constructor, example: # set(1,2,3)=> TypeError: set expected at most 1 arguments, got 3set([1,2,3])#=> {1, 2, 3} But note the latter requires passing in another iterable object like a list. The union of 2 sets can be found by using the union() method. s1 = {1,2,3,4,5}s2 = {4,5,6,7,8}s1.union(s2)#=> {1, 2, 3, 4, 5, 6, 7, 8} It can also be found with the | operator. s1 = {1,2,3,4,5}s2 = {4,5,6,7,8}s1 | s2#=> {1, 2, 3, 4, 5, 6, 7, 8} The intersection of 2 sets can be taken with the intersection() method. s1 = {1,2,3,4,5}s2 = {4,5,6,7,8}s1.intersection(s2)# => {4, 5} It can also be taken with the & operator. s1 = {1,2,3,4,5}s2 = {4,5,6,7,8}s1 & s2# => {4, 5} This can be found with the difference() method. s1 = {1,2,3,4,5}s2 = {4,5,6,7,8}s1.difference(s2){1, 2, 3} It can also be found with the - operator. s1 = {1,2,3,4,5}s2 = {4,5,6,7,8}s1 - s2{1, 2, 3} remove() removes an element from a set by value. s = {'x','y','z'}s.remove('x')s#=> {'y', 'z'} pop() removes and returns an element from a set, treating the set like an unordered queue. s = {'z','y','x'}s.pop()s#=> {'y', 'z'} Sets, s1 and s2 are disjoint if they have no elements in common. a = {1,2,3}b = {4,5,6}c = {3}a.isdisjoint(b) #=> Truea.isdisjoint(c) #=> False The update() method adds elements from another set. a = {1,2,3}b = {3,4,5}a.update(b)a#=> {1, 2, 3, 4, 5} This can also be done with the |= operator. a = {1,2,3}b = {3,4,5}a |= ba#=> {1, 2, 3, 4, 5} Note this is different from union. union() returns a new set instead of updating an existing set. clear() removes all elements from a set. The set can then be used for future operations and store other values. a = {1,2,3}a.clear()a#=> set() discard() removes an element if that element exists, otherwise it does nothing. a = {1,2,3}a.discard(1)a#=> {2, 3}a = {1,2,3}a.discard(5)a#=> {1, 2, 3} Contrast this to remove() which throws an error if you try to remove an element that doesn’t exist. a = {1,2,3}a.remove(5)a#=> KeyError: 5 Only the dictionary’s keys will exist in the returned set. d = {'dog': 1, 'cat':2, 'fish':3}set(d)#=> {'cat', 'dog', 'fish'} Yes. But the values from each set may not be joined in order. Notice how the 1st value in the integer set was combined with the 3rd value in the letter set, (1, 'c'). z = zip( {1,2,3}, {'a','b','c'})list(z)#=> [(1, 'c'), (2, 'b'), (3, 'a')] No. Trying to access a set by index will throw an error. s = {1,2,3}s[0]#=> TypeError: 'set' object is not subscriptable Tuples are immutable. Sets are mutable. Values in a tuple can be accessed by index. Values in a set can only be accessed by value. Tuples have order. Sets have no order. Sets implement set theory, so they have lots of interesting functionality like union, intersect, difference, etc. Frozensets behave just like sets except they are immutable. s = set([1,2,3])fs = frozenset([1,2,3])s #=> {1, 2, 3}fs #=> frozenset({1, 2, 3})s.add(4)s #=> {1, 2, 3, 4}fs.add(4)fs #=> AttributeError: 'frozenset' object has no attribute 'add' intersection_update() updates the first set to be equal to the intersection. s1 = {1,2,3,4,5}s2 = {4,5,6,7,8}s1.intersection_update(s2)s1#=> {4, 5} This can also be done with the &= operator. s1 = {1,2,3,4,5}s2 = {4,5,6,7,8}s1 &= s2s1#=> {4, 5} difference_update() removes the intersection from the first set. s1 = {1,2,3,4,5}s2 = {4,5,6,7,8}s1.difference_update(s2)s1#=> {1, 2, 3} The operator -= also works. s1 = {1,2,3,4,5}s2 = {4,5,6,7,8}s1 -= s2s1#=> {1, 2, 3} How did you do? Honestly, I did worse here than on my string questions and list questions. We don’t often use sets in day to day programming, and most of us only touch set theory when writing SQL joins. That said it doesn’t hurt to be familiar with the basics. If you found this interesting you might also like my python interview questions. Onward and upward.
[ { "code": null, "e": 283, "s": 172, "text": "In my pursuit of interview algorithm mastery, I’ve found it useful to dig into Python’s basic data structures." }, { "code": null, "e": 370, "s": 283, "text": "This is my personal list of questions I wrote to evaluate my knowledge of Python sets." }, { "code": null, "e": 404, "s": 370, "text": "How well do you know python sets?" }, { "code": null, "e": 476, "s": 404, "text": "No. A set is not an ordered data structure, so order is not maintained." }, { "code": null, "e": 557, "s": 476, "text": "Look what happens when we convert the list [3,2,1] to a set. It becomes {1,2,3}." }, { "code": null, "e": 589, "s": 557, "text": "a = set([3,2,1])a #=> {1, 2, 3}" }, { "code": null, "e": 634, "s": 589, "text": "This can be done with the issubset() method." }, { "code": null, "e": 703, "s": 634, "text": "a = {4,5}b = {1,2,3,4,5}a.issubset(b) #=> Trueb.issubset(a)#=> False" }, { "code": null, "e": 765, "s": 703, "text": "A set, s1, is a subset of s2 if all elements of s1 are in s2." }, { "code": null, "e": 871, "s": 765, "text": "The operators <= will return True if all elements of the 1st set exist in the 2nd set (aka. is a subset)." }, { "code": null, "e": 932, "s": 871, "text": "a = {'a','b'}b = {'a','b','c'}a <= b#=> Trueb <= a #=> False" }, { "code": null, "e": 937, "s": 932, "text": "Yes." }, { "code": null, "e": 1103, "s": 937, "text": "Because a set contains all elements in itself, it is indeed a subset of itself. This is important to understand when we contrast “subset” with “proper subset” later." }, { "code": null, "e": 1137, "s": 1103, "text": "a = {10,20}a.issubset(a) #=> True" }, { "code": null, "e": 1230, "s": 1137, "text": "Like other types of iterables, we can check if a value exists in a set with the in operator." }, { "code": null, "e": 1271, "s": 1230, "text": "s = {5,7,9}5 in s#=> True6 in s#=> False" }, { "code": null, "e": 1336, "s": 1271, "text": "We can again use the in operator, but this time prefaced by not." }, { "code": null, "e": 1394, "s": 1336, "text": "s = {'x','y''z'}'w' not in s#=> True'x' not in s#=> False" }, { "code": null, "e": 1446, "s": 1394, "text": "A set is an unordered collection of unique objects." }, { "code": null, "e": 1514, "s": 1446, "text": "Duplicate values are removed when any object is converted to a set." }, { "code": null, "e": 1544, "s": 1514, "text": "set([1,1,1,3,5])#=> {1, 3, 5}" }, { "code": null, "e": 1668, "s": 1544, "text": "In my personal experience, I use sets because they make operations like finding intersections, unions and differences easy." }, { "code": null, "e": 1727, "s": 1668, "text": "A proper subset is a subset of a set, not equal to itself." }, { "code": null, "e": 1768, "s": 1727, "text": "{1,2,3} is a proper subset of {1,2,3,4}." }, { "code": null, "e": 1831, "s": 1768, "text": "{1,2,3} is not a proper subset of {1,2,3}, but it is a subset." }, { "code": null, "e": 1909, "s": 1831, "text": "We can check if a set is a proper subset of another set using the < operator." }, { "code": null, "e": 1963, "s": 1909, "text": "{1,2,3} < {1,2,3,4}#=> True{1,2,3} < {1,2,3}#=> False" }, { "code": null, "e": 2031, "s": 1963, "text": "Unlike lists, we can’t use the + operator to add elements to a set." }, { "code": null, "e": 2110, "s": 2031, "text": "{1,2,3} + {4}#=> TypeError: unsupported operand type(s) for +: 'set' and 'set'" }, { "code": null, "e": 2146, "s": 2110, "text": "Use the add method to add elements." }, { "code": null, "e": 2199, "s": 2146, "text": "s = {'a','b','c'}s.add('d')s#=> {'a', 'b', 'c', 'd'}" }, { "code": null, "e": 2248, "s": 2199, "text": "The copy() method makes a shallow copy of a set." }, { "code": null, "e": 2303, "s": 2248, "text": "s1 = {'a','b','c'}s2 = s1.copy()s2 #=> {'c', 'b', 'a'}" }, { "code": null, "e": 2387, "s": 2303, "text": "A set, s1 is a superset of another set, s2, if all values in s2 can be found in s1." }, { "code": null, "e": 2469, "s": 2387, "text": "You can check if a set is a superset of another set with the issuperset() method." }, { "code": null, "e": 2544, "s": 2469, "text": "a = {10,20,30}b = {10,20}a.issuperset(b) #=> Trueb.issuperset(a) #=> False" }, { "code": null, "e": 2644, "s": 2544, "text": "In addition to issuperset(), we can check if a set is a superset using the >= comparison operators." }, { "code": null, "e": 2701, "s": 2644, "text": "a = {10,20,30}b = {10,20}a >= b #=> Trueb >= a #=> False" }, { "code": null, "e": 2813, "s": 2701, "text": "Because all the values in a set, s1, are in s1, it is a superset of itself. Though it is not a proper superset." }, { "code": null, "e": 2852, "s": 2813, "text": "a = {10,20,30}a.issuperset(a) #=> True" }, { "code": null, "e": 2952, "s": 2852, "text": "A set, s1 is a proper superset of another set, s2, if all the values in s2 are in s1, and s1 != s2." }, { "code": null, "e": 2993, "s": 2952, "text": "This can be checked with the > operator." }, { "code": null, "e": 3059, "s": 2993, "text": "a = {10,20,30}b = {10,20}c = {10,20}a > b #=> Trueb > c #=> False" }, { "code": null, "e": 3171, "s": 3059, "text": "Calling the list constructor, list(), on a set converts a set to a list. But note that order is not guaranteed." }, { "code": null, "e": 3203, "s": 3171, "text": "a = {4,2,3}list(a)#=> [2, 3, 4]" }, { "code": null, "e": 3308, "s": 3203, "text": "A set can be iterated over like any other iterator with a loop. But note again, order is not guaranteed." }, { "code": null, "e": 3386, "s": 3308, "text": "s = {'a','b','c','d','e'}for i in s: print(i) #=> b#=> c#=> e#=> d#=> a" }, { "code": null, "e": 3459, "s": 3386, "text": "The number of elements in a set can be returned with the len() function." }, { "code": null, "e": 3496, "s": 3459, "text": "s = {'a','b','c','d','e'}len(s)#=> 5" }, { "code": null, "e": 3576, "s": 3496, "text": "A set can be created using set notation with curly braces like, {...}, example:" }, { "code": null, "e": 3597, "s": 3576, "text": "{1,2,3}#=> {1, 2, 3}" }, { "code": null, "e": 3635, "s": 3597, "text": "Or with the set constructor, example:" }, { "code": null, "e": 3726, "s": 3635, "text": "# set(1,2,3)=> TypeError: set expected at most 1 arguments, got 3set([1,2,3])#=> {1, 2, 3}" }, { "code": null, "e": 3803, "s": 3726, "text": "But note the latter requires passing in another iterable object like a list." }, { "code": null, "e": 3865, "s": 3803, "text": "The union of 2 sets can be found by using the union() method." }, { "code": null, "e": 3938, "s": 3865, "text": "s1 = {1,2,3,4,5}s2 = {4,5,6,7,8}s1.union(s2)#=> {1, 2, 3, 4, 5, 6, 7, 8}" }, { "code": null, "e": 3980, "s": 3938, "text": "It can also be found with the | operator." }, { "code": null, "e": 4048, "s": 3980, "text": "s1 = {1,2,3,4,5}s2 = {4,5,6,7,8}s1 | s2#=> {1, 2, 3, 4, 5, 6, 7, 8}" }, { "code": null, "e": 4120, "s": 4048, "text": "The intersection of 2 sets can be taken with the intersection() method." }, { "code": null, "e": 4183, "s": 4120, "text": "s1 = {1,2,3,4,5}s2 = {4,5,6,7,8}s1.intersection(s2)# => {4, 5}" }, { "code": null, "e": 4225, "s": 4183, "text": "It can also be taken with the & operator." }, { "code": null, "e": 4276, "s": 4225, "text": "s1 = {1,2,3,4,5}s2 = {4,5,6,7,8}s1 & s2# => {4, 5}" }, { "code": null, "e": 4324, "s": 4276, "text": "This can be found with the difference() method." }, { "code": null, "e": 4383, "s": 4324, "text": "s1 = {1,2,3,4,5}s2 = {4,5,6,7,8}s1.difference(s2){1, 2, 3}" }, { "code": null, "e": 4425, "s": 4383, "text": "It can also be found with the - operator." }, { "code": null, "e": 4474, "s": 4425, "text": "s1 = {1,2,3,4,5}s2 = {4,5,6,7,8}s1 - s2{1, 2, 3}" }, { "code": null, "e": 4523, "s": 4474, "text": "remove() removes an element from a set by value." }, { "code": null, "e": 4569, "s": 4523, "text": "s = {'x','y','z'}s.remove('x')s#=> {'y', 'z'}" }, { "code": null, "e": 4660, "s": 4569, "text": "pop() removes and returns an element from a set, treating the set like an unordered queue." }, { "code": null, "e": 4700, "s": 4660, "text": "s = {'z','y','x'}s.pop()s#=> {'y', 'z'}" }, { "code": null, "e": 4765, "s": 4700, "text": "Sets, s1 and s2 are disjoint if they have no elements in common." }, { "code": null, "e": 4844, "s": 4765, "text": "a = {1,2,3}b = {4,5,6}c = {3}a.isdisjoint(b) #=> Truea.isdisjoint(c) #=> False" }, { "code": null, "e": 4896, "s": 4844, "text": "The update() method adds elements from another set." }, { "code": null, "e": 4950, "s": 4896, "text": "a = {1,2,3}b = {3,4,5}a.update(b)a#=> {1, 2, 3, 4, 5}" }, { "code": null, "e": 4994, "s": 4950, "text": "This can also be done with the |= operator." }, { "code": null, "e": 5043, "s": 4994, "text": "a = {1,2,3}b = {3,4,5}a |= ba#=> {1, 2, 3, 4, 5}" }, { "code": null, "e": 5141, "s": 5043, "text": "Note this is different from union. union() returns a new set instead of updating an existing set." }, { "code": null, "e": 5253, "s": 5141, "text": "clear() removes all elements from a set. The set can then be used for future operations and store other values." }, { "code": null, "e": 5284, "s": 5253, "text": "a = {1,2,3}a.clear()a#=> set()" }, { "code": null, "e": 5364, "s": 5284, "text": "discard() removes an element if that element exists, otherwise it does nothing." }, { "code": null, "e": 5436, "s": 5364, "text": "a = {1,2,3}a.discard(1)a#=> {2, 3}a = {1,2,3}a.discard(5)a#=> {1, 2, 3}" }, { "code": null, "e": 5536, "s": 5436, "text": "Contrast this to remove() which throws an error if you try to remove an element that doesn’t exist." }, { "code": null, "e": 5575, "s": 5536, "text": "a = {1,2,3}a.remove(5)a#=> KeyError: 5" }, { "code": null, "e": 5634, "s": 5575, "text": "Only the dictionary’s keys will exist in the returned set." }, { "code": null, "e": 5700, "s": 5634, "text": "d = {'dog': 1, 'cat':2, 'fish':3}set(d)#=> {'cat', 'dog', 'fish'}" }, { "code": null, "e": 5762, "s": 5700, "text": "Yes. But the values from each set may not be joined in order." }, { "code": null, "e": 5867, "s": 5762, "text": "Notice how the 1st value in the integer set was combined with the 3rd value in the letter set, (1, 'c')." }, { "code": null, "e": 5943, "s": 5867, "text": "z = zip( {1,2,3}, {'a','b','c'})list(z)#=> [(1, 'c'), (2, 'b'), (3, 'a')]" }, { "code": null, "e": 6000, "s": 5943, "text": "No. Trying to access a set by index will throw an error." }, { "code": null, "e": 6064, "s": 6000, "text": "s = {1,2,3}s[0]#=> TypeError: 'set' object is not subscriptable" }, { "code": null, "e": 6104, "s": 6064, "text": "Tuples are immutable. Sets are mutable." }, { "code": null, "e": 6195, "s": 6104, "text": "Values in a tuple can be accessed by index. Values in a set can only be accessed by value." }, { "code": null, "e": 6234, "s": 6195, "text": "Tuples have order. Sets have no order." }, { "code": null, "e": 6348, "s": 6234, "text": "Sets implement set theory, so they have lots of interesting functionality like union, intersect, difference, etc." }, { "code": null, "e": 6408, "s": 6348, "text": "Frozensets behave just like sets except they are immutable." }, { "code": null, "e": 6589, "s": 6408, "text": "s = set([1,2,3])fs = frozenset([1,2,3])s #=> {1, 2, 3}fs #=> frozenset({1, 2, 3})s.add(4)s #=> {1, 2, 3, 4}fs.add(4)fs #=> AttributeError: 'frozenset' object has no attribute 'add'" }, { "code": null, "e": 6666, "s": 6589, "text": "intersection_update() updates the first set to be equal to the intersection." }, { "code": null, "e": 6737, "s": 6666, "text": "s1 = {1,2,3,4,5}s2 = {4,5,6,7,8}s1.intersection_update(s2)s1#=> {4, 5}" }, { "code": null, "e": 6781, "s": 6737, "text": "This can also be done with the &= operator." }, { "code": null, "e": 6834, "s": 6781, "text": "s1 = {1,2,3,4,5}s2 = {4,5,6,7,8}s1 &= s2s1#=> {4, 5}" }, { "code": null, "e": 6899, "s": 6834, "text": "difference_update() removes the intersection from the first set." }, { "code": null, "e": 6971, "s": 6899, "text": "s1 = {1,2,3,4,5}s2 = {4,5,6,7,8}s1.difference_update(s2)s1#=> {1, 2, 3}" }, { "code": null, "e": 6999, "s": 6971, "text": "The operator -= also works." }, { "code": null, "e": 7055, "s": 6999, "text": "s1 = {1,2,3,4,5}s2 = {4,5,6,7,8}s1 -= s2s1#=> {1, 2, 3}" }, { "code": null, "e": 7071, "s": 7055, "text": "How did you do?" }, { "code": null, "e": 7146, "s": 7071, "text": "Honestly, I did worse here than on my string questions and list questions." }, { "code": null, "e": 7316, "s": 7146, "text": "We don’t often use sets in day to day programming, and most of us only touch set theory when writing SQL joins. That said it doesn’t hurt to be familiar with the basics." }, { "code": null, "e": 7397, "s": 7316, "text": "If you found this interesting you might also like my python interview questions." } ]
Getting Started with PyTorch - GeeksforGeeks
22 Jul, 2021 Deep Learning is a branch of Machine Learning where algorithms are written which mimic the functioning of a human brain. The most commonly used libraries in deep learning are Tensorflow and PyTorch. As there are various deep learning frameworks available, one might wonder when to use PyTorch. Here are reasons why one might prefer using Pytorch for specific tasks. Pytorch is an open-source deep learning framework available with a Python and C++ interface. Pytorch resides inside the torch module. In PyTorch, the data that has to be processed is input in the form of a tensor. If you have Anaconda Python Package manager installed in your system, then using by running the following command in the terminal will install PyTorch: conda install pytorch torchvision cpuonly -c pytorch If you want to use PyTorch without explicitly installing it into your local machine, you can use Google Colab. The Pytorch is used to process the tensors. Tensors are multidimensional arrays like n-dimensional NumPy array. However, tensors can be used in GPUs as well, which is not in the case of NumPy array. PyTorch accelerates the scientific computation of tensors as it has various inbuilt functions. A vector is a one-dimensional tensor, and a matrix is a two-dimensional tensor. One significant difference between the Tensor and multidimensional array used in C, C++, and Java is tensors should have the same size of columns in all dimensions. Also, the tensors can contain only numeric data types. The two fundamental attributes of a tensor are: Shape: refers to the dimensionality of array or matrix Rank: refers to the number of dimensions present in tensor Code: Python3 # importing torchimport torch # creating a tensorst1=torch.tensor([1, 2, 3, 4])t2=torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) # printing the tensors:print("Tensor t1: \n", t1)print("\nTensor t2: \n", t2) # rank of tensorsprint("\nRank of t1: ", len(t1.shape))print("Rank of t2: ", len(t2.shape)) # shape of tensorsprint("\nRank of t1: ", t1.shape)print("Rank of t2: ", t2.shape) Output: There are various methods to create a tensor in PyTorch. A tensor can contain elements of a single data type. We can create a tensor using a python list or NumPy array. The torch has 10 variants of tensors for both GPU and CPU. Below are different ways of defining a tensor. torch.Tensor() : It copies the data and creates its tensor. It is an alias for torch.FloatTensor. torch.tensor() : It also copies the data to create a tensor; however, it infers the data type automatically. torch.as_tensor() : The data is shared and not copied in this case while creating the data and accepts any type of array for tensor creation. torch.from_numpy() : It is similar to tensor.as_tensor() however it accepts only numpy array. Code: Python3 # importing torch moduleimport torchimport numpy as np # list of values to be stored as tensordata1 = [1, 2, 3, 4, 5, 6]data2 = np.array([1.5, 3.4, 6.8, 9.3, 7.0, 2.8]) # creating tensors and printingt1 = torch.tensor(data1)t2 = torch.Tensor(data1)t3 = torch.as_tensor(data2)t4 = torch.from_numpy(data2) print("Tensor: ",t1, "Data type: ", t1.dtype,"\n")print("Tensor: ",t2, "Data type: ", t2.dtype,"\n")print("Tensor: ",t3, "Data type: ", t3.dtype,"\n")print("Tensor: ",t4, "Data type: ", t4.dtype,"\n") Output: We can modify the shape and size of a tensor as desired in PyTorch. We can also create a transpose of an n-d tensor. Below are three common ways to change the structure of your tensor as desired: .reshape(a, b) : returns a new tensor with size a,b .resize(a, b) : returns the same tensor with the size a,b .transpose(a, b) : returns a tensor transposed in a and b dimension A 2*3 matrix has been reshaped and transposed to 3*2. We can visualize the change in the arrangement of the elements in the tensor in both cases. Code: Python3 # import torch moduleimport torch # defining tensort = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) # reshaping the tensorprint("Reshaping")print(t.reshape(6, 2)) # resizing the tensorprint("\nResizing")print(t.resize(2, 6)) # transposing the tensorprint("\nTransposing")print(t.transpose(1, 0)) We can perform various mathematical operations on tensors using Pytorch. The code for performing Mathematical operations is the same as in the case with NumPy arrays. Below is the code for performing the four basic operations in tensors. Python3 # import torch moduleimport torch # defining two tensorst1 = torch.tensor([1, 2, 3, 4])t2 = torch.tensor([5, 6, 7, 8]) # adding two tensorsprint("tensor2 + tensor1")print(torch.add(t2, t1)) # subtracting two tensorprint("\ntensor2 - tensor1")print(torch.sub(t2, t1)) # multiplying two tensorsprint("\ntensor2 * tensor1")print(torch.mul(t2, t1)) # diving two tensorsprint("\ntensor2 / tensor1")print(torch.div(t2, t1)) Output: For getting into further in-depth matrix multiplication using Pytorch please refer to this article. The PyTorch library modules are essential to create and train neural networks. The three main library modules are Autograd, Optim, and nn. # 1. Autograd Module: The autograd provides the functionality of easy calculation of gradients without the explicitly manual implementation of forward and backward pass for all layers. For training any neural network we perform backpropagation to calculate the gradient. By calling the .backward() function we can calculate every gradient from the root to the leaf. Code: Python3 # importing torchimport torch # creating a tensort1=torch.tensor(1.0, requires_grad = True)t2=torch.tensor(2.0, requires_grad = True) # creating a variable and gradientz=100 * t1 * t2z.backward() # printing gradientprint("dz/dt1 : ", t1.grad.data)print("dz/dt2 : ", t2.grad.data) Output: # 2. Optim Module: PyTorch Optium Module which helps in the implementation of various optimization algorithms. This package contains the most commonly used algorithms like Adam, SGD, and RMS-Prop. To use torch.optim we first need to construct an Optimizer object which will keep the parameters and update it accordingly. First, we define the Optimizer by providing the optimizer algorithm we want to use. We set the gradients to zero before backpropagation. Then for updation of parameters the optimizer.step() is called. optimizer = torch.optim.Adam(model.parameters(), lr=0.01) #defining optimizer optimizer.zero_grad() #setting gradients to zero optimizer.step() #parameter updation # 3. nn Module: This package helps in the construction of neural networks. It is used to build layers. For creating a model with a single layer we can simply define it by using nn.Sequential(). model = nn.Sequential( nn.Linear(in, out), nn.Sigmoid(), nn.Linear(_in, _out), nn.Sigmoid() ) For the implementation of the model which is not in a single sequence, we define a model by subclassing the nn.Module class. Python3 class Model (nn.Module) : def __init__(self): super(Model, self).__init__() self.linear = torch.nn.Linear(1, 1) def forward(self, x): y_pred = self.linear(x) return y_pred The torch.utils.data.Dataset class contains all the custom datasets. We need to implement two methods, __len__() and __get_item__(), to create our own dataset class. The PyTorch Dataloader has an amazing feature of loading the dataset in parallel with automatic batching. It, therefore, reduces the time of loading the dataset sequentially hence enhancing the speed. Syntax: DataLoader(dataset, shuffle=True, sampler=None, batch_sampler=None, batch_size=32) The PyTorch DataLoader supports two types of datasets: Map-style datasets: The data items are mapped to the indexes. In these datasets, the __get_item__() method is used to retrieve the index of each item. Iterable-style datasets: In these datasets __iter__() protocol is implemented. The data samples are retrieved in sequence. Please refer to the article on Using a DataLoader in PyTorch to know more. We will see this in a stepwise implementation: Dataset Preparation: As everything in PyTorch is represented in the form of tensors, so we should first in tensors.Building model: For building a neutral network first we first define the number of input layers, hidden layers, and output layers. We also need to define the initial weights. The values of the weights matrices are chosen randomly using torch.randn(). Torch.randn() returns a tensor consisting of random numbers from a standard normal distribution.Forward Propagation: The data is fed to a neural network and a matrix multiplication is performed between the weights and input. This can be easily done using a torch.Loss computation: PyTorch.nn functions have multiple loss functions. Loss functions are used to measure the error between the predicted value to the target value.Backpropagation: It is used for optimizing weights. The weights are changed such that the loss is minimized. Dataset Preparation: As everything in PyTorch is represented in the form of tensors, so we should first in tensors. Building model: For building a neutral network first we first define the number of input layers, hidden layers, and output layers. We also need to define the initial weights. The values of the weights matrices are chosen randomly using torch.randn(). Torch.randn() returns a tensor consisting of random numbers from a standard normal distribution. Forward Propagation: The data is fed to a neural network and a matrix multiplication is performed between the weights and input. This can be easily done using a torch. Loss computation: PyTorch.nn functions have multiple loss functions. Loss functions are used to measure the error between the predicted value to the target value. Backpropagation: It is used for optimizing weights. The weights are changed such that the loss is minimized. Now let’s build a neural network from scratch: Python3 # importing torchimport torch # training input(X) and output(y)X = torch.Tensor([[1], [2], [3], [4], [5], [6]])y = torch.Tensor([[5], [10], [15], [20], [25], [30]]) class Model(torch.nn.Module): # defining layer def __init__(self): super(Model, self).__init__() self.linear = torch.nn.Linear(1, 1) # implementing forward pass def forward(self, x): y_pred = self.linear(x) return y_pred model = torch.nn.Linear(1 , 1) # defining loss function and optimizerloss_fn = torch.nn.L1Loss()optimizer = torch.optim.Adam(model.parameters(), lr = 0.01 ) for epoch in range(1000): # predicting y using initial weigths y_pred = model(X.requires_grad_()) # loss calculation loss = loss_fn(y_pred, y) # calculating gradients loss.backward() # updating weights optimizer.step() optimizer.zero_grad() # testing on new data X = torch.Tensor([[7], [8]])predicted = model(X)print(predicted) Output: anikaseth98 Picked Python-PyTorch 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 Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n22 Jul, 2021" }, { "code": null, "e": 25903, "s": 25537, "text": "Deep Learning is a branch of Machine Learning where algorithms are written which mimic the functioning of a human brain. The most commonly used libraries in deep learning are Tensorflow and PyTorch. As there are various deep learning frameworks available, one might wonder when to use PyTorch. Here are reasons why one might prefer using Pytorch for specific tasks." }, { "code": null, "e": 26117, "s": 25903, "text": "Pytorch is an open-source deep learning framework available with a Python and C++ interface. Pytorch resides inside the torch module. In PyTorch, the data that has to be processed is input in the form of a tensor." }, { "code": null, "e": 26270, "s": 26117, "text": "If you have Anaconda Python Package manager installed in your system, then using by running the following command in the terminal will install PyTorch: " }, { "code": null, "e": 26323, "s": 26270, "text": "conda install pytorch torchvision cpuonly -c pytorch" }, { "code": null, "e": 26434, "s": 26323, "text": "If you want to use PyTorch without explicitly installing it into your local machine, you can use Google Colab." }, { "code": null, "e": 26728, "s": 26434, "text": "The Pytorch is used to process the tensors. Tensors are multidimensional arrays like n-dimensional NumPy array. However, tensors can be used in GPUs as well, which is not in the case of NumPy array. PyTorch accelerates the scientific computation of tensors as it has various inbuilt functions." }, { "code": null, "e": 27028, "s": 26728, "text": "A vector is a one-dimensional tensor, and a matrix is a two-dimensional tensor. One significant difference between the Tensor and multidimensional array used in C, C++, and Java is tensors should have the same size of columns in all dimensions. Also, the tensors can contain only numeric data types." }, { "code": null, "e": 27077, "s": 27028, "text": "The two fundamental attributes of a tensor are: " }, { "code": null, "e": 27132, "s": 27077, "text": "Shape: refers to the dimensionality of array or matrix" }, { "code": null, "e": 27191, "s": 27132, "text": "Rank: refers to the number of dimensions present in tensor" }, { "code": null, "e": 27197, "s": 27191, "text": "Code:" }, { "code": null, "e": 27205, "s": 27197, "text": "Python3" }, { "code": "# importing torchimport torch # creating a tensorst1=torch.tensor([1, 2, 3, 4])t2=torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) # printing the tensors:print(\"Tensor t1: \\n\", t1)print(\"\\nTensor t2: \\n\", t2) # rank of tensorsprint(\"\\nRank of t1: \", len(t1.shape))print(\"Rank of t2: \", len(t2.shape)) # shape of tensorsprint(\"\\nRank of t1: \", t1.shape)print(\"Rank of t2: \", t2.shape)", "e": 27632, "s": 27205, "text": null }, { "code": null, "e": 27643, "s": 27635, "text": "Output:" }, { "code": null, "e": 27923, "s": 27647, "text": "There are various methods to create a tensor in PyTorch. A tensor can contain elements of a single data type. We can create a tensor using a python list or NumPy array. The torch has 10 variants of tensors for both GPU and CPU. Below are different ways of defining a tensor." }, { "code": null, "e": 28023, "s": 27925, "text": "torch.Tensor() : It copies the data and creates its tensor. It is an alias for torch.FloatTensor." }, { "code": null, "e": 28132, "s": 28023, "text": "torch.tensor() : It also copies the data to create a tensor; however, it infers the data type automatically." }, { "code": null, "e": 28274, "s": 28132, "text": "torch.as_tensor() : The data is shared and not copied in this case while creating the data and accepts any type of array for tensor creation." }, { "code": null, "e": 28368, "s": 28274, "text": "torch.from_numpy() : It is similar to tensor.as_tensor() however it accepts only numpy array." }, { "code": null, "e": 28376, "s": 28370, "text": "Code:" }, { "code": null, "e": 28386, "s": 28378, "text": "Python3" }, { "code": "# importing torch moduleimport torchimport numpy as np # list of values to be stored as tensordata1 = [1, 2, 3, 4, 5, 6]data2 = np.array([1.5, 3.4, 6.8, 9.3, 7.0, 2.8]) # creating tensors and printingt1 = torch.tensor(data1)t2 = torch.Tensor(data1)t3 = torch.as_tensor(data2)t4 = torch.from_numpy(data2) print(\"Tensor: \",t1, \"Data type: \", t1.dtype,\"\\n\")print(\"Tensor: \",t2, \"Data type: \", t2.dtype,\"\\n\")print(\"Tensor: \",t3, \"Data type: \", t3.dtype,\"\\n\")print(\"Tensor: \",t4, \"Data type: \", t4.dtype,\"\\n\")", "e": 28906, "s": 28386, "text": null }, { "code": null, "e": 28916, "s": 28906, "text": " Output:" }, { "code": null, "e": 29115, "s": 28918, "text": " We can modify the shape and size of a tensor as desired in PyTorch. We can also create a transpose of an n-d tensor. Below are three common ways to change the structure of your tensor as desired:" }, { "code": null, "e": 29167, "s": 29115, "text": ".reshape(a, b) : returns a new tensor with size a,b" }, { "code": null, "e": 29225, "s": 29167, "text": ".resize(a, b) : returns the same tensor with the size a,b" }, { "code": null, "e": 29293, "s": 29225, "text": ".transpose(a, b) : returns a tensor transposed in a and b dimension" }, { "code": null, "e": 29442, "s": 29295, "text": "A 2*3 matrix has been reshaped and transposed to 3*2. We can visualize the change in the arrangement of the elements in the tensor in both cases. " }, { "code": null, "e": 29448, "s": 29442, "text": "Code:" }, { "code": null, "e": 29456, "s": 29448, "text": "Python3" }, { "code": "# import torch moduleimport torch # defining tensort = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) # reshaping the tensorprint(\"Reshaping\")print(t.reshape(6, 2)) # resizing the tensorprint(\"\\nResizing\")print(t.resize(2, 6)) # transposing the tensorprint(\"\\nTransposing\")print(t.transpose(1, 0))", "e": 29799, "s": 29456, "text": null }, { "code": null, "e": 30042, "s": 29804, "text": "We can perform various mathematical operations on tensors using Pytorch. The code for performing Mathematical operations is the same as in the case with NumPy arrays. Below is the code for performing the four basic operations in tensors." }, { "code": null, "e": 30050, "s": 30042, "text": "Python3" }, { "code": "# import torch moduleimport torch # defining two tensorst1 = torch.tensor([1, 2, 3, 4])t2 = torch.tensor([5, 6, 7, 8]) # adding two tensorsprint(\"tensor2 + tensor1\")print(torch.add(t2, t1)) # subtracting two tensorprint(\"\\ntensor2 - tensor1\")print(torch.sub(t2, t1)) # multiplying two tensorsprint(\"\\ntensor2 * tensor1\")print(torch.mul(t2, t1)) # diving two tensorsprint(\"\\ntensor2 / tensor1\")print(torch.div(t2, t1))", "e": 30468, "s": 30050, "text": null }, { "code": null, "e": 30479, "s": 30471, "text": "Output:" }, { "code": null, "e": 30584, "s": 30483, "text": "For getting into further in-depth matrix multiplication using Pytorch please refer to this article. " }, { "code": null, "e": 30724, "s": 30584, "text": "The PyTorch library modules are essential to create and train neural networks. The three main library modules are Autograd, Optim, and nn. " }, { "code": null, "e": 30910, "s": 30724, "text": "# 1. Autograd Module: The autograd provides the functionality of easy calculation of gradients without the explicitly manual implementation of forward and backward pass for all layers. " }, { "code": null, "e": 31093, "s": 30910, "text": "For training any neural network we perform backpropagation to calculate the gradient. By calling the .backward() function we can calculate every gradient from the root to the leaf. " }, { "code": null, "e": 31099, "s": 31093, "text": "Code:" }, { "code": null, "e": 31107, "s": 31099, "text": "Python3" }, { "code": "# importing torchimport torch # creating a tensort1=torch.tensor(1.0, requires_grad = True)t2=torch.tensor(2.0, requires_grad = True) # creating a variable and gradientz=100 * t1 * t2z.backward() # printing gradientprint(\"dz/dt1 : \", t1.grad.data)print(\"dz/dt2 : \", t2.grad.data)", "e": 31387, "s": 31107, "text": null }, { "code": null, "e": 31397, "s": 31387, "text": " Output:" }, { "code": null, "e": 31924, "s": 31401, "text": "# 2. Optim Module: PyTorch Optium Module which helps in the implementation of various optimization algorithms. This package contains the most commonly used algorithms like Adam, SGD, and RMS-Prop. To use torch.optim we first need to construct an Optimizer object which will keep the parameters and update it accordingly. First, we define the Optimizer by providing the optimizer algorithm we want to use. We set the gradients to zero before backpropagation. Then for updation of parameters the optimizer.step() is called. " }, { "code": null, "e": 32002, "s": 31924, "text": "optimizer = torch.optim.Adam(model.parameters(), lr=0.01) #defining optimizer" }, { "code": null, "e": 32051, "s": 32002, "text": "optimizer.zero_grad() #setting gradients to zero" }, { "code": null, "e": 32089, "s": 32051, "text": "optimizer.step() #parameter updation " }, { "code": null, "e": 32195, "s": 32091, "text": "# 3. nn Module: This package helps in the construction of neural networks. It is used to build layers. " }, { "code": null, "e": 32286, "s": 32195, "text": "For creating a model with a single layer we can simply define it by using nn.Sequential()." }, { "code": null, "e": 32380, "s": 32286, "text": "model = nn.Sequential( nn.Linear(in, out), nn.Sigmoid(), nn.Linear(_in, _out), nn.Sigmoid() )" }, { "code": null, "e": 32506, "s": 32380, "text": "For the implementation of the model which is not in a single sequence, we define a model by subclassing the nn.Module class. " }, { "code": null, "e": 32516, "s": 32508, "text": "Python3" }, { "code": "class Model (nn.Module) : def __init__(self): super(Model, self).__init__() self.linear = torch.nn.Linear(1, 1) def forward(self, x): y_pred = self.linear(x) return y_pred", "e": 32759, "s": 32516, "text": null }, { "code": null, "e": 32931, "s": 32764, "text": "The torch.utils.data.Dataset class contains all the custom datasets. We need to implement two methods, __len__() and __get_item__(), to create our own dataset class. " }, { "code": null, "e": 33135, "s": 32933, "text": "The PyTorch Dataloader has an amazing feature of loading the dataset in parallel with automatic batching. It, therefore, reduces the time of loading the dataset sequentially hence enhancing the speed. " }, { "code": null, "e": 33228, "s": 33137, "text": "Syntax: DataLoader(dataset, shuffle=True, sampler=None, batch_sampler=None, batch_size=32)" }, { "code": null, "e": 33285, "s": 33230, "text": "The PyTorch DataLoader supports two types of datasets:" }, { "code": null, "e": 33436, "s": 33285, "text": "Map-style datasets: The data items are mapped to the indexes. In these datasets, the __get_item__() method is used to retrieve the index of each item." }, { "code": null, "e": 33560, "s": 33436, "text": "Iterable-style datasets: In these datasets __iter__() protocol is implemented. The data samples are retrieved in sequence. " }, { "code": null, "e": 33636, "s": 33560, "text": "Please refer to the article on Using a DataLoader in PyTorch to know more. " }, { "code": null, "e": 33685, "s": 33638, "text": "We will see this in a stepwise implementation:" }, { "code": null, "e": 34585, "s": 33685, "text": "Dataset Preparation: As everything in PyTorch is represented in the form of tensors, so we should first in tensors.Building model: For building a neutral network first we first define the number of input layers, hidden layers, and output layers. We also need to define the initial weights. The values of the weights matrices are chosen randomly using torch.randn(). Torch.randn() returns a tensor consisting of random numbers from a standard normal distribution.Forward Propagation: The data is fed to a neural network and a matrix multiplication is performed between the weights and input. This can be easily done using a torch.Loss computation: PyTorch.nn functions have multiple loss functions. Loss functions are used to measure the error between the predicted value to the target value.Backpropagation: It is used for optimizing weights. The weights are changed such that the loss is minimized." }, { "code": null, "e": 34701, "s": 34585, "text": "Dataset Preparation: As everything in PyTorch is represented in the form of tensors, so we should first in tensors." }, { "code": null, "e": 35049, "s": 34701, "text": "Building model: For building a neutral network first we first define the number of input layers, hidden layers, and output layers. We also need to define the initial weights. The values of the weights matrices are chosen randomly using torch.randn(). Torch.randn() returns a tensor consisting of random numbers from a standard normal distribution." }, { "code": null, "e": 35217, "s": 35049, "text": "Forward Propagation: The data is fed to a neural network and a matrix multiplication is performed between the weights and input. This can be easily done using a torch." }, { "code": null, "e": 35380, "s": 35217, "text": "Loss computation: PyTorch.nn functions have multiple loss functions. Loss functions are used to measure the error between the predicted value to the target value." }, { "code": null, "e": 35489, "s": 35380, "text": "Backpropagation: It is used for optimizing weights. The weights are changed such that the loss is minimized." }, { "code": null, "e": 35538, "s": 35491, "text": "Now let’s build a neural network from scratch:" }, { "code": null, "e": 35548, "s": 35540, "text": "Python3" }, { "code": "# importing torchimport torch # training input(X) and output(y)X = torch.Tensor([[1], [2], [3], [4], [5], [6]])y = torch.Tensor([[5], [10], [15], [20], [25], [30]]) class Model(torch.nn.Module): # defining layer def __init__(self): super(Model, self).__init__() self.linear = torch.nn.Linear(1, 1) # implementing forward pass def forward(self, x): y_pred = self.linear(x) return y_pred model = torch.nn.Linear(1 , 1) # defining loss function and optimizerloss_fn = torch.nn.L1Loss()optimizer = torch.optim.Adam(model.parameters(), lr = 0.01 ) for epoch in range(1000): # predicting y using initial weigths y_pred = model(X.requires_grad_()) # loss calculation loss = loss_fn(y_pred, y) # calculating gradients loss.backward() # updating weights optimizer.step() optimizer.zero_grad() # testing on new data X = torch.Tensor([[7], [8]])predicted = model(X)print(predicted)", "e": 36534, "s": 35548, "text": null }, { "code": null, "e": 36545, "s": 36537, "text": "Output:" }, { "code": null, "e": 36561, "s": 36549, "text": "anikaseth98" }, { "code": null, "e": 36568, "s": 36561, "text": "Picked" }, { "code": null, "e": 36583, "s": 36568, "text": "Python-PyTorch" }, { "code": null, "e": 36590, "s": 36583, "text": "Python" }, { "code": null, "e": 36688, "s": 36590, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36720, "s": 36688, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 36762, "s": 36720, "text": "Check if element exists in list in Python" }, { "code": null, "e": 36804, "s": 36762, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 36831, "s": 36804, "text": "Python Classes and Objects" }, { "code": null, "e": 36887, "s": 36831, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 36926, "s": 36887, "text": "Python | Get unique values from a list" }, { "code": null, "e": 36948, "s": 36926, "text": "Defaultdict in Python" }, { "code": null, "e": 36979, "s": 36948, "text": "Python | os.path.join() method" }, { "code": null, "e": 37008, "s": 36979, "text": "Create a directory in Python" } ]
Native MongoDB driver for Node.js - GeeksforGeeks
08 Oct, 2021 The native MongoDB driver for Node.JS is a dependency that allows our JavaScript application to interact with the NoSQL database, either locally or on the cloud through MongoDB Atlas. We are allowed to use promises as well as callbacks that gives us greater flexibility in using ES6 features. In order to start working with the MongoDB driver, we shall first create a new folder and initialize our project: npm init -y Here, -y is a flag which will initialize our project with default values. We will install the MongoDB driver and save it as a dependency with the following command: npm install mongodb --save In our JavaScript entry point file, for the sake of convenience, we shall name app.js and we will write the following code to connect to the server: JavaScript // Importing MongoClient from mongodb driverconst { MongoClient } = require('mongodb'); // Conencting to a local portconst uri = 'mongodb://127.0.0.1:27017'; const client = new MongoClient(uri, { useUnifiedTopology: true, useNewUrlParser: true}); connect(); // ESNext syntax using async-awaitasync function connect() { try { await client.connect(); const db = client.db('cars'); console.log( `Successfully connected to db ${db.databaseName}`); } catch (err) { console.error(`we encountered ${err}`); } finally { client.close(); }} Output: Successfully connected to db cars Now that we have made the connection, let us see some basic Insertion, Read, Update and Delete Operations on our database:Insertion and Read: In the following code snippet we are going to deal with Insertion and Read operation. JavaScript const { MongoClient } = require('mongodb');const uri = 'mongodb://127.0.0.1:27017'; const client = new MongoClient(uri, { useUnifiedTopology: true, useNewUrlParser: true }); connect(); async function connect() { try { await client.connect(); const db = client.db('cars'); console.log( `Successfully connected to db ${db.databaseName}`); const sportsCars = db.collection('SportsCars'); // Insertion const cursorInsertion = await sportsCars.insertMany([ { 'company': 'mercedes', 'series': 'Black Series', 'model': 'SLS AMG' }, { 'company': 'Audi', 'series': 'A series', 'model': 'A8' }]); console.log(cursorInsertion.insertedCount); // Display const cursorFind = sportsCars.find(); const data = await cursorFind.toArray(); console.table(data); } catch (err) { console.error(`we encountered ${err}`); } finally { client.close(); }} Explanation: A collection called sports cars is created using the collections() method. For Insertion, we use the two following methods: insertMany() method: This method is used to insert more than one entry into the database with the help of cursors. In this case, it takes an array of objects as parametes. The method returns a promise, hence we used the await keyword. Alternatively, the method insertOne() is used to insert a single document into the table.InsertedCount: This function is used to count the number of insertions that were made. insertMany() method: This method is used to insert more than one entry into the database with the help of cursors. In this case, it takes an array of objects as parametes. The method returns a promise, hence we used the await keyword. Alternatively, the method insertOne() is used to insert a single document into the table. InsertedCount: This function is used to count the number of insertions that were made. For Display we used the following methods: find(): This method is used to find all the documents in the database with the help of cursors.toArray(): This method uses the cursor element received from the find() method to store the database in an array of objects. This method returns a promise, hence we have used the keyword await. find(): This method is used to find all the documents in the database with the help of cursors. toArray(): This method uses the cursor element received from the find() method to store the database in an array of objects. This method returns a promise, hence we have used the keyword await. The Output of the Snippet is as follows: Update: The following code snippet will help us to update a database element and then we shall display the updated database: JavaScript const { MongoClient } = require('mongodb');const uri = 'mongodb://127.0.0.1:27017'; const client = new MongoClient(uri, { useUnifiedTopology: true, useNewUrlParser: true }); connect(); async function connect() { try { await client.connect(); const db = client.db('cars'); const sportsCars = db.collection('SportsCars'); //update const cursorUpdate = await sportsCars.updateOne( { "company": "mercedes" }, { "$set": { "status": "sold" } } ); console.log(cursorUpdate.modifiedCount); // Display const cursorFind = sportsCars.find(); const data = await cursorFind.toArray(); console.table(data); } catch (err) { console.error(`we encountered ${err}`); } finally { client.close(); }} Explanation: We use the following methods for updating the database: updateOne() method: This methods allows us to update one entry. The first argument it takes is a key-value pair corresponding to the database entry as we want to update. It can be any of the properties that the element possesses. The second argument is an update command $set, which is paired with an object. The object is again a key-value pair of either an existing or a new property. If the property already exists, then the property is updated with the value passed. If it does not exist, then it is added. This method returns a promise, hence we use the keyword await. Alternatively, updateMany() method can be used to update multiple documents.modifiedCount: This method is called on the cursor element received from the previous method and gives us a count of the number of entries updated. updateOne() method: This methods allows us to update one entry. The first argument it takes is a key-value pair corresponding to the database entry as we want to update. It can be any of the properties that the element possesses. The second argument is an update command $set, which is paired with an object. The object is again a key-value pair of either an existing or a new property. If the property already exists, then the property is updated with the value passed. If it does not exist, then it is added. This method returns a promise, hence we use the keyword await. Alternatively, updateMany() method can be used to update multiple documents. modifiedCount: This method is called on the cursor element received from the previous method and gives us a count of the number of entries updated. Output: Deleting an Entry: In the following snippet, we will delete an entry based on series: JavaScript const { MongoClient } = require('mongodb');const uri = 'mongodb://127.0.0.1:27017'; const client = new MongoClient(uri, { useUnifiedTopology: true, useNewUrlParser: true }); connect(); async function connect() { try { await client.connect(); const db = client.db('cars'); const sportsCars = db.collection('SportsCars'); //Delete const cursorDelete = await sportsCars .deleteOne({ "series": "A series" }); console.log(cursorDelete.deletedCount); // Display const cursorFind = sportsCars.find(); const data = await cursorFind.toArray(); console.table(data); } catch (err) { console.error(`we encountered ${err}`); } finally { client.close(); }} Explanation: We use the following methods to delete the entry “company” : “Audi” from the database: deleteOne: This method is used to delete one entry from the database. It takes in a key-value pair which corresponds to the entry that we want to delete. This method returns a promise. Hence, we use the keyword await. Alternatively, deleteMany() method can be used to delete multiple documents at once.deletedCount: This method is called on the cursor element received from the previous method and it returns the number of deletions that were made. deleteOne: This method is used to delete one entry from the database. It takes in a key-value pair which corresponds to the entry that we want to delete. This method returns a promise. Hence, we use the keyword await. Alternatively, deleteMany() method can be used to delete multiple documents at once. deletedCount: This method is called on the cursor element received from the previous method and it returns the number of deletions that were made. Output: Hence, Node and MongoDB can be easily used to make efficient backend CRUD apis. Node.js-Misc Picked MongoDB Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Spring Boot JpaRepository with Example Aggregation in MongoDB Mongoose Populate() Method MongoDB - Check the existence of the fields in the specified collection How to build a basic CRUD app with Node.js and ReactJS ? Installation of Node.js on Linux How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method Node.js fs.readFile() Method
[ { "code": null, "e": 25669, "s": 25641, "text": "\n08 Oct, 2021" }, { "code": null, "e": 25963, "s": 25669, "text": "The native MongoDB driver for Node.JS is a dependency that allows our JavaScript application to interact with the NoSQL database, either locally or on the cloud through MongoDB Atlas. We are allowed to use promises as well as callbacks that gives us greater flexibility in using ES6 features. " }, { "code": null, "e": 26078, "s": 25963, "text": "In order to start working with the MongoDB driver, we shall first create a new folder and initialize our project: " }, { "code": null, "e": 26091, "s": 26078, "text": "npm init -y\n" }, { "code": null, "e": 26166, "s": 26091, "text": "Here, -y is a flag which will initialize our project with default values. " }, { "code": null, "e": 26258, "s": 26166, "text": "We will install the MongoDB driver and save it as a dependency with the following command: " }, { "code": null, "e": 26286, "s": 26258, "text": "npm install mongodb --save\n" }, { "code": null, "e": 26436, "s": 26286, "text": "In our JavaScript entry point file, for the sake of convenience, we shall name app.js and we will write the following code to connect to the server: " }, { "code": null, "e": 26447, "s": 26436, "text": "JavaScript" }, { "code": "// Importing MongoClient from mongodb driverconst { MongoClient } = require('mongodb'); // Conencting to a local portconst uri = 'mongodb://127.0.0.1:27017'; const client = new MongoClient(uri, { useUnifiedTopology: true, useNewUrlParser: true}); connect(); // ESNext syntax using async-awaitasync function connect() { try { await client.connect(); const db = client.db('cars'); console.log( `Successfully connected to db ${db.databaseName}`); } catch (err) { console.error(`we encountered ${err}`); } finally { client.close(); }}", "e": 27044, "s": 26447, "text": null }, { "code": null, "e": 27054, "s": 27044, "text": "Output: " }, { "code": null, "e": 27088, "s": 27054, "text": "Successfully connected to db cars" }, { "code": null, "e": 27316, "s": 27088, "text": "Now that we have made the connection, let us see some basic Insertion, Read, Update and Delete Operations on our database:Insertion and Read: In the following code snippet we are going to deal with Insertion and Read operation." }, { "code": null, "e": 27327, "s": 27316, "text": "JavaScript" }, { "code": "const { MongoClient } = require('mongodb');const uri = 'mongodb://127.0.0.1:27017'; const client = new MongoClient(uri, { useUnifiedTopology: true, useNewUrlParser: true }); connect(); async function connect() { try { await client.connect(); const db = client.db('cars'); console.log( `Successfully connected to db ${db.databaseName}`); const sportsCars = db.collection('SportsCars'); // Insertion const cursorInsertion = await sportsCars.insertMany([ { 'company': 'mercedes', 'series': 'Black Series', 'model': 'SLS AMG' }, { 'company': 'Audi', 'series': 'A series', 'model': 'A8' }]); console.log(cursorInsertion.insertedCount); // Display const cursorFind = sportsCars.find(); const data = await cursorFind.toArray(); console.table(data); } catch (err) { console.error(`we encountered ${err}`); } finally { client.close(); }}", "e": 28431, "s": 27327, "text": null }, { "code": null, "e": 28570, "s": 28431, "text": "Explanation: A collection called sports cars is created using the collections() method. For Insertion, we use the two following methods: " }, { "code": null, "e": 28981, "s": 28570, "text": "insertMany() method: This method is used to insert more than one entry into the database with the help of cursors. In this case, it takes an array of objects as parametes. The method returns a promise, hence we used the await keyword. Alternatively, the method insertOne() is used to insert a single document into the table.InsertedCount: This function is used to count the number of insertions that were made." }, { "code": null, "e": 29306, "s": 28981, "text": "insertMany() method: This method is used to insert more than one entry into the database with the help of cursors. In this case, it takes an array of objects as parametes. The method returns a promise, hence we used the await keyword. Alternatively, the method insertOne() is used to insert a single document into the table." }, { "code": null, "e": 29393, "s": 29306, "text": "InsertedCount: This function is used to count the number of insertions that were made." }, { "code": null, "e": 29436, "s": 29393, "text": "For Display we used the following methods:" }, { "code": null, "e": 29725, "s": 29436, "text": "find(): This method is used to find all the documents in the database with the help of cursors.toArray(): This method uses the cursor element received from the find() method to store the database in an array of objects. This method returns a promise, hence we have used the keyword await." }, { "code": null, "e": 29821, "s": 29725, "text": "find(): This method is used to find all the documents in the database with the help of cursors." }, { "code": null, "e": 30015, "s": 29821, "text": "toArray(): This method uses the cursor element received from the find() method to store the database in an array of objects. This method returns a promise, hence we have used the keyword await." }, { "code": null, "e": 30056, "s": 30015, "text": "The Output of the Snippet is as follows:" }, { "code": null, "e": 30181, "s": 30056, "text": "Update: The following code snippet will help us to update a database element and then we shall display the updated database:" }, { "code": null, "e": 30192, "s": 30181, "text": "JavaScript" }, { "code": "const { MongoClient } = require('mongodb');const uri = 'mongodb://127.0.0.1:27017'; const client = new MongoClient(uri, { useUnifiedTopology: true, useNewUrlParser: true }); connect(); async function connect() { try { await client.connect(); const db = client.db('cars'); const sportsCars = db.collection('SportsCars'); //update const cursorUpdate = await sportsCars.updateOne( { \"company\": \"mercedes\" }, { \"$set\": { \"status\": \"sold\" } } ); console.log(cursorUpdate.modifiedCount); // Display const cursorFind = sportsCars.find(); const data = await cursorFind.toArray(); console.table(data); } catch (err) { console.error(`we encountered ${err}`); } finally { client.close(); }}", "e": 31027, "s": 30192, "text": null }, { "code": null, "e": 31096, "s": 31027, "text": "Explanation: We use the following methods for updating the database:" }, { "code": null, "e": 31894, "s": 31096, "text": "updateOne() method: This methods allows us to update one entry. The first argument it takes is a key-value pair corresponding to the database entry as we want to update. It can be any of the properties that the element possesses. The second argument is an update command $set, which is paired with an object. The object is again a key-value pair of either an existing or a new property. If the property already exists, then the property is updated with the value passed. If it does not exist, then it is added. This method returns a promise, hence we use the keyword await. Alternatively, updateMany() method can be used to update multiple documents.modifiedCount: This method is called on the cursor element received from the previous method and gives us a count of the number of entries updated." }, { "code": null, "e": 32545, "s": 31894, "text": "updateOne() method: This methods allows us to update one entry. The first argument it takes is a key-value pair corresponding to the database entry as we want to update. It can be any of the properties that the element possesses. The second argument is an update command $set, which is paired with an object. The object is again a key-value pair of either an existing or a new property. If the property already exists, then the property is updated with the value passed. If it does not exist, then it is added. This method returns a promise, hence we use the keyword await. Alternatively, updateMany() method can be used to update multiple documents." }, { "code": null, "e": 32693, "s": 32545, "text": "modifiedCount: This method is called on the cursor element received from the previous method and gives us a count of the number of entries updated." }, { "code": null, "e": 32703, "s": 32693, "text": "Output: " }, { "code": null, "e": 32789, "s": 32703, "text": "Deleting an Entry: In the following snippet, we will delete an entry based on series:" }, { "code": null, "e": 32800, "s": 32789, "text": "JavaScript" }, { "code": "const { MongoClient } = require('mongodb');const uri = 'mongodb://127.0.0.1:27017'; const client = new MongoClient(uri, { useUnifiedTopology: true, useNewUrlParser: true }); connect(); async function connect() { try { await client.connect(); const db = client.db('cars'); const sportsCars = db.collection('SportsCars'); //Delete const cursorDelete = await sportsCars .deleteOne({ \"series\": \"A series\" }); console.log(cursorDelete.deletedCount); // Display const cursorFind = sportsCars.find(); const data = await cursorFind.toArray(); console.table(data); } catch (err) { console.error(`we encountered ${err}`); } finally { client.close(); }}", "e": 33584, "s": 32800, "text": null }, { "code": null, "e": 33684, "s": 33584, "text": "Explanation: We use the following methods to delete the entry “company” : “Audi” from the database:" }, { "code": null, "e": 34133, "s": 33684, "text": "deleteOne: This method is used to delete one entry from the database. It takes in a key-value pair which corresponds to the entry that we want to delete. This method returns a promise. Hence, we use the keyword await. Alternatively, deleteMany() method can be used to delete multiple documents at once.deletedCount: This method is called on the cursor element received from the previous method and it returns the number of deletions that were made." }, { "code": null, "e": 34436, "s": 34133, "text": "deleteOne: This method is used to delete one entry from the database. It takes in a key-value pair which corresponds to the entry that we want to delete. This method returns a promise. Hence, we use the keyword await. Alternatively, deleteMany() method can be used to delete multiple documents at once." }, { "code": null, "e": 34583, "s": 34436, "text": "deletedCount: This method is called on the cursor element received from the previous method and it returns the number of deletions that were made." }, { "code": null, "e": 34591, "s": 34583, "text": "Output:" }, { "code": null, "e": 34671, "s": 34591, "text": "Hence, Node and MongoDB can be easily used to make efficient backend CRUD apis." }, { "code": null, "e": 34684, "s": 34671, "text": "Node.js-Misc" }, { "code": null, "e": 34691, "s": 34684, "text": "Picked" }, { "code": null, "e": 34699, "s": 34691, "text": "MongoDB" }, { "code": null, "e": 34707, "s": 34699, "text": "Node.js" }, { "code": null, "e": 34724, "s": 34707, "text": "Web Technologies" }, { "code": null, "e": 34822, "s": 34724, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34861, "s": 34822, "text": "Spring Boot JpaRepository with Example" }, { "code": null, "e": 34884, "s": 34861, "text": "Aggregation in MongoDB" }, { "code": null, "e": 34911, "s": 34884, "text": "Mongoose Populate() Method" }, { "code": null, "e": 34983, "s": 34911, "text": "MongoDB - Check the existence of the fields in the specified collection" }, { "code": null, "e": 35040, "s": 34983, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 35073, "s": 35040, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 35121, "s": 35073, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 35154, "s": 35121, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 35184, "s": 35154, "text": "Node.js fs.writeFile() Method" } ]
Construct BST from given preorder traversal | Set 1 - GeeksforGeeks
09 Mar, 2022 Given preorder traversal of a binary search tree, construct the BST. For example, if the given traversal is {10, 5, 1, 7, 40, 50}, then the output should be the root of the following tree. 10 / \ 5 40 / \ \ 1 7 50 Method 1 ( O(n2) time complexity ) The first element of preorder traversal is always root. We first construct the root. Then we find the index of the first element which is greater than the root. Let the index be ‘i’. The values between root and ‘i’ will be part of the left subtree, and the values between ‘i'(inclusive) and ‘n-1’ will be part of the right subtree. Divide given pre[] at index “i” and recur for left and right sub-trees. For example in {10, 5, 1, 7, 40, 50}, 10 is the first element, so we make it root. Now we look for the first element greater than 10, we find 40. So we know the structure of BST is as following. 10 / \ / \ {5, 1, 7} {40, 50} We recursively follow above steps for subarrays {5, 1, 7} and {40, 50}, and get the complete tree. C++ C Java Python3 C# /* A O(n^2) program for construction of BST from preorder * traversal */#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */class node {public: int data; node* left; node* right;}; // A utility function to create a nodenode* newNode(int data){ node* temp = new node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // A recursive function to construct Full from pre[].// preIndex is used to keep track of index in pre[].node* constructTreeUtil(int pre[], int* preIndex, int low, int high, int size){ // Base case if (*preIndex >= size || low > high) return NULL; // The first node in preorder traversal is root. So take // the node at preIndex from pre[] and make it root, and // increment preIndex node* root = newNode(pre[*preIndex]); *preIndex = *preIndex + 1; // If the current subarray has only one element, no need // to recur if (low == high) return root; // Search for the first element greater than root int i; for (i = low; i <= high; ++i) if (pre[i] > root->data) break; // Use the index of element found in preorder to divide // preorder array in two parts. Left subtree and right // subtree root->left = constructTreeUtil(pre, preIndex, *preIndex, i - 1, size); root->right = constructTreeUtil(pre, preIndex, i, high, size); return root;} // The main function to construct BST from given preorder// traversal. This function mainly uses constructTreeUtil()node* constructTree(int pre[], int size){ int preIndex = 0; return constructTreeUtil(pre, &preIndex, 0, size - 1, size);} // A utility function to print inorder traversal of a Binary// Treevoid printInorder(node* node){ if (node == NULL) return; printInorder(node->left); cout << node->data << " "; printInorder(node->right);} // Driver codeint main(){ int pre[] = { 10, 5, 1, 7, 40, 50 }; int size = sizeof(pre) / sizeof(pre[0]); node* root = constructTree(pre, size); cout << "Inorder traversal of the constructed tree: \n"; printInorder(root); return 0;} // This code is contributed by rathbhupendra /* A O(n^2) program for construction of BST from preorder * traversal */#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node { int data; struct node* left; struct node* right;}; // A utility function to create a nodestruct node* newNode(int data){ struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->data = data; temp->left = temp->right = NULL; return temp;} // A recursive function to construct Full from pre[].// preIndex is used to keep track of index in pre[].struct node* constructTreeUtil(int pre[], int* preIndex, int low, int high, int size){ // Base case if (*preIndex >= size || low > high) return NULL; // The first node in preorder traversal is root. So take // the node at preIndex from pre[] and make it root, and // increment preIndex struct node* root = newNode(pre[*preIndex]); *preIndex = *preIndex + 1; // If the current subarray has only one element, no need // to recur if (low == high) return root; // Search for the first element greater than root int i; for (i = low; i <= high; ++i) if (pre[i] > root->data) break; // Use the index of element found in preorder to divide // preorder array in two parts. Left subtree and right // subtree root->left = constructTreeUtil(pre, preIndex, *preIndex, i - 1, size); root->right = constructTreeUtil(pre, preIndex, i, high, size); return root;} // The main function to construct BST from given preorder// traversal. This function mainly uses constructTreeUtil()struct node* constructTree(int pre[], int size){ int preIndex = 0; return constructTreeUtil(pre, &preIndex, 0, size - 1, size);} // A utility function to print inorder traversal of a Binary// Treevoid printInorder(struct node* node){ if (node == NULL) return; printInorder(node->left); printf("%d ", node->data); printInorder(node->right);} // Driver codeint main(){ int pre[] = { 10, 5, 1, 7, 40, 50 }; int size = sizeof(pre) / sizeof(pre[0]); struct node* root = constructTree(pre, size); printf("Inorder traversal of the constructed tree: \n"); printInorder(root); return 0;} // Java program to construct BST from given preorder// traversal // A binary tree nodeclass Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} class Index { int index = 0;} class BinaryTree { Index index = new Index(); // A recursive function to construct Full from pre[]. // preIndex is used to keep track of index in pre[]. Node constructTreeUtil(int pre[], Index preIndex, int low, int high, int size) { // Base case if (preIndex.index >= size || low > high) { return null; } // The first node in preorder traversal is root. So // take the node at preIndex from pre[] and make it // root, and increment preIndex Node root = new Node(pre[preIndex.index]); preIndex.index = preIndex.index + 1; // If the current subarray has only one element, no // need to recur if (low == high) { return root; } // Search for the first element greater than root int i; for (i = low; i <= high; ++i) { if (pre[i] > root.data) { break; } } // Use the index of element found in preorder to // divide preorder array in two parts. Left subtree // and right subtree root.left = constructTreeUtil( pre, preIndex, preIndex.index, i - 1, size); root.right = constructTreeUtil(pre, preIndex, i, high, size); return root; } // The main function to construct BST from given // preorder traversal. This function mainly uses // constructTreeUtil() Node constructTree(int pre[], int size) { return constructTreeUtil(pre, index, 0, size - 1, size); } // A utility function to print inorder traversal of a // Binary Tree void printInorder(Node node) { if (node == null) { return; } printInorder(node.left); System.out.print(node.data + " "); printInorder(node.right); } // Driver code public static void main(String[] args) { BinaryTree tree = new BinaryTree(); int pre[] = new int[] { 10, 5, 1, 7, 40, 50 }; int size = pre.length; Node root = tree.constructTree(pre, size); System.out.println( "Inorder traversal of the constructed tree is "); tree.printInorder(root); }} // This code has been contributed by Mayank Jaiswal # A O(n^2) Python3 program for# construction of BST from preorder traversal # A binary tree node class Node(): # A constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # constructTreeUtil.preIndex is a static variable of# function constructTreeUtil # Function to get the value of static variable# constructTreeUtil.preIndexdef getPreIndex(): return constructTreeUtil.preIndex # Function to increment the value of static variable# constructTreeUtil.preIndex def incrementPreIndex(): constructTreeUtil.preIndex += 1 # A recurseive function to construct Full from pre[].# preIndex is used to keep track of index in pre[[]. def constructTreeUtil(pre, low, high): # Base Case if(low > high): return None # The first node in preorder traversal is root. So take # the node at preIndex from pre[] and make it root, # and increment preIndex root = Node(pre[getPreIndex()]) incrementPreIndex() # If the current subarray has onlye one element, # no need to recur if low == high: return root r_root = -1 # Search for the first element greater than root for i in range(low, high+1): if (pre[i] > root.data): r_root = i break # If no elements are greater than the current root, # all elements are left children # so assign root appropriately if r_root == -1: r_root = getPreIndex() + (high - low) # Use the index of element found in preorder to divide # preorder array in two parts. Left subtree and right # subtree root.left = constructTreeUtil(pre, getPreIndex(), r_root-1) root.right = constructTreeUtil(pre, r_root, high) return root # The main function to construct BST from given preorder# traversal. This function mailny uses constructTreeUtil() def constructTree(pre): size = len(pre) constructTreeUtil.preIndex = 0 return constructTreeUtil(pre, 0, size-1) def printInorder(root): if root is None: return printInorder(root.left) print (root.data,end=' ') printInorder(root.right) # Driver codepre = [10, 5, 1, 7, 40, 50] root = constructTree(pre)print ("Inorder traversal of the constructed tree:")printInorder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) and Rhys Compton using System; // C# program to construct BST from given preorder traversal// A binary tree nodepublic class Node { public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class Index { public int index = 0;} public class BinaryTree { public Index index = new Index(); // A recursive function to construct Full from pre[]. // preIndex is used to keep track of index in pre[]. public virtual Node constructTreeUtil(int[] pre, Index preIndex, int low, int high, int size) { // Base case if (preIndex.index >= size || low > high) { return null; } // The first node in preorder traversal is root. So // take the node at preIndex from pre[] and make it // root, and increment preIndex Node root = new Node(pre[preIndex.index]); preIndex.index = preIndex.index + 1; // If the current subarray has only one element, no // need to recur if (low == high) { return root; } // Search for the first element greater than root int i; for (i = low; i <= high; ++i) { if (pre[i] > root.data) { break; } } // Use the index of element found in preorder to // divide preorder array in two parts. Left subtree // and right subtree root.left = constructTreeUtil( pre, preIndex, preIndex.index, i - 1, size); root.right = constructTreeUtil(pre, preIndex, i, high, size); return root; } // The main function to construct BST from given // preorder traversal. This function mainly uses // constructTreeUtil() public virtual Node constructTree(int[] pre, int size) { return constructTreeUtil(pre, index, 0, size - 1, size); } // A utility function to print inorder traversal of a // Binary Tree public virtual void printInorder(Node node) { if (node == null) { return; } printInorder(node.left); Console.Write(node.data + " "); printInorder(node.right); } // Driver code public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); int[] pre = new int[] { 10, 5, 1, 7, 40, 50 }; int size = pre.Length; Node root = tree.constructTree(pre, size); Console.WriteLine( "Inorder traversal of the constructed tree is "); tree.printInorder(root); }} // This code is contributed by Shrikant13 Inorder traversal of the constructed tree: 1 5 7 10 40 50 Time Complexity: O(n2) Method 2 ( O(n) time complexity ) The idea used here is inspired by method 3 of this post. The trick is to set a range {min .. max} for every node. Initialize the range as {INT_MIN .. INT_MAX}. The first node will definitely be in range, so create a root node. To construct the left subtree, set the range as {INT_MIN ...root->data}. If a value is in the range {INT_MIN .. root->data}, the values are part of the left subtree. To construct the right subtree, set the range as {root->data..max .. INT_MAX}. Below is the implementation of the above idea: C++ C Java Python3 C# Javascript /* A O(n) program for constructionof BST from preorder traversal */#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */class node {public: int data; node* left; node* right;}; // A utility function to create a nodenode* newNode(int data){ node* temp = new node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // A recursive function to construct// BST from pre[]. preIndex is used// to keep track of index in pre[].node* constructTreeUtil(int pre[], int* preIndex, int key, int min, int max, int size){ // Base case if (*preIndex >= size) return NULL; node* root = NULL; // If current element of pre[] is in range, then // only it is part of current subtree if (key > min && key < max) { // Allocate memory for root of this // subtree and increment *preIndex root = newNode(key); *preIndex = *preIndex + 1; if (*preIndex < size) { // Construct the subtree under root // All nodes which are in range // {min .. key} will go in left // subtree, and first such node // will be root of left subtree. root->left = constructTreeUtil(pre, preIndex, pre[*preIndex], min, key, size); } if (*preIndex < size) { // All nodes which are in range // {key..max} will go in right // subtree, and first such node // will be root of right subtree. root->right = constructTreeUtil(pre, preIndex, pre[*preIndex], key, max, size); } } return root;} // The main function to construct BST// from given preorder traversal.// This function mainly uses constructTreeUtil()node* constructTree(int pre[], int size){ int preIndex = 0; return constructTreeUtil(pre, &preIndex, pre[0], INT_MIN, INT_MAX, size);} // A utility function to print inorder// traversal of a Binary Treevoid printInorder(node* node){ if (node == NULL) return; printInorder(node->left); cout << node->data << " "; printInorder(node->right);} // Driver codeint main(){ int pre[] = { 10, 5, 1, 7, 40, 50 }; int size = sizeof(pre) / sizeof(pre[0]); // Function call node* root = constructTree(pre, size); cout << "Inorder traversal of the constructed tree: \n"; printInorder(root); return 0;} // This is code is contributed by rathbhupendra /* A O(n) program for construction of BST from preorder * traversal */#include <limits.h>#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node { int data; struct node* left; struct node* right;}; // A utility function to create a nodestruct node* newNode(int data){ struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->data = data; temp->left = temp->right = NULL; return temp;} // A recursive function to construct BST from pre[].// preIndex is used to keep track of index in pre[].struct node* constructTreeUtil(int pre[], int* preIndex, int key, int min, int max, int size){ // Base case if (*preIndex >= size) return NULL; struct node* root = NULL; // If current element of pre[] is in range, then // only it is part of current subtree if (key > min && key < max) { // Allocate memory for root of this subtree and // increment *preIndex root = newNode(key); *preIndex = *preIndex + 1; if (*preIndex < size) { // Construct the subtree under root // All nodes which are in range {min .. key} // will go in left subtree, and first such node // will be root of left subtree. root->left = constructTreeUtil(pre, preIndex, pre[*preIndex], min, key, size); } if (*preIndex < size) { // All nodes which are in range {key..max} will // go in right subtree, and first such node will // be root of right subtree. root->right = constructTreeUtil(pre, preIndex, pre[*preIndex], key, max, size); } } return root;} // The main function to construct BST from given preorder// traversal. This function mainly uses constructTreeUtil()struct node* constructTree(int pre[], int size){ int preIndex = 0; return constructTreeUtil(pre, &preIndex, pre[0], INT_MIN, INT_MAX, size);} // A utility function to print inorder traversal of a Binary// Treevoid printInorder(struct node* node){ if (node == NULL) return; printInorder(node->left); printf("%d ", node->data); printInorder(node->right);} // Driver codeint main(){ int pre[] = { 10, 5, 1, 7, 40, 50 }; int size = sizeof(pre) / sizeof(pre[0]); // function call struct node* root = constructTree(pre, size); printf("Inorder traversal of the constructed tree: \n"); printInorder(root); return 0;} // Java program to construct BST from given preorder// traversal // A binary tree nodeclass Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} class Index { int index = 0;} class BinaryTree { Index index = new Index(); // A recursive function to construct BST from pre[]. // preIndex is used to keep track of index in pre[]. Node constructTreeUtil(int pre[], Index preIndex, int key, int min, int max, int size) { // Base case if (preIndex.index >= size) { return null; } Node root = null; // If current element of pre[] is in range, then // only it is part of current subtree if (key > min && key < max) { // Allocate memory for root of this // subtree and increment *preIndex root = new Node(key); preIndex.index = preIndex.index + 1; if (preIndex.index < size) { // Construct the subtree under root // All nodes which are in range {min .. key} // will go in left subtree, and first such // node will be root of left subtree. root.left = constructTreeUtil( pre, preIndex, pre[preIndex.index], min, key, size); } if (preIndex.index < size) { // All nodes which are in range {key..max} // will go in right subtree, and first such // node will be root of right subtree. root.right = constructTreeUtil( pre, preIndex, pre[preIndex.index], key, max, size); } } return root; } // The main function to construct BST from given // preorder traversal. This function mainly uses // constructTreeUtil() Node constructTree(int pre[], int size) { int preIndex = 0; return constructTreeUtil(pre, index, pre[0], Integer.MIN_VALUE, Integer.MAX_VALUE, size); } // A utility function to print inorder traversal of a // Binary Tree void printInorder(Node node) { if (node == null) { return; } printInorder(node.left); System.out.print(node.data + " "); printInorder(node.right); } // Driver code public static void main(String[] args) { BinaryTree tree = new BinaryTree(); int pre[] = new int[] { 10, 5, 1, 7, 40, 50 }; int size = pre.length; // Function call Node root = tree.constructTree(pre, size); System.out.println( "Inorder traversal of the constructed tree is "); tree.printInorder(root); }} // This code has been contributed by Mayank Jaiswal # A O(n) program for construction of BST from preorder traversal INT_MIN = -float("inf")INT_MAX = float("inf") # A Binary tree node class Node: # Constructor to created a new node def __init__(self, data): self.data = data self.left = None self.right = None # Methods to get and set the value of static variable# constructTreeUtil.preIndex for function construcTreeUtil() def getPreIndex(): return constructTreeUtil.preIndex def incrementPreIndex(): constructTreeUtil.preIndex += 1 # A recursive function to construct BST from pre[].# preIndex is used to keep track of index in pre[] def constructTreeUtil(pre, key, mini, maxi, size): # Base Case if(getPreIndex() >= size): return None root = None # If current element of pre[] is in range, then # only it is part of current subtree if(key > mini and key < maxi): # Allocate memory for root of this subtree # and increment constructTreeUtil.preIndex root = Node(key) incrementPreIndex() if(getPreIndex() < size): # Construct the subtree under root # All nodes which are in range {min.. key} will # go in left subtree, and first such node will # be root of left subtree root.left = constructTreeUtil(pre, pre[getPreIndex()], mini, key, size) if(getPreIndex() < size): # All nodes which are in range{key..max} will # go to right subtree, and first such node will # be root of right subtree root.right = constructTreeUtil(pre, pre[getPreIndex()], key, maxi, size) return root # This is the main function to construct BST from given# preorder traversal. This function mainly uses# constructTreeUtil() def constructTree(pre): constructTreeUtil.preIndex = 0 size = len(pre) return constructTreeUtil(pre, pre[0], INT_MIN, INT_MAX, size) # A utility function to print inorder traversal of Binary Treedef printInorder(node): if node is None: return printInorder(node.left) print (node.data,end=" ") printInorder(node.right) # Driver codepre = [10, 5, 1, 7, 40, 50] # Function callroot = constructTree(pre) print ("Inorder traversal of the constructed tree: ")printInorder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // C# program to construct BST from given preorder traversalusing System; // A binary tree nodepublic class Node { public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class Index { public int index = 0;} public class BinaryTree { public Index index = new Index(); // A recursive function to construct BST from pre[]. // preIndex is used to keep track of index in pre[]. public virtual Node constructTreeUtil(int[] pre, Index preIndex, int key, int min, int max, int size) { // Base case if (preIndex.index >= size) { return null; } Node root = null; // If current element of pre[] is in range, then // only it is part of current subtree if (key > min && key < max) { // Allocate memory for root of this subtree // and increment *preIndex root = new Node(key); preIndex.index = preIndex.index + 1; if (preIndex.index < size) { // Construct the subtree under root // All nodes which are in range // {min .. key} will go in left // subtree, and first such node will // be root of left subtree. root.left = constructTreeUtil( pre, preIndex, pre[preIndex.index], min, key, size); } if (preIndex.index < size) { // All nodes which are in range // {key..max} will go in right // subtree, and first such node // will be root of right subtree. root.right = constructTreeUtil( pre, preIndex, pre[preIndex.index], key, max, size); } } return root; } // The main function to construct BST from given // preorder traversal. This function mainly uses // constructTreeUtil() public virtual Node constructTree(int[] pre, int size) { return constructTreeUtil(pre, index, pre[0], int.MinValue, int.MaxValue, size); } // A utility function to print inorder traversal of a // Binary Tree public virtual void printInorder(Node node) { if (node == null) { return; } printInorder(node.left); Console.Write(node.data + " "); printInorder(node.right); } // Driver code public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); int[] pre = new int[] { 10, 5, 1, 7, 40, 50 }; int size = pre.Length; // Function call Node root = tree.constructTree(pre, size); Console.WriteLine( "Inorder traversal of the constructed tree is "); tree.printInorder(root); }} // This code is contributed by Shrikant13 <script>// javascript program to construct BST from given preorder// traversal // A binary tree nodeclass Node { constructor(d) { this.data = d; this.left = this.right = null; }} class Index { constructor(){ this.index = 0; }} index = new Index(); // A recursive function to construct BST from pre. // preIndex is used to keep track of index in pre. function constructTreeUtil(pre, preIndex , key , min , max , size) { // Base case if (preIndex.index >= size) { return null; } var root = null; // If current element of pre is in range, then // only it is part of current subtree if (key > min && key < max) { // Allocate memory for root of this // subtree and increment *preIndex root = new Node(key); preIndex.index = preIndex.index + 1; if (preIndex.index < size) { // Construct the subtree under root // All nodes which are in range {min .. key} // will go in left subtree, and first such // node will be root of left subtree. root.left = constructTreeUtil(pre, preIndex, pre[preIndex.index], min, key, size); } if (preIndex.index < size) { // All nodes which are in range {key..max} // will go in right subtree, and first such // node will be root of right subtree. root.right = constructTreeUtil(pre, preIndex, pre[preIndex.index], key, max, size); } } return root; } // The main function to construct BST from given // preorder traversal. This function mainly uses // constructTreeUtil() function constructTree(pre , size) { var preIndex = 0; return constructTreeUtil(pre, index, pre[0], Number.MIN_VALUE, Number.MAX_VALUE, size); } // A utility function to print inorder traversal of a // Binary Tree function printInorder(node) { if (node == null) { return; } printInorder(node.left); document.write(node.data + " "); printInorder(node.right); } // Driver code var pre =[ 10, 5, 1, 7, 40, 50 ]; var size = pre.length; // Function call var root = constructTree(pre, size); document.write("Inorder traversal of the constructed tree is <br/>"); printInorder(root); // This code is contributed by Rajput-Ji</script> Inorder traversal of the constructed tree: 1 5 7 10 40 50 Time Complexity: O(n) We will soon publish a O(n) iterative solution as a separate post.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Method 3 ( O(n2) time complexity ): Simply do that just by using the recursion concept and iterating through the array of the given elements like below. Java C# Javascript /*Construct a BST from given pre-order traversalfor example if the given traversal is {10, 5, 1, 7, 40, 50},then the output should be the root of the following tree. 10 / \ 5 40 / \ \1 7 50 */ class Node { int data; Node left, right; Node(int data) { this.data = data; this.left = this.right = null; }} class CreateBSTFromPreorder { private static Node node; // This will create the BST public static Node createNode(Node node, int data) { if (node == null) node = new Node(data); if (node.data > data) node.left = createNode(node.left, data); if (node.data < data) node.right = createNode(node.right, data); return node; } // A wrapper function of createNode public static void create(int data) { node = createNode(node, data); } // A function to print BST in inorder public static void inorderRec(Node root) { if (root != null) { inorderRec(root.left); System.out.println(root.data); inorderRec(root.right); } } // Driver Code public static void main(String[] args) { int[] nodeData = { 10, 5, 1, 7, 40, 50 }; for (int i = 0; i < nodeData.length; i++) { create(nodeData[i]); } inorderRec(node); }} /*Construct a BST from given pre-order traversalfor example if the given traversal is {10, 5, 1, 7, 40, 50},then the output should be the root of the following tree. 10 / \ 5 40 / \ \1 7 50 */using System;public class Node { public int data; public Node left, right; public Node(int data) { this.data = data; this.left = this.right = null; }} public class CreateBSTFromPreorder { private static Node node; // This will create the BST public static Node createNode(Node node, int data) { if (node == null) node = new Node(data); if (node.data > data) node.left = createNode(node.left, data); if (node.data < data) node.right = createNode(node.right, data); return node; } // A wrapper function of createNode public static void create(int data) { node = createNode(node, data); } // A function to print BST in inorder public static void inorderRec(Node root) { if (root != null) { inorderRec(root.left); Console.WriteLine(root.data); inorderRec(root.right); } } // Driver Code public static void Main(String[] args) { int[] nodeData = { 10, 5, 1, 7, 40, 50 }; for (int i = 0; i < nodeData.Length; i++) { create(nodeData[i]); } inorderRec(node); }} // This code is contributed by Rajput-Ji <script>/*Construct a BST from given pre-order traversalfor example if the given traversal is {10, 5, 1, 7, 40, 50],then the output should be the root of the following tree. 10 / \ 5 40 / \ \1 7 50 */ class Node { constructor(data) { this.data = data; this.left = this.right = null; }} var node; // This will create the BST function createNode(node , data) { if (node == null) node = new Node(data); if (node.data > data) node.left = createNode(node.left, data); if (node.data < data) node.right = createNode(node.right, data); return node; } // A wrapper function of createNode function create(data) { node = createNode(node, data); } // A function to print BST in inorder function inorderRec(root) { if (root != null) { inorderRec(root.left); document.write(root.data+"<br/>"); inorderRec(root.right); } } // Driver Code var nodeData = [ 10, 5, 1, 7, 40, 50 ]; for (i = 0; i < nodeData.length; i++) { create(nodeData[i]); } inorderRec(node); // This code is contributed by Rajput-Ji</script> 1 5 7 10 40 50 shrikanth13 rathbhupendra Akanksha_Rai SatvikNema roysubham505 Rajput-Ji duke0122 rhyscompton zeekgeek harmonpreet012 as5853535 asthasinha2305 gunjanmodi amartyaghoshgfg sweetyty GauravRajput1 sagartomar9927 Binary Search Tree Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. AVL Tree | Set 1 (Insertion) A program to check if a binary tree is BST or not Red-Black Tree | Set 2 (Insert) Optimal Binary Search Tree | DP-24 Inorder Successor in Binary Search Tree Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Difference between Binary Tree and Binary Search Tree Lowest Common Ancestor in a Binary Search Tree. Find k-th smallest element in BST (Order Statistics in BST) Inorder predecessor and successor for a given key in BST
[ { "code": null, "e": 39003, "s": 38975, "text": "\n09 Mar, 2022" }, { "code": null, "e": 39072, "s": 39003, "text": "Given preorder traversal of a binary search tree, construct the BST." }, { "code": null, "e": 39192, "s": 39072, "text": "For example, if the given traversal is {10, 5, 1, 7, 40, 50}, then the output should be the root of the following tree." }, { "code": null, "e": 39248, "s": 39192, "text": " 10\n / \\\n 5 40\n / \\ \\\n1 7 50" }, { "code": null, "e": 39688, "s": 39248, "text": "Method 1 ( O(n2) time complexity ) The first element of preorder traversal is always root. We first construct the root. Then we find the index of the first element which is greater than the root. Let the index be ‘i’. The values between root and ‘i’ will be part of the left subtree, and the values between ‘i'(inclusive) and ‘n-1’ will be part of the right subtree. Divide given pre[] at index “i” and recur for left and right sub-trees. " }, { "code": null, "e": 39884, "s": 39688, "text": "For example in {10, 5, 1, 7, 40, 50}, 10 is the first element, so we make it root. Now we look for the first element greater than 10, we find 40. So we know the structure of BST is as following. " }, { "code": null, "e": 39964, "s": 39884, "text": " 10\n / \\\n / \\\n {5, 1, 7} {40, 50}" }, { "code": null, "e": 40064, "s": 39964, "text": "We recursively follow above steps for subarrays {5, 1, 7} and {40, 50}, and get the complete tree. " }, { "code": null, "e": 40068, "s": 40064, "text": "C++" }, { "code": null, "e": 40070, "s": 40068, "text": "C" }, { "code": null, "e": 40075, "s": 40070, "text": "Java" }, { "code": null, "e": 40083, "s": 40075, "text": "Python3" }, { "code": null, "e": 40086, "s": 40083, "text": "C#" }, { "code": "/* A O(n^2) program for construction of BST from preorder * traversal */#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */class node {public: int data; node* left; node* right;}; // A utility function to create a nodenode* newNode(int data){ node* temp = new node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // A recursive function to construct Full from pre[].// preIndex is used to keep track of index in pre[].node* constructTreeUtil(int pre[], int* preIndex, int low, int high, int size){ // Base case if (*preIndex >= size || low > high) return NULL; // The first node in preorder traversal is root. So take // the node at preIndex from pre[] and make it root, and // increment preIndex node* root = newNode(pre[*preIndex]); *preIndex = *preIndex + 1; // If the current subarray has only one element, no need // to recur if (low == high) return root; // Search for the first element greater than root int i; for (i = low; i <= high; ++i) if (pre[i] > root->data) break; // Use the index of element found in preorder to divide // preorder array in two parts. Left subtree and right // subtree root->left = constructTreeUtil(pre, preIndex, *preIndex, i - 1, size); root->right = constructTreeUtil(pre, preIndex, i, high, size); return root;} // The main function to construct BST from given preorder// traversal. This function mainly uses constructTreeUtil()node* constructTree(int pre[], int size){ int preIndex = 0; return constructTreeUtil(pre, &preIndex, 0, size - 1, size);} // A utility function to print inorder traversal of a Binary// Treevoid printInorder(node* node){ if (node == NULL) return; printInorder(node->left); cout << node->data << \" \"; printInorder(node->right);} // Driver codeint main(){ int pre[] = { 10, 5, 1, 7, 40, 50 }; int size = sizeof(pre) / sizeof(pre[0]); node* root = constructTree(pre, size); cout << \"Inorder traversal of the constructed tree: \\n\"; printInorder(root); return 0;} // This code is contributed by rathbhupendra", "e": 42409, "s": 40086, "text": null }, { "code": "/* A O(n^2) program for construction of BST from preorder * traversal */#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node { int data; struct node* left; struct node* right;}; // A utility function to create a nodestruct node* newNode(int data){ struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->data = data; temp->left = temp->right = NULL; return temp;} // A recursive function to construct Full from pre[].// preIndex is used to keep track of index in pre[].struct node* constructTreeUtil(int pre[], int* preIndex, int low, int high, int size){ // Base case if (*preIndex >= size || low > high) return NULL; // The first node in preorder traversal is root. So take // the node at preIndex from pre[] and make it root, and // increment preIndex struct node* root = newNode(pre[*preIndex]); *preIndex = *preIndex + 1; // If the current subarray has only one element, no need // to recur if (low == high) return root; // Search for the first element greater than root int i; for (i = low; i <= high; ++i) if (pre[i] > root->data) break; // Use the index of element found in preorder to divide // preorder array in two parts. Left subtree and right // subtree root->left = constructTreeUtil(pre, preIndex, *preIndex, i - 1, size); root->right = constructTreeUtil(pre, preIndex, i, high, size); return root;} // The main function to construct BST from given preorder// traversal. This function mainly uses constructTreeUtil()struct node* constructTree(int pre[], int size){ int preIndex = 0; return constructTreeUtil(pre, &preIndex, 0, size - 1, size);} // A utility function to print inorder traversal of a Binary// Treevoid printInorder(struct node* node){ if (node == NULL) return; printInorder(node->left); printf(\"%d \", node->data); printInorder(node->right);} // Driver codeint main(){ int pre[] = { 10, 5, 1, 7, 40, 50 }; int size = sizeof(pre) / sizeof(pre[0]); struct node* root = constructTree(pre, size); printf(\"Inorder traversal of the constructed tree: \\n\"); printInorder(root); return 0;}", "e": 44785, "s": 42409, "text": null }, { "code": "// Java program to construct BST from given preorder// traversal // A binary tree nodeclass Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} class Index { int index = 0;} class BinaryTree { Index index = new Index(); // A recursive function to construct Full from pre[]. // preIndex is used to keep track of index in pre[]. Node constructTreeUtil(int pre[], Index preIndex, int low, int high, int size) { // Base case if (preIndex.index >= size || low > high) { return null; } // The first node in preorder traversal is root. So // take the node at preIndex from pre[] and make it // root, and increment preIndex Node root = new Node(pre[preIndex.index]); preIndex.index = preIndex.index + 1; // If the current subarray has only one element, no // need to recur if (low == high) { return root; } // Search for the first element greater than root int i; for (i = low; i <= high; ++i) { if (pre[i] > root.data) { break; } } // Use the index of element found in preorder to // divide preorder array in two parts. Left subtree // and right subtree root.left = constructTreeUtil( pre, preIndex, preIndex.index, i - 1, size); root.right = constructTreeUtil(pre, preIndex, i, high, size); return root; } // The main function to construct BST from given // preorder traversal. This function mainly uses // constructTreeUtil() Node constructTree(int pre[], int size) { return constructTreeUtil(pre, index, 0, size - 1, size); } // A utility function to print inorder traversal of a // Binary Tree void printInorder(Node node) { if (node == null) { return; } printInorder(node.left); System.out.print(node.data + \" \"); printInorder(node.right); } // Driver code public static void main(String[] args) { BinaryTree tree = new BinaryTree(); int pre[] = new int[] { 10, 5, 1, 7, 40, 50 }; int size = pre.length; Node root = tree.constructTree(pre, size); System.out.println( \"Inorder traversal of the constructed tree is \"); tree.printInorder(root); }} // This code has been contributed by Mayank Jaiswal", "e": 47346, "s": 44785, "text": null }, { "code": "# A O(n^2) Python3 program for# construction of BST from preorder traversal # A binary tree node class Node(): # A constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # constructTreeUtil.preIndex is a static variable of# function constructTreeUtil # Function to get the value of static variable# constructTreeUtil.preIndexdef getPreIndex(): return constructTreeUtil.preIndex # Function to increment the value of static variable# constructTreeUtil.preIndex def incrementPreIndex(): constructTreeUtil.preIndex += 1 # A recurseive function to construct Full from pre[].# preIndex is used to keep track of index in pre[[]. def constructTreeUtil(pre, low, high): # Base Case if(low > high): return None # The first node in preorder traversal is root. So take # the node at preIndex from pre[] and make it root, # and increment preIndex root = Node(pre[getPreIndex()]) incrementPreIndex() # If the current subarray has onlye one element, # no need to recur if low == high: return root r_root = -1 # Search for the first element greater than root for i in range(low, high+1): if (pre[i] > root.data): r_root = i break # If no elements are greater than the current root, # all elements are left children # so assign root appropriately if r_root == -1: r_root = getPreIndex() + (high - low) # Use the index of element found in preorder to divide # preorder array in two parts. Left subtree and right # subtree root.left = constructTreeUtil(pre, getPreIndex(), r_root-1) root.right = constructTreeUtil(pre, r_root, high) return root # The main function to construct BST from given preorder# traversal. This function mailny uses constructTreeUtil() def constructTree(pre): size = len(pre) constructTreeUtil.preIndex = 0 return constructTreeUtil(pre, 0, size-1) def printInorder(root): if root is None: return printInorder(root.left) print (root.data,end=' ') printInorder(root.right) # Driver codepre = [10, 5, 1, 7, 40, 50] root = constructTree(pre)print (\"Inorder traversal of the constructed tree:\")printInorder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) and Rhys Compton", "e": 49696, "s": 47346, "text": null }, { "code": "using System; // C# program to construct BST from given preorder traversal// A binary tree nodepublic class Node { public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class Index { public int index = 0;} public class BinaryTree { public Index index = new Index(); // A recursive function to construct Full from pre[]. // preIndex is used to keep track of index in pre[]. public virtual Node constructTreeUtil(int[] pre, Index preIndex, int low, int high, int size) { // Base case if (preIndex.index >= size || low > high) { return null; } // The first node in preorder traversal is root. So // take the node at preIndex from pre[] and make it // root, and increment preIndex Node root = new Node(pre[preIndex.index]); preIndex.index = preIndex.index + 1; // If the current subarray has only one element, no // need to recur if (low == high) { return root; } // Search for the first element greater than root int i; for (i = low; i <= high; ++i) { if (pre[i] > root.data) { break; } } // Use the index of element found in preorder to // divide preorder array in two parts. Left subtree // and right subtree root.left = constructTreeUtil( pre, preIndex, preIndex.index, i - 1, size); root.right = constructTreeUtil(pre, preIndex, i, high, size); return root; } // The main function to construct BST from given // preorder traversal. This function mainly uses // constructTreeUtil() public virtual Node constructTree(int[] pre, int size) { return constructTreeUtil(pre, index, 0, size - 1, size); } // A utility function to print inorder traversal of a // Binary Tree public virtual void printInorder(Node node) { if (node == null) { return; } printInorder(node.left); Console.Write(node.data + \" \"); printInorder(node.right); } // Driver code public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); int[] pre = new int[] { 10, 5, 1, 7, 40, 50 }; int size = pre.Length; Node root = tree.constructTree(pre, size); Console.WriteLine( \"Inorder traversal of the constructed tree is \"); tree.printInorder(root); }} // This code is contributed by Shrikant13", "e": 52450, "s": 49696, "text": null }, { "code": null, "e": 52510, "s": 52450, "text": "Inorder traversal of the constructed tree: \n1 5 7 10 40 50 " }, { "code": null, "e": 52533, "s": 52510, "text": "Time Complexity: O(n2)" }, { "code": null, "e": 53040, "s": 52533, "text": "Method 2 ( O(n) time complexity ) The idea used here is inspired by method 3 of this post. The trick is to set a range {min .. max} for every node. Initialize the range as {INT_MIN .. INT_MAX}. The first node will definitely be in range, so create a root node. To construct the left subtree, set the range as {INT_MIN ...root->data}. If a value is in the range {INT_MIN .. root->data}, the values are part of the left subtree. To construct the right subtree, set the range as {root->data..max .. INT_MAX}. " }, { "code": null, "e": 53087, "s": 53040, "text": "Below is the implementation of the above idea:" }, { "code": null, "e": 53091, "s": 53087, "text": "C++" }, { "code": null, "e": 53093, "s": 53091, "text": "C" }, { "code": null, "e": 53098, "s": 53093, "text": "Java" }, { "code": null, "e": 53106, "s": 53098, "text": "Python3" }, { "code": null, "e": 53109, "s": 53106, "text": "C#" }, { "code": null, "e": 53120, "s": 53109, "text": "Javascript" }, { "code": "/* A O(n) program for constructionof BST from preorder traversal */#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */class node {public: int data; node* left; node* right;}; // A utility function to create a nodenode* newNode(int data){ node* temp = new node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // A recursive function to construct// BST from pre[]. preIndex is used// to keep track of index in pre[].node* constructTreeUtil(int pre[], int* preIndex, int key, int min, int max, int size){ // Base case if (*preIndex >= size) return NULL; node* root = NULL; // If current element of pre[] is in range, then // only it is part of current subtree if (key > min && key < max) { // Allocate memory for root of this // subtree and increment *preIndex root = newNode(key); *preIndex = *preIndex + 1; if (*preIndex < size) { // Construct the subtree under root // All nodes which are in range // {min .. key} will go in left // subtree, and first such node // will be root of left subtree. root->left = constructTreeUtil(pre, preIndex, pre[*preIndex], min, key, size); } if (*preIndex < size) { // All nodes which are in range // {key..max} will go in right // subtree, and first such node // will be root of right subtree. root->right = constructTreeUtil(pre, preIndex, pre[*preIndex], key, max, size); } } return root;} // The main function to construct BST// from given preorder traversal.// This function mainly uses constructTreeUtil()node* constructTree(int pre[], int size){ int preIndex = 0; return constructTreeUtil(pre, &preIndex, pre[0], INT_MIN, INT_MAX, size);} // A utility function to print inorder// traversal of a Binary Treevoid printInorder(node* node){ if (node == NULL) return; printInorder(node->left); cout << node->data << \" \"; printInorder(node->right);} // Driver codeint main(){ int pre[] = { 10, 5, 1, 7, 40, 50 }; int size = sizeof(pre) / sizeof(pre[0]); // Function call node* root = constructTree(pre, size); cout << \"Inorder traversal of the constructed tree: \\n\"; printInorder(root); return 0;} // This is code is contributed by rathbhupendra", "e": 55805, "s": 53120, "text": null }, { "code": "/* A O(n) program for construction of BST from preorder * traversal */#include <limits.h>#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node { int data; struct node* left; struct node* right;}; // A utility function to create a nodestruct node* newNode(int data){ struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->data = data; temp->left = temp->right = NULL; return temp;} // A recursive function to construct BST from pre[].// preIndex is used to keep track of index in pre[].struct node* constructTreeUtil(int pre[], int* preIndex, int key, int min, int max, int size){ // Base case if (*preIndex >= size) return NULL; struct node* root = NULL; // If current element of pre[] is in range, then // only it is part of current subtree if (key > min && key < max) { // Allocate memory for root of this subtree and // increment *preIndex root = newNode(key); *preIndex = *preIndex + 1; if (*preIndex < size) { // Construct the subtree under root // All nodes which are in range {min .. key} // will go in left subtree, and first such node // will be root of left subtree. root->left = constructTreeUtil(pre, preIndex, pre[*preIndex], min, key, size); } if (*preIndex < size) { // All nodes which are in range {key..max} will // go in right subtree, and first such node will // be root of right subtree. root->right = constructTreeUtil(pre, preIndex, pre[*preIndex], key, max, size); } } return root;} // The main function to construct BST from given preorder// traversal. This function mainly uses constructTreeUtil()struct node* constructTree(int pre[], int size){ int preIndex = 0; return constructTreeUtil(pre, &preIndex, pre[0], INT_MIN, INT_MAX, size);} // A utility function to print inorder traversal of a Binary// Treevoid printInorder(struct node* node){ if (node == NULL) return; printInorder(node->left); printf(\"%d \", node->data); printInorder(node->right);} // Driver codeint main(){ int pre[] = { 10, 5, 1, 7, 40, 50 }; int size = sizeof(pre) / sizeof(pre[0]); // function call struct node* root = constructTree(pre, size); printf(\"Inorder traversal of the constructed tree: \\n\"); printInorder(root); return 0;}", "e": 58560, "s": 55805, "text": null }, { "code": "// Java program to construct BST from given preorder// traversal // A binary tree nodeclass Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} class Index { int index = 0;} class BinaryTree { Index index = new Index(); // A recursive function to construct BST from pre[]. // preIndex is used to keep track of index in pre[]. Node constructTreeUtil(int pre[], Index preIndex, int key, int min, int max, int size) { // Base case if (preIndex.index >= size) { return null; } Node root = null; // If current element of pre[] is in range, then // only it is part of current subtree if (key > min && key < max) { // Allocate memory for root of this // subtree and increment *preIndex root = new Node(key); preIndex.index = preIndex.index + 1; if (preIndex.index < size) { // Construct the subtree under root // All nodes which are in range {min .. key} // will go in left subtree, and first such // node will be root of left subtree. root.left = constructTreeUtil( pre, preIndex, pre[preIndex.index], min, key, size); } if (preIndex.index < size) { // All nodes which are in range {key..max} // will go in right subtree, and first such // node will be root of right subtree. root.right = constructTreeUtil( pre, preIndex, pre[preIndex.index], key, max, size); } } return root; } // The main function to construct BST from given // preorder traversal. This function mainly uses // constructTreeUtil() Node constructTree(int pre[], int size) { int preIndex = 0; return constructTreeUtil(pre, index, pre[0], Integer.MIN_VALUE, Integer.MAX_VALUE, size); } // A utility function to print inorder traversal of a // Binary Tree void printInorder(Node node) { if (node == null) { return; } printInorder(node.left); System.out.print(node.data + \" \"); printInorder(node.right); } // Driver code public static void main(String[] args) { BinaryTree tree = new BinaryTree(); int pre[] = new int[] { 10, 5, 1, 7, 40, 50 }; int size = pre.length; // Function call Node root = tree.constructTree(pre, size); System.out.println( \"Inorder traversal of the constructed tree is \"); tree.printInorder(root); }} // This code has been contributed by Mayank Jaiswal", "e": 61448, "s": 58560, "text": null }, { "code": "# A O(n) program for construction of BST from preorder traversal INT_MIN = -float(\"inf\")INT_MAX = float(\"inf\") # A Binary tree node class Node: # Constructor to created a new node def __init__(self, data): self.data = data self.left = None self.right = None # Methods to get and set the value of static variable# constructTreeUtil.preIndex for function construcTreeUtil() def getPreIndex(): return constructTreeUtil.preIndex def incrementPreIndex(): constructTreeUtil.preIndex += 1 # A recursive function to construct BST from pre[].# preIndex is used to keep track of index in pre[] def constructTreeUtil(pre, key, mini, maxi, size): # Base Case if(getPreIndex() >= size): return None root = None # If current element of pre[] is in range, then # only it is part of current subtree if(key > mini and key < maxi): # Allocate memory for root of this subtree # and increment constructTreeUtil.preIndex root = Node(key) incrementPreIndex() if(getPreIndex() < size): # Construct the subtree under root # All nodes which are in range {min.. key} will # go in left subtree, and first such node will # be root of left subtree root.left = constructTreeUtil(pre, pre[getPreIndex()], mini, key, size) if(getPreIndex() < size): # All nodes which are in range{key..max} will # go to right subtree, and first such node will # be root of right subtree root.right = constructTreeUtil(pre, pre[getPreIndex()], key, maxi, size) return root # This is the main function to construct BST from given# preorder traversal. This function mainly uses# constructTreeUtil() def constructTree(pre): constructTreeUtil.preIndex = 0 size = len(pre) return constructTreeUtil(pre, pre[0], INT_MIN, INT_MAX, size) # A utility function to print inorder traversal of Binary Treedef printInorder(node): if node is None: return printInorder(node.left) print (node.data,end=\" \") printInorder(node.right) # Driver codepre = [10, 5, 1, 7, 40, 50] # Function callroot = constructTree(pre) print (\"Inorder traversal of the constructed tree: \")printInorder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 63943, "s": 61448, "text": null }, { "code": "// C# program to construct BST from given preorder traversalusing System; // A binary tree nodepublic class Node { public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class Index { public int index = 0;} public class BinaryTree { public Index index = new Index(); // A recursive function to construct BST from pre[]. // preIndex is used to keep track of index in pre[]. public virtual Node constructTreeUtil(int[] pre, Index preIndex, int key, int min, int max, int size) { // Base case if (preIndex.index >= size) { return null; } Node root = null; // If current element of pre[] is in range, then // only it is part of current subtree if (key > min && key < max) { // Allocate memory for root of this subtree // and increment *preIndex root = new Node(key); preIndex.index = preIndex.index + 1; if (preIndex.index < size) { // Construct the subtree under root // All nodes which are in range // {min .. key} will go in left // subtree, and first such node will // be root of left subtree. root.left = constructTreeUtil( pre, preIndex, pre[preIndex.index], min, key, size); } if (preIndex.index < size) { // All nodes which are in range // {key..max} will go in right // subtree, and first such node // will be root of right subtree. root.right = constructTreeUtil( pre, preIndex, pre[preIndex.index], key, max, size); } } return root; } // The main function to construct BST from given // preorder traversal. This function mainly uses // constructTreeUtil() public virtual Node constructTree(int[] pre, int size) { return constructTreeUtil(pre, index, pre[0], int.MinValue, int.MaxValue, size); } // A utility function to print inorder traversal of a // Binary Tree public virtual void printInorder(Node node) { if (node == null) { return; } printInorder(node.left); Console.Write(node.data + \" \"); printInorder(node.right); } // Driver code public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); int[] pre = new int[] { 10, 5, 1, 7, 40, 50 }; int size = pre.Length; // Function call Node root = tree.constructTree(pre, size); Console.WriteLine( \"Inorder traversal of the constructed tree is \"); tree.printInorder(root); }} // This code is contributed by Shrikant13", "e": 66999, "s": 63943, "text": null }, { "code": "<script>// javascript program to construct BST from given preorder// traversal // A binary tree nodeclass Node { constructor(d) { this.data = d; this.left = this.right = null; }} class Index { constructor(){ this.index = 0; }} index = new Index(); // A recursive function to construct BST from pre. // preIndex is used to keep track of index in pre. function constructTreeUtil(pre, preIndex , key , min , max , size) { // Base case if (preIndex.index >= size) { return null; } var root = null; // If current element of pre is in range, then // only it is part of current subtree if (key > min && key < max) { // Allocate memory for root of this // subtree and increment *preIndex root = new Node(key); preIndex.index = preIndex.index + 1; if (preIndex.index < size) { // Construct the subtree under root // All nodes which are in range {min .. key} // will go in left subtree, and first such // node will be root of left subtree. root.left = constructTreeUtil(pre, preIndex, pre[preIndex.index], min, key, size); } if (preIndex.index < size) { // All nodes which are in range {key..max} // will go in right subtree, and first such // node will be root of right subtree. root.right = constructTreeUtil(pre, preIndex, pre[preIndex.index], key, max, size); } } return root; } // The main function to construct BST from given // preorder traversal. This function mainly uses // constructTreeUtil() function constructTree(pre , size) { var preIndex = 0; return constructTreeUtil(pre, index, pre[0], Number.MIN_VALUE, Number.MAX_VALUE, size); } // A utility function to print inorder traversal of a // Binary Tree function printInorder(node) { if (node == null) { return; } printInorder(node.left); document.write(node.data + \" \"); printInorder(node.right); } // Driver code var pre =[ 10, 5, 1, 7, 40, 50 ]; var size = pre.length; // Function call var root = constructTree(pre, size); document.write(\"Inorder traversal of the constructed tree is <br/>\"); printInorder(root); // This code is contributed by Rajput-Ji</script>", "e": 69556, "s": 66999, "text": null }, { "code": null, "e": 69616, "s": 69556, "text": "Inorder traversal of the constructed tree: \n1 5 7 10 40 50 " }, { "code": null, "e": 69638, "s": 69616, "text": "Time Complexity: O(n)" }, { "code": null, "e": 69829, "s": 69638, "text": "We will soon publish a O(n) iterative solution as a separate post.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 69867, "s": 69829, "text": "Method 3 ( O(n2) time complexity ): " }, { "code": null, "e": 69984, "s": 69867, "text": "Simply do that just by using the recursion concept and iterating through the array of the given elements like below." }, { "code": null, "e": 69989, "s": 69984, "text": "Java" }, { "code": null, "e": 69992, "s": 69989, "text": "C#" }, { "code": null, "e": 70003, "s": 69992, "text": "Javascript" }, { "code": "/*Construct a BST from given pre-order traversalfor example if the given traversal is {10, 5, 1, 7, 40, 50},then the output should be the root of the following tree. 10 / \\ 5 40 / \\ \\1 7 50 */ class Node { int data; Node left, right; Node(int data) { this.data = data; this.left = this.right = null; }} class CreateBSTFromPreorder { private static Node node; // This will create the BST public static Node createNode(Node node, int data) { if (node == null) node = new Node(data); if (node.data > data) node.left = createNode(node.left, data); if (node.data < data) node.right = createNode(node.right, data); return node; } // A wrapper function of createNode public static void create(int data) { node = createNode(node, data); } // A function to print BST in inorder public static void inorderRec(Node root) { if (root != null) { inorderRec(root.left); System.out.println(root.data); inorderRec(root.right); } } // Driver Code public static void main(String[] args) { int[] nodeData = { 10, 5, 1, 7, 40, 50 }; for (int i = 0; i < nodeData.length; i++) { create(nodeData[i]); } inorderRec(node); }}", "e": 71370, "s": 70003, "text": null }, { "code": "/*Construct a BST from given pre-order traversalfor example if the given traversal is {10, 5, 1, 7, 40, 50},then the output should be the root of the following tree. 10 / \\ 5 40 / \\ \\1 7 50 */using System;public class Node { public int data; public Node left, right; public Node(int data) { this.data = data; this.left = this.right = null; }} public class CreateBSTFromPreorder { private static Node node; // This will create the BST public static Node createNode(Node node, int data) { if (node == null) node = new Node(data); if (node.data > data) node.left = createNode(node.left, data); if (node.data < data) node.right = createNode(node.right, data); return node; } // A wrapper function of createNode public static void create(int data) { node = createNode(node, data); } // A function to print BST in inorder public static void inorderRec(Node root) { if (root != null) { inorderRec(root.left); Console.WriteLine(root.data); inorderRec(root.right); } } // Driver Code public static void Main(String[] args) { int[] nodeData = { 10, 5, 1, 7, 40, 50 }; for (int i = 0; i < nodeData.Length; i++) { create(nodeData[i]); } inorderRec(node); }} // This code is contributed by Rajput-Ji", "e": 72824, "s": 71370, "text": null }, { "code": "<script>/*Construct a BST from given pre-order traversalfor example if the given traversal is {10, 5, 1, 7, 40, 50],then the output should be the root of the following tree. 10 / \\ 5 40 / \\ \\1 7 50 */ class Node { constructor(data) { this.data = data; this.left = this.right = null; }} var node; // This will create the BST function createNode(node , data) { if (node == null) node = new Node(data); if (node.data > data) node.left = createNode(node.left, data); if (node.data < data) node.right = createNode(node.right, data); return node; } // A wrapper function of createNode function create(data) { node = createNode(node, data); } // A function to print BST in inorder function inorderRec(root) { if (root != null) { inorderRec(root.left); document.write(root.data+\"<br/>\"); inorderRec(root.right); } } // Driver Code var nodeData = [ 10, 5, 1, 7, 40, 50 ]; for (i = 0; i < nodeData.length; i++) { create(nodeData[i]); } inorderRec(node); // This code is contributed by Rajput-Ji</script>", "e": 74063, "s": 72824, "text": null }, { "code": null, "e": 74078, "s": 74063, "text": "1\n5\n7\n10\n40\n50" }, { "code": null, "e": 74090, "s": 74078, "text": "shrikanth13" }, { "code": null, "e": 74104, "s": 74090, "text": "rathbhupendra" }, { "code": null, "e": 74117, "s": 74104, "text": "Akanksha_Rai" }, { "code": null, "e": 74128, "s": 74117, "text": "SatvikNema" }, { "code": null, "e": 74141, "s": 74128, "text": "roysubham505" }, { "code": null, "e": 74151, "s": 74141, "text": "Rajput-Ji" }, { "code": null, "e": 74160, "s": 74151, "text": "duke0122" }, { "code": null, "e": 74172, "s": 74160, "text": "rhyscompton" }, { "code": null, "e": 74181, "s": 74172, "text": "zeekgeek" }, { "code": null, "e": 74196, "s": 74181, "text": "harmonpreet012" }, { "code": null, "e": 74206, "s": 74196, "text": "as5853535" }, { "code": null, "e": 74221, "s": 74206, "text": "asthasinha2305" }, { "code": null, "e": 74232, "s": 74221, "text": "gunjanmodi" }, { "code": null, "e": 74248, "s": 74232, "text": "amartyaghoshgfg" }, { "code": null, "e": 74257, "s": 74248, "text": "sweetyty" }, { "code": null, "e": 74271, "s": 74257, "text": "GauravRajput1" }, { "code": null, "e": 74286, "s": 74271, "text": "sagartomar9927" }, { "code": null, "e": 74305, "s": 74286, "text": "Binary Search Tree" }, { "code": null, "e": 74324, "s": 74305, "text": "Binary Search Tree" }, { "code": null, "e": 74422, "s": 74324, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 74451, "s": 74422, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 74501, "s": 74451, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 74533, "s": 74501, "text": "Red-Black Tree | Set 2 (Insert)" }, { "code": null, "e": 74568, "s": 74533, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 74608, "s": 74568, "text": "Inorder Successor in Binary Search Tree" }, { "code": null, "e": 74678, "s": 74608, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 74732, "s": 74678, "text": "Difference between Binary Tree and Binary Search Tree" }, { "code": null, "e": 74780, "s": 74732, "text": "Lowest Common Ancestor in a Binary Search Tree." }, { "code": null, "e": 74840, "s": 74780, "text": "Find k-th smallest element in BST (Order Statistics in BST)" } ]
SVG polygon Element - GeeksforGeeks
31 Mar, 2022 SVG stands for Scalable Vector Graphic. It can be used to make graphics and animations like in HTML canvas. The <polygon> element of SVG is used to make any type of polygon on the SVG and defines a closed shape consisting of a set of connected straight line segments. Syntax: <polygon points="Pair of points required to draw the shape" stroke="stroke color" fill="fill color for colored closed shapes"> Attributes: points: Pair of points required to draw the shape pathLength: It tells the total length of the path. Few examples are given below for a better understanding of the <polygon> SVG element. Example 1: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <svg width="400px" height="400px"> <!-- try different pairs and make different shapes--> <polygon points="0, 100 100, 100 100, 100 100, -20000" fill="green"> </svg></body></html> Output: Example 2: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><style> svg{ background-color: black; }</style><body> <svg width="200px" height="200px"> <!-- try different pairs and make different shapes--> <polygon points="100, 100 15, 205 150, 7 20, 0" fill="green" stroke="yellow"> </svg></body></html> Output: Browsers supported: Below given are the browsers supported by this svg element. Chrome Edge Opera Internet explorer Safari Firefox Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-SVG SVG-Element HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26139, "s": 26111, "text": "\n31 Mar, 2022" }, { "code": null, "e": 26407, "s": 26139, "text": "SVG stands for Scalable Vector Graphic. It can be used to make graphics and animations like in HTML canvas. The <polygon> element of SVG is used to make any type of polygon on the SVG and defines a closed shape consisting of a set of connected straight line segments." }, { "code": null, "e": 26415, "s": 26407, "text": "Syntax:" }, { "code": null, "e": 26555, "s": 26415, "text": "<polygon points=\"Pair of points required to draw the shape\"\n stroke=\"stroke color\"\n fill=\"fill color for colored closed shapes\">" }, { "code": null, "e": 26567, "s": 26555, "text": "Attributes:" }, { "code": null, "e": 26617, "s": 26567, "text": "points: Pair of points required to draw the shape" }, { "code": null, "e": 26668, "s": 26617, "text": "pathLength: It tells the total length of the path." }, { "code": null, "e": 26754, "s": 26668, "text": "Few examples are given below for a better understanding of the <polygon> SVG element." }, { "code": null, "e": 26765, "s": 26754, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Document</title></head><body> <svg width=\"400px\" height=\"400px\"> <!-- try different pairs and make different shapes--> <polygon points=\"0, 100 100, 100 100, 100 100, -20000\" fill=\"green\"> </svg></body></html>", "e": 27159, "s": 26765, "text": null }, { "code": null, "e": 27167, "s": 27159, "text": "Output:" }, { "code": null, "e": 27178, "s": 27167, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Document</title></head><style> svg{ background-color: black; }</style><body> <svg width=\"200px\" height=\"200px\"> <!-- try different pairs and make different shapes--> <polygon points=\"100, 100 15, 205 150, 7 20, 0\" fill=\"green\" stroke=\"yellow\"> </svg></body></html>", "e": 27633, "s": 27178, "text": null }, { "code": null, "e": 27641, "s": 27633, "text": "Output:" }, { "code": null, "e": 27721, "s": 27641, "text": "Browsers supported: Below given are the browsers supported by this svg element." }, { "code": null, "e": 27728, "s": 27721, "text": "Chrome" }, { "code": null, "e": 27733, "s": 27728, "text": "Edge" }, { "code": null, "e": 27739, "s": 27733, "text": "Opera" }, { "code": null, "e": 27757, "s": 27739, "text": "Internet explorer" }, { "code": null, "e": 27764, "s": 27757, "text": "Safari" }, { "code": null, "e": 27772, "s": 27764, "text": "Firefox" }, { "code": null, "e": 27909, "s": 27772, "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": 27918, "s": 27909, "text": "HTML-SVG" }, { "code": null, "e": 27930, "s": 27918, "text": "SVG-Element" }, { "code": null, "e": 27935, "s": 27930, "text": "HTML" }, { "code": null, "e": 27952, "s": 27935, "text": "Web Technologies" }, { "code": null, "e": 27957, "s": 27952, "text": "HTML" }, { "code": null, "e": 28055, "s": 27957, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28079, "s": 28055, "text": "REST API (Introduction)" }, { "code": null, "e": 28120, "s": 28079, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 28157, "s": 28120, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28186, "s": 28157, "text": "Form validation using jQuery" }, { "code": null, "e": 28206, "s": 28186, "text": "Angular File Upload" }, { "code": null, "e": 28246, "s": 28206, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28279, "s": 28246, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28324, "s": 28279, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28367, "s": 28324, "text": "How to fetch data from an API in ReactJS ?" } ]
Sub-string Divisibility by 11 Queries - GeeksforGeeks
08 Jul, 2021 Given a large number, n (having number digits up to 10^6) and various queries of the below form : Query(l, r) : find if the sub-string between the indices l and r (Both inclusive) are divisible by 11. Examples: Input: n = 122164154695 Queries: l = 0 r = 3, l = 1 r = 2, l = 5 r = 9, l = 0 r = 11 Output: True False False True Explanation: In the first query, 1221 is divisible by 11 In the second query, 22 is divisible by 11 and so on. We know that any number is divisible by 11 if the difference between the sum of odd indexed digits and the sum of even indexed digits is divisible by 11, i.e., Sum(digits at odd places) – Sum(digits at even places) should be divisible by 11.Hence, the idea is to pre-process an auxiliary array that would store the sum of digits at odd and even places. To evaluate a query we can use the auxiliary array to answer it in O(1). C++ Java Python3 C# Javascript // C++ program to check divisibility by 11 in// substrings of a number string#include <iostream>using namespace std; const int MAX = 1000005; // To store sums of even and odd digitsstruct OddEvenSums{ // Sum of even placed digits int e_sum; // Sum of odd placed digits int o_sum;}; // Auxiliary arrayOddEvenSums sum[MAX]; // Utility function to evaluate a character's// integer valueint toInt(char x){ return int(x) - 48;} // This function receives the string representation// of the number and precomputes the sum arrayvoid preCompute(string x){ // Initialize everb sum[0].e_sum = sum[0].o_sum = 0; // Add the respective digits depending on whether // they're even indexed or odd indexed for (int i=0; i<x.length(); i++) { if (i%2==0) { sum[i+1].e_sum = sum[i].e_sum+toInt(x[i]); sum[i+1].o_sum = sum[i].o_sum; } else { sum[i+1].o_sum = sum[i].o_sum+toInt(x[i]); sum[i+1].e_sum = sum[i].e_sum; } }} // This function receives l and r representing// the indices and prints the required outputbool query(int l,int r){ int diff = (sum[r+1].e_sum - sum[r+1].o_sum) - (sum[l].e_sum - sum[l].o_sum); return (diff%11==0);} //driver function to check the programint main(){ string s = "122164154695"; preCompute(s); cout << query(0, 3) << endl; cout << query(1, 2) << endl; cout << query(5, 9) << endl; cout << query(0, 11) << endl; return 0;} // Java program to check divisibility by 11 in// subStrings of a number Stringclass GFG{ static int MAX = 1000005; // To store sums of even and odd digitsstatic class OddEvenSums{ // Sum of even placed digits int e_sum; // Sum of odd placed digits int o_sum;}; // Auxiliary arraystatic OddEvenSums []sum = new OddEvenSums[MAX]; // Utility function to evaluate a character's// integer valuestatic int toInt(char x){ return x - 48;} // This function receives the String representation// of the number and precomputes the sum arraystatic void preCompute(String x){ // Initialize everb sum[0].e_sum = sum[0].o_sum = 0; // Add the respective digits depending on whether // they're even indexed or odd indexed for (int i = 0; i < x.length(); i++) { if (i % 2 == 0) { sum[i + 1].e_sum = sum[i].e_sum + toInt(x.charAt(i)); sum[i + 1].o_sum = sum[i].o_sum; } else { sum[i + 1].o_sum = sum[i].o_sum + toInt(x.charAt(i)); sum[i + 1].e_sum = sum[i].e_sum; } }} // This function receives l and r representing// the indices and prints the required outputstatic boolean query(int l, int r){ int diff = (sum[r + 1].e_sum - sum[r + 1].o_sum) - (sum[l].e_sum - sum[l].o_sum); return (diff % 11 == 0);} //driver function to check the programpublic static void main(String[] args){ for (int i = 0; i < MAX; i++) { sum[i] = new OddEvenSums(); } String s = "122164154695"; preCompute(s); System.out.println(query(0, 3) ? 1 : 0); System.out.println(query(1, 2) ? 1 : 0); System.out.println(query(5, 9) ? 1 : 0); System.out.println(query(0, 11) ? 1 : 0); }} // This code is contributed by Rajput-Ji # Python3 program to check divisibility by# 11 in subStrings of a number StringMAX = 1000005 # To store sums of even and odd digitsclass OddEvenSums: def __init__(self, e_sum, o_sum): # Sum of even placed digits self.e_sum = e_sum # Sum of odd placed digits self.o_sum = o_sum sum = [OddEvenSums(0, 0) for i in range(MAX)] # This function receives the String# representation of the number and# precomputes the sum arraydef preCompute(x): # Initialize everb sum[0].e_sum = sum[0].o_sum = 0 # Add the respective digits # depending on whether # they're even indexed or # odd indexed for i in range(len(x)): if (i % 2 == 0): sum[i + 1].e_sum = (sum[i].e_sum + int(x[i])) sum[i + 1].o_sum = sum[i].o_sum else: sum[i + 1].o_sum = (sum[i].o_sum + int(x[i])) sum[i + 1].e_sum = sum[i].e_sum # This function receives l and r representing# the indices and prints the required outputdef query(l, r): diff = ((sum[r + 1].e_sum - sum[r + 1].o_sum) - (sum[l].e_sum - sum[l].o_sum)) if (diff % 11 == 0): return True else: return False # Driver codeif __name__=="__main__": s = "122164154695" preCompute(s) print(1 if query(0, 3) else 0) print(1 if query(1, 2) else 0) print(1 if query(5, 9) else 0) print(1 if query(0, 11) else 0) # This code is contributed by rutvik_56 // C# program to check// divisibility by 11 in// subStrings of a number Stringusing System;class GFG{ static int MAX = 1000005; // To store sums of even// and odd digits public class OddEvenSums{ // Sum of even placed digits public int e_sum; // Sum of odd placed digits public int o_sum;}; // Auxiliary arraystatic OddEvenSums []sum = new OddEvenSums[MAX]; // Utility function to// evaluate a character's// integer valuestatic int toInt(char x){ return x - 48;} // This function receives the// String representation of the// number and precomputes the sum arraystatic void preCompute(String x){ // Initialize everb sum[0].e_sum = sum[0].o_sum = 0; // Add the respective digits // depending on whether they're // even indexed or odd indexed for (int i = 0; i < x.Length; i++) { if (i % 2 == 0) { sum[i + 1].e_sum = sum[i].e_sum + toInt(x[i]); sum[i + 1].o_sum = sum[i].o_sum; } else { sum[i + 1].o_sum = sum[i].o_sum + toInt(x[i]); sum[i + 1].e_sum = sum[i].e_sum; } }} // This function receives l and r// representing the indices and// prints the required outputstatic bool query(int l, int r){ int diff = (sum[r + 1].e_sum - sum[r + 1].o_sum) - (sum[l].e_sum - sum[l].o_sum); return (diff % 11 == 0);} // Driver function to check the programpublic static void Main(String[] args){ for (int i = 0; i < MAX; i++) { sum[i] = new OddEvenSums(); } String s = "122164154695"; preCompute(s); Console.WriteLine(query(0, 3) ? 1 : 0); Console.WriteLine(query(1, 2) ? 1 : 0); Console.WriteLine(query(5, 9) ? 1 : 0); Console.WriteLine(query(0, 11) ? 1 : 0);}} // This code is contributed by gauravrajput1 <script>// Javascript program to check divisibility by 11 in// subStrings of a number Stringlet MAX = 1000005; // To store sums of even and odd digitsclass OddEvenSums{ constructor() { this.e_sum = 0; this.o_sum = 0; }} // Auxiliary arraylet sum = new Array(MAX); // Utility function to evaluate a character's// integer valuefunction toInt(x){ return x.charCodeAt(0) - 48;} // This function receives the String representation// of the number and precomputes the sum arrayfunction preCompute(x){ // Initialize everb sum[0].e_sum = sum[0].o_sum = 0; // Add the respective digits depending on whether // they're even indexed or odd indexed for (let i = 0; i < x.length; i++) { if (i % 2 == 0) { sum[i + 1].e_sum = sum[i].e_sum + parseInt(x[i]); sum[i + 1].o_sum = sum[i].o_sum; } else { sum[i + 1].o_sum = sum[i].o_sum + parseInt(x[i]); sum[i + 1].e_sum = sum[i].e_sum; } }} // This function receives l and r representing// the indices and prints the required outputfunction query(l,r){ let diff = (sum[r + 1].e_sum - sum[r + 1].o_sum) - (sum[l].e_sum - sum[l].o_sum); return (diff % 11 == 0);} // driver function to check the programfor (let i = 0; i < MAX; i++) { sum[i] = new OddEvenSums();}let s = "122164154695"; preCompute(s); document.write((query(0, 3) ? 1 : 0)+"<br>");document.write((query(1, 2) ? 1 : 0)+"<br>");document.write((query(5, 9) ? 1 : 0)+"<br>");document.write((query(0, 11) ? 1 :0)+"<br>"); // This code is contributed by unknown2108</script> Output: 1 1 0 1 This article is contributed by Ashutosh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Rajput-Ji GauravRajput1 rutvik_56 unknown2108 divisibility Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Sieve of Eratosthenes Print all possible combinations of r elements in a given array of size n Program for Decimal to Binary Conversion The Knight's tour problem | Backtracking-1 Operators in C / C++ Program for factorial of a number
[ { "code": null, "e": 26587, "s": 26559, "text": "\n08 Jul, 2021" }, { "code": null, "e": 26685, "s": 26587, "text": "Given a large number, n (having number digits up to 10^6) and various queries of the below form :" }, { "code": null, "e": 26822, "s": 26685, "text": "Query(l, r) : find if the sub-string between the \n indices l and r (Both inclusive) \n are divisible by 11. " }, { "code": null, "e": 26834, "s": 26822, "text": "Examples: " }, { "code": null, "e": 27070, "s": 26834, "text": "Input: n = 122164154695\nQueries: l = 0 r = 3, l = 1 r = 2, l = 5 r = 9,\n l = 0 r = 11\nOutput:\nTrue\nFalse\nFalse\nTrue\n\nExplanation:\nIn the first query, 1221 is divisible by 11\nIn the second query, 22 is divisible by 11 and so on." }, { "code": null, "e": 27498, "s": 27070, "text": "We know that any number is divisible by 11 if the difference between the sum of odd indexed digits and the sum of even indexed digits is divisible by 11, i.e., Sum(digits at odd places) – Sum(digits at even places) should be divisible by 11.Hence, the idea is to pre-process an auxiliary array that would store the sum of digits at odd and even places. To evaluate a query we can use the auxiliary array to answer it in O(1). " }, { "code": null, "e": 27502, "s": 27498, "text": "C++" }, { "code": null, "e": 27507, "s": 27502, "text": "Java" }, { "code": null, "e": 27515, "s": 27507, "text": "Python3" }, { "code": null, "e": 27518, "s": 27515, "text": "C#" }, { "code": null, "e": 27529, "s": 27518, "text": "Javascript" }, { "code": "// C++ program to check divisibility by 11 in// substrings of a number string#include <iostream>using namespace std; const int MAX = 1000005; // To store sums of even and odd digitsstruct OddEvenSums{ // Sum of even placed digits int e_sum; // Sum of odd placed digits int o_sum;}; // Auxiliary arrayOddEvenSums sum[MAX]; // Utility function to evaluate a character's// integer valueint toInt(char x){ return int(x) - 48;} // This function receives the string representation// of the number and precomputes the sum arrayvoid preCompute(string x){ // Initialize everb sum[0].e_sum = sum[0].o_sum = 0; // Add the respective digits depending on whether // they're even indexed or odd indexed for (int i=0; i<x.length(); i++) { if (i%2==0) { sum[i+1].e_sum = sum[i].e_sum+toInt(x[i]); sum[i+1].o_sum = sum[i].o_sum; } else { sum[i+1].o_sum = sum[i].o_sum+toInt(x[i]); sum[i+1].e_sum = sum[i].e_sum; } }} // This function receives l and r representing// the indices and prints the required outputbool query(int l,int r){ int diff = (sum[r+1].e_sum - sum[r+1].o_sum) - (sum[l].e_sum - sum[l].o_sum); return (diff%11==0);} //driver function to check the programint main(){ string s = \"122164154695\"; preCompute(s); cout << query(0, 3) << endl; cout << query(1, 2) << endl; cout << query(5, 9) << endl; cout << query(0, 11) << endl; return 0;}", "e": 29034, "s": 27529, "text": null }, { "code": "// Java program to check divisibility by 11 in// subStrings of a number Stringclass GFG{ static int MAX = 1000005; // To store sums of even and odd digitsstatic class OddEvenSums{ // Sum of even placed digits int e_sum; // Sum of odd placed digits int o_sum;}; // Auxiliary arraystatic OddEvenSums []sum = new OddEvenSums[MAX]; // Utility function to evaluate a character's// integer valuestatic int toInt(char x){ return x - 48;} // This function receives the String representation// of the number and precomputes the sum arraystatic void preCompute(String x){ // Initialize everb sum[0].e_sum = sum[0].o_sum = 0; // Add the respective digits depending on whether // they're even indexed or odd indexed for (int i = 0; i < x.length(); i++) { if (i % 2 == 0) { sum[i + 1].e_sum = sum[i].e_sum + toInt(x.charAt(i)); sum[i + 1].o_sum = sum[i].o_sum; } else { sum[i + 1].o_sum = sum[i].o_sum + toInt(x.charAt(i)); sum[i + 1].e_sum = sum[i].e_sum; } }} // This function receives l and r representing// the indices and prints the required outputstatic boolean query(int l, int r){ int diff = (sum[r + 1].e_sum - sum[r + 1].o_sum) - (sum[l].e_sum - sum[l].o_sum); return (diff % 11 == 0);} //driver function to check the programpublic static void main(String[] args){ for (int i = 0; i < MAX; i++) { sum[i] = new OddEvenSums(); } String s = \"122164154695\"; preCompute(s); System.out.println(query(0, 3) ? 1 : 0); System.out.println(query(1, 2) ? 1 : 0); System.out.println(query(5, 9) ? 1 : 0); System.out.println(query(0, 11) ? 1 : 0); }} // This code is contributed by Rajput-Ji", "e": 30800, "s": 29034, "text": null }, { "code": "# Python3 program to check divisibility by# 11 in subStrings of a number StringMAX = 1000005 # To store sums of even and odd digitsclass OddEvenSums: def __init__(self, e_sum, o_sum): # Sum of even placed digits self.e_sum = e_sum # Sum of odd placed digits self.o_sum = o_sum sum = [OddEvenSums(0, 0) for i in range(MAX)] # This function receives the String# representation of the number and# precomputes the sum arraydef preCompute(x): # Initialize everb sum[0].e_sum = sum[0].o_sum = 0 # Add the respective digits # depending on whether # they're even indexed or # odd indexed for i in range(len(x)): if (i % 2 == 0): sum[i + 1].e_sum = (sum[i].e_sum + int(x[i])) sum[i + 1].o_sum = sum[i].o_sum else: sum[i + 1].o_sum = (sum[i].o_sum + int(x[i])) sum[i + 1].e_sum = sum[i].e_sum # This function receives l and r representing# the indices and prints the required outputdef query(l, r): diff = ((sum[r + 1].e_sum - sum[r + 1].o_sum) - (sum[l].e_sum - sum[l].o_sum)) if (diff % 11 == 0): return True else: return False # Driver codeif __name__==\"__main__\": s = \"122164154695\" preCompute(s) print(1 if query(0, 3) else 0) print(1 if query(1, 2) else 0) print(1 if query(5, 9) else 0) print(1 if query(0, 11) else 0) # This code is contributed by rutvik_56", "e": 32353, "s": 30800, "text": null }, { "code": "// C# program to check// divisibility by 11 in// subStrings of a number Stringusing System;class GFG{ static int MAX = 1000005; // To store sums of even// and odd digits public class OddEvenSums{ // Sum of even placed digits public int e_sum; // Sum of odd placed digits public int o_sum;}; // Auxiliary arraystatic OddEvenSums []sum = new OddEvenSums[MAX]; // Utility function to// evaluate a character's// integer valuestatic int toInt(char x){ return x - 48;} // This function receives the// String representation of the// number and precomputes the sum arraystatic void preCompute(String x){ // Initialize everb sum[0].e_sum = sum[0].o_sum = 0; // Add the respective digits // depending on whether they're // even indexed or odd indexed for (int i = 0; i < x.Length; i++) { if (i % 2 == 0) { sum[i + 1].e_sum = sum[i].e_sum + toInt(x[i]); sum[i + 1].o_sum = sum[i].o_sum; } else { sum[i + 1].o_sum = sum[i].o_sum + toInt(x[i]); sum[i + 1].e_sum = sum[i].e_sum; } }} // This function receives l and r// representing the indices and// prints the required outputstatic bool query(int l, int r){ int diff = (sum[r + 1].e_sum - sum[r + 1].o_sum) - (sum[l].e_sum - sum[l].o_sum); return (diff % 11 == 0);} // Driver function to check the programpublic static void Main(String[] args){ for (int i = 0; i < MAX; i++) { sum[i] = new OddEvenSums(); } String s = \"122164154695\"; preCompute(s); Console.WriteLine(query(0, 3) ? 1 : 0); Console.WriteLine(query(1, 2) ? 1 : 0); Console.WriteLine(query(5, 9) ? 1 : 0); Console.WriteLine(query(0, 11) ? 1 : 0);}} // This code is contributed by gauravrajput1", "e": 34119, "s": 32353, "text": null }, { "code": "<script>// Javascript program to check divisibility by 11 in// subStrings of a number Stringlet MAX = 1000005; // To store sums of even and odd digitsclass OddEvenSums{ constructor() { this.e_sum = 0; this.o_sum = 0; }} // Auxiliary arraylet sum = new Array(MAX); // Utility function to evaluate a character's// integer valuefunction toInt(x){ return x.charCodeAt(0) - 48;} // This function receives the String representation// of the number and precomputes the sum arrayfunction preCompute(x){ // Initialize everb sum[0].e_sum = sum[0].o_sum = 0; // Add the respective digits depending on whether // they're even indexed or odd indexed for (let i = 0; i < x.length; i++) { if (i % 2 == 0) { sum[i + 1].e_sum = sum[i].e_sum + parseInt(x[i]); sum[i + 1].o_sum = sum[i].o_sum; } else { sum[i + 1].o_sum = sum[i].o_sum + parseInt(x[i]); sum[i + 1].e_sum = sum[i].e_sum; } }} // This function receives l and r representing// the indices and prints the required outputfunction query(l,r){ let diff = (sum[r + 1].e_sum - sum[r + 1].o_sum) - (sum[l].e_sum - sum[l].o_sum); return (diff % 11 == 0);} // driver function to check the programfor (let i = 0; i < MAX; i++) { sum[i] = new OddEvenSums();}let s = \"122164154695\"; preCompute(s); document.write((query(0, 3) ? 1 : 0)+\"<br>\");document.write((query(1, 2) ? 1 : 0)+\"<br>\");document.write((query(5, 9) ? 1 : 0)+\"<br>\");document.write((query(0, 11) ? 1 :0)+\"<br>\"); // This code is contributed by unknown2108</script>", "e": 35758, "s": 34119, "text": null }, { "code": null, "e": 35768, "s": 35758, "text": "Output: " }, { "code": null, "e": 35776, "s": 35768, "text": "1\n1\n0\n1" }, { "code": null, "e": 36199, "s": 35776, "text": "This article is contributed by Ashutosh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 36209, "s": 36199, "text": "Rajput-Ji" }, { "code": null, "e": 36223, "s": 36209, "text": "GauravRajput1" }, { "code": null, "e": 36233, "s": 36223, "text": "rutvik_56" }, { "code": null, "e": 36245, "s": 36233, "text": "unknown2108" }, { "code": null, "e": 36258, "s": 36245, "text": "divisibility" }, { "code": null, "e": 36271, "s": 36258, "text": "Mathematical" }, { "code": null, "e": 36284, "s": 36271, "text": "Mathematical" }, { "code": null, "e": 36382, "s": 36284, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36406, "s": 36382, "text": "Merge two sorted arrays" }, { "code": null, "e": 36449, "s": 36406, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 36463, "s": 36449, "text": "Prime Numbers" }, { "code": null, "e": 36505, "s": 36463, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 36527, "s": 36505, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 36600, "s": 36527, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 36641, "s": 36600, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 36684, "s": 36641, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 36705, "s": 36684, "text": "Operators in C / C++" } ]
Fabric.js Canvas selection Property - GeeksforGeeks
30 Jul, 2021 In this article, we are going to see how to enable or disable the selection of objects in a canvas in Fabric.js using the selection property. The canvas in Fabric.js is used as a wrapper over the native canvas object provided by HTML. It provides high-level access to the underlying canvas allowing it to have an object model, allow parsing for SVG files, and allowing the canvas to be interacted with in an intuitive manner. Approach: To make it possible we are going to use a JavaScript library called Fabric.js. After importing the library, we will create the canvas block in the body tag. After this, we will initialize an instance of the canvas object provided by Fabric.js and set the selection mode needed for the canvas using the selection property. Syntax: fabric.Canvas(canvasElement, { selection: Boolean }); Parameters: This property accepts a single parameter as mentioned above and described below. selection: It is a boolean that specifies whether the selection of objects should be enabled or not on the canvas. Example: The below example illustrates the use of Fabric.js Canvas selection property in JavaScript. HTML <!DOCTYPE html><html> <head> <!-- Adding the FabricJS library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"> </script></head> <body> <div style="text-align: center; width: 500px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <b> Fabric.js | Canvas selection Property </b> </div> <b>Selection Disabled</b> <canvas id="canvas" width="500" height="250" style="border:1px solid #000000"> </canvas> <b>Selection Enabled</b> <canvas id="canvas2" width="500" height="250" style="border:1px solid #000000"> </canvas> <script> let circle = new fabric.Circle({ radius: 30, }); let circle2 = new fabric.Circle({ radius: 30, }); // Initiate a Canvas instance let canvas = new fabric.Canvas("canvas", { // Disable selection // in this Canvas selection: false }); // Initiate a Canvas instance let canvas2 = new fabric.Canvas("canvas2", { // Enable selection // in this Canvas selection: true }); canvas.add(circle); canvas.centerObject(circle); canvas2.add(circle2); canvas2.centerObject(circle2); </script></body> </html> Output: Fabric.js HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload 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": 26139, "s": 26111, "text": "\n30 Jul, 2021" }, { "code": null, "e": 26565, "s": 26139, "text": "In this article, we are going to see how to enable or disable the selection of objects in a canvas in Fabric.js using the selection property. The canvas in Fabric.js is used as a wrapper over the native canvas object provided by HTML. It provides high-level access to the underlying canvas allowing it to have an object model, allow parsing for SVG files, and allowing the canvas to be interacted with in an intuitive manner." }, { "code": null, "e": 26897, "s": 26565, "text": "Approach: To make it possible we are going to use a JavaScript library called Fabric.js. After importing the library, we will create the canvas block in the body tag. After this, we will initialize an instance of the canvas object provided by Fabric.js and set the selection mode needed for the canvas using the selection property." }, { "code": null, "e": 26905, "s": 26897, "text": "Syntax:" }, { "code": null, "e": 26963, "s": 26905, "text": "fabric.Canvas(canvasElement, {\n selection: Boolean\n});" }, { "code": null, "e": 27056, "s": 26963, "text": "Parameters: This property accepts a single parameter as mentioned above and described below." }, { "code": null, "e": 27171, "s": 27056, "text": "selection: It is a boolean that specifies whether the selection of objects should be enabled or not on the canvas." }, { "code": null, "e": 27272, "s": 27171, "text": "Example: The below example illustrates the use of Fabric.js Canvas selection property in JavaScript." }, { "code": null, "e": 27277, "s": 27272, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Adding the FabricJS library --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js\"> </script></head> <body> <div style=\"text-align: center; width: 500px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b> Fabric.js | Canvas selection Property </b> </div> <b>Selection Disabled</b> <canvas id=\"canvas\" width=\"500\" height=\"250\" style=\"border:1px solid #000000\"> </canvas> <b>Selection Enabled</b> <canvas id=\"canvas2\" width=\"500\" height=\"250\" style=\"border:1px solid #000000\"> </canvas> <script> let circle = new fabric.Circle({ radius: 30, }); let circle2 = new fabric.Circle({ radius: 30, }); // Initiate a Canvas instance let canvas = new fabric.Canvas(\"canvas\", { // Disable selection // in this Canvas selection: false }); // Initiate a Canvas instance let canvas2 = new fabric.Canvas(\"canvas2\", { // Enable selection // in this Canvas selection: true }); canvas.add(circle); canvas.centerObject(circle); canvas2.add(circle2); canvas2.centerObject(circle2); </script></body> </html>", "e": 28674, "s": 27277, "text": null }, { "code": null, "e": 28682, "s": 28674, "text": "Output:" }, { "code": null, "e": 28692, "s": 28682, "text": "Fabric.js" }, { "code": null, "e": 28697, "s": 28692, "text": "HTML" }, { "code": null, "e": 28708, "s": 28697, "text": "JavaScript" }, { "code": null, "e": 28725, "s": 28708, "text": "Web Technologies" }, { "code": null, "e": 28730, "s": 28725, "text": "HTML" }, { "code": null, "e": 28828, "s": 28730, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28852, "s": 28828, "text": "REST API (Introduction)" }, { "code": null, "e": 28893, "s": 28852, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 28930, "s": 28893, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28959, "s": 28930, "text": "Form validation using jQuery" }, { "code": null, "e": 28979, "s": 28959, "text": "Angular File Upload" }, { "code": null, "e": 29019, "s": 28979, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29064, "s": 29019, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29125, "s": 29064, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29197, "s": 29125, "text": "Differences between Functional Components and Class Components in React" } ]
Python Lists VS Numpy Arrays - GeeksforGeeks
19 May, 2020 NumPy is the fundamental package for scientific computing in Python. NumPy arrays facilitate advanced mathematical and other types of operations on large numbers of data. Typically, such operations are executed more efficiently and with less code than is possible using Python’s built-in sequences. NumPy is not another programming language but a Python extension module. It provides fast and efficient operations on arrays of homogeneous data. Some important points about Numpy arrays: We can create a N-dimensional array in python using numpy.array(). Array are by default Homogeneous, which means data inside an array must be of the same Datatype. (Note you can also create a structured array in python). Element wise operation is possible. Numpy array has the various function, methods, and variables, to ease our task of matrix computation. Elements of an array are stored contiguously in memory. For example, all rows of a two dimensioned array must have the same number of columns. Or a three dimensioned array must have the same number of rows and columns on each card. Representation of Numpy array: Single Dimensional Numpy Array;import numpy as np a = np.array([1, 2, 3])print(a)Output:[1 2 3] import numpy as np a = np.array([1, 2, 3])print(a) [1 2 3] Multi-dimensional Numpy Array:import numpy as np a = np.array([(1, 2, 3), (4, 5, 6)])print(a)Output:[[1 2 3] [4 5 6]] import numpy as np a = np.array([(1, 2, 3), (4, 5, 6)])print(a) [[1 2 3] [4 5 6]] Advantages of using Numpy Arrays Over Python Lists: consumes less memory. fast as compared to the python List. convenient to use. List: A list is a collection which is ordered and changeable. In Python, lists are written with square brackets. Some important points about Python Lists: The list can be homogeneous or heterogeneous. Element wise operation is not possible on the list. Python list is by default 1 dimensional. But we can create an N-Dimensional list. But then too it will be 1 D list storing another 1D list Elements of a list need not be contiguous in memory. Below are some examples which clearly demonstrate how Numpy arrays are better than Python lists by analyzing the memory consumption, execution time comparison, and operations supported by both of them. Example 1: Memory consumption between Numpy array and listsIn this example, a Python list and a Numpy array of size 1000 will be created. The size of each element and then the whole size of both the containers will be calculated and comparison will be done in terms of memory consumption. Below is the implementation. # importing numpy packageimport numpy as np # importing system moduleimport sys # declaring a list of 1000 elements S= range(1000) # printing size of each element of the listprint("Size of each element of list in bytes: ",sys.getsizeof(S)) # printing size of the whole listprint("Size of the whole list in bytes: ",sys.getsizeof(S)*len(S)) # declaring a Numpy array of 1000 elements D= np.arange(1000) # printing size of each element of the Numpy arrayprint("Size of each element of the Numpy array in bytes: ",D.itemsize) # printing size of the whole Numpy arrayprint("Size of the whole Numpy array in bytes: ",D.size*D.itemsize) Size of each element of list in bytes: 48 Size of the whole list in bytes: 48000 Size of each element of the Numpy array in bytes: 8 Size of the whole Numpy array in bytes: 8000 Example 2: Time comparison between Numpy array and Python listsIn this example, 2 Python lists and 2 Numpy arrays will be created and each container has 1000000 elements. Multiplication of elements in both the lists and Numpy arrays respectively will be carried out and the difference in time needed for the execution for both the containers will be analyzed to determine which one takes less time to perform the operation. Below is the implementation. # importing required packagesimport numpyimport time # size of arrays and listssize = 1000000 # declaring listslist1 = range(size)list2 = range(size) # declaring arraysarray1 = numpy.arange(size) array2 = numpy.arange(size) # capturing time before the multiplication of Python listsinitialTime = time.time() # multiplying elements of both the lists and stored in another listresultantList = [(a * b) for a, b in zip(list1, list2)] # calculating execution timeprint("Time taken by Lists to perform multiplication:", (time.time() - initialTime), "seconds") # capturing time before the multiplication of Numpy arraysinitialTime = time.time() # multiplying elements of both the Numpy arrays and stored in another Numpy array resultantArray = array1 * array2 # calculating execution time print("Time taken by NumPy Arrays to perform multiplication:", (time.time() - initialTime), "seconds") Time taken by Lists : 0.15030384063720703 seconds Time taken by NumPy Arrays : 0.005921125411987305 seconds Example 3: Effect of operations on Numpy array and Python ListsIn this example, the incapability of the Python list to carry out a basic operation is demonstrated. A Python list and a Numpy array having the same elements will be declared and an integer will be added to increment each element of the container by that integer value without looping statements. The effect of this operation on the Numpy array and Python list will be analyzed. Below is the implementation. # importing Numpy packageimport numpy as np # declaring a listls =[1, 2, 3] # converting the list into a Numpy arrayarr = np.array(ls) try: # adding 4 to each element of list ls = ls + 4 except(TypeError): print("Lists don't support list + int") # now on arraytry: # adding 4 to each element of Numpy array arr = arr + 4 # printing the Numpy array print("Modified Numpy array: ",arr) except(TypeError): print("Numpy arrays don't support list + int") Lists don't support list + int Modified Numpy array: [5 6 7] RISHU_MISHRA python-list Python-numpy Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python sum() function in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 25453, "s": 25425, "text": "\n19 May, 2020" }, { "code": null, "e": 25898, "s": 25453, "text": "NumPy is the fundamental package for scientific computing in Python. NumPy arrays facilitate advanced mathematical and other types of operations on large numbers of data. Typically, such operations are executed more efficiently and with less code than is possible using Python’s built-in sequences. NumPy is not another programming language but a Python extension module. It provides fast and efficient operations on arrays of homogeneous data." }, { "code": null, "e": 25940, "s": 25898, "text": "Some important points about Numpy arrays:" }, { "code": null, "e": 26007, "s": 25940, "text": "We can create a N-dimensional array in python using numpy.array()." }, { "code": null, "e": 26161, "s": 26007, "text": "Array are by default Homogeneous, which means data inside an array must be of the same Datatype. (Note you can also create a structured array in python)." }, { "code": null, "e": 26197, "s": 26161, "text": "Element wise operation is possible." }, { "code": null, "e": 26299, "s": 26197, "text": "Numpy array has the various function, methods, and variables, to ease our task of matrix computation." }, { "code": null, "e": 26531, "s": 26299, "text": "Elements of an array are stored contiguously in memory. For example, all rows of a two dimensioned array must have the same number of columns. Or a three dimensioned array must have the same number of rows and columns on each card." }, { "code": null, "e": 26562, "s": 26531, "text": "Representation of Numpy array:" }, { "code": null, "e": 26660, "s": 26562, "text": "Single Dimensional Numpy Array;import numpy as np a = np.array([1, 2, 3])print(a)Output:[1 2 3]\n" }, { "code": "import numpy as np a = np.array([1, 2, 3])print(a)", "e": 26712, "s": 26660, "text": null }, { "code": null, "e": 26721, "s": 26712, "text": "[1 2 3]\n" }, { "code": null, "e": 26842, "s": 26721, "text": "Multi-dimensional Numpy Array:import numpy as np a = np.array([(1, 2, 3), (4, 5, 6)])print(a)Output:[[1 2 3]\n [4 5 6]]\n" }, { "code": "import numpy as np a = np.array([(1, 2, 3), (4, 5, 6)])print(a)", "e": 26907, "s": 26842, "text": null }, { "code": null, "e": 26927, "s": 26907, "text": "[[1 2 3]\n [4 5 6]]\n" }, { "code": null, "e": 26979, "s": 26927, "text": "Advantages of using Numpy Arrays Over Python Lists:" }, { "code": null, "e": 27001, "s": 26979, "text": "consumes less memory." }, { "code": null, "e": 27038, "s": 27001, "text": "fast as compared to the python List." }, { "code": null, "e": 27057, "s": 27038, "text": "convenient to use." }, { "code": null, "e": 27170, "s": 27057, "text": "List: A list is a collection which is ordered and changeable. In Python, lists are written with square brackets." }, { "code": null, "e": 27212, "s": 27170, "text": "Some important points about Python Lists:" }, { "code": null, "e": 27258, "s": 27212, "text": "The list can be homogeneous or heterogeneous." }, { "code": null, "e": 27310, "s": 27258, "text": "Element wise operation is not possible on the list." }, { "code": null, "e": 27449, "s": 27310, "text": "Python list is by default 1 dimensional. But we can create an N-Dimensional list. But then too it will be 1 D list storing another 1D list" }, { "code": null, "e": 27502, "s": 27449, "text": "Elements of a list need not be contiguous in memory." }, { "code": null, "e": 27704, "s": 27502, "text": "Below are some examples which clearly demonstrate how Numpy arrays are better than Python lists by analyzing the memory consumption, execution time comparison, and operations supported by both of them." }, { "code": null, "e": 27993, "s": 27704, "text": "Example 1: Memory consumption between Numpy array and listsIn this example, a Python list and a Numpy array of size 1000 will be created. The size of each element and then the whole size of both the containers will be calculated and comparison will be done in terms of memory consumption." }, { "code": null, "e": 28022, "s": 27993, "text": "Below is the implementation." }, { "code": "# importing numpy packageimport numpy as np # importing system moduleimport sys # declaring a list of 1000 elements S= range(1000) # printing size of each element of the listprint(\"Size of each element of list in bytes: \",sys.getsizeof(S)) # printing size of the whole listprint(\"Size of the whole list in bytes: \",sys.getsizeof(S)*len(S)) # declaring a Numpy array of 1000 elements D= np.arange(1000) # printing size of each element of the Numpy arrayprint(\"Size of each element of the Numpy array in bytes: \",D.itemsize) # printing size of the whole Numpy arrayprint(\"Size of the whole Numpy array in bytes: \",D.size*D.itemsize)", "e": 28660, "s": 28022, "text": null }, { "code": null, "e": 28843, "s": 28660, "text": "Size of each element of list in bytes: 48\nSize of the whole list in bytes: 48000\nSize of each element of the Numpy array in bytes: 8\nSize of the whole Numpy array in bytes: 8000\n" }, { "code": null, "e": 29267, "s": 28843, "text": "Example 2: Time comparison between Numpy array and Python listsIn this example, 2 Python lists and 2 Numpy arrays will be created and each container has 1000000 elements. Multiplication of elements in both the lists and Numpy arrays respectively will be carried out and the difference in time needed for the execution for both the containers will be analyzed to determine which one takes less time to perform the operation." }, { "code": null, "e": 29296, "s": 29267, "text": "Below is the implementation." }, { "code": "# importing required packagesimport numpyimport time # size of arrays and listssize = 1000000 # declaring listslist1 = range(size)list2 = range(size) # declaring arraysarray1 = numpy.arange(size) array2 = numpy.arange(size) # capturing time before the multiplication of Python listsinitialTime = time.time() # multiplying elements of both the lists and stored in another listresultantList = [(a * b) for a, b in zip(list1, list2)] # calculating execution timeprint(\"Time taken by Lists to perform multiplication:\", (time.time() - initialTime), \"seconds\") # capturing time before the multiplication of Numpy arraysinitialTime = time.time() # multiplying elements of both the Numpy arrays and stored in another Numpy array resultantArray = array1 * array2 # calculating execution time print(\"Time taken by NumPy Arrays to perform multiplication:\", (time.time() - initialTime), \"seconds\")", "e": 30224, "s": 29296, "text": null }, { "code": null, "e": 30333, "s": 30224, "text": "Time taken by Lists : 0.15030384063720703 seconds\nTime taken by NumPy Arrays : 0.005921125411987305 seconds\n" }, { "code": null, "e": 30775, "s": 30333, "text": "Example 3: Effect of operations on Numpy array and Python ListsIn this example, the incapability of the Python list to carry out a basic operation is demonstrated. A Python list and a Numpy array having the same elements will be declared and an integer will be added to increment each element of the container by that integer value without looping statements. The effect of this operation on the Numpy array and Python list will be analyzed." }, { "code": null, "e": 30804, "s": 30775, "text": "Below is the implementation." }, { "code": "# importing Numpy packageimport numpy as np # declaring a listls =[1, 2, 3] # converting the list into a Numpy arrayarr = np.array(ls) try: # adding 4 to each element of list ls = ls + 4 except(TypeError): print(\"Lists don't support list + int\") # now on arraytry: # adding 4 to each element of Numpy array arr = arr + 4 # printing the Numpy array print(\"Modified Numpy array: \",arr) except(TypeError): print(\"Numpy arrays don't support list + int\")", "e": 31294, "s": 30804, "text": null }, { "code": null, "e": 31356, "s": 31294, "text": "Lists don't support list + int\nModified Numpy array: [5 6 7]\n" }, { "code": null, "e": 31369, "s": 31356, "text": "RISHU_MISHRA" }, { "code": null, "e": 31381, "s": 31369, "text": "python-list" }, { "code": null, "e": 31394, "s": 31381, "text": "Python-numpy" }, { "code": null, "e": 31401, "s": 31394, "text": "Python" }, { "code": null, "e": 31413, "s": 31401, "text": "python-list" }, { "code": null, "e": 31511, "s": 31413, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31543, "s": 31511, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31565, "s": 31543, "text": "Enumerate() in Python" }, { "code": null, "e": 31607, "s": 31565, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 31633, "s": 31607, "text": "Python String | replace()" }, { "code": null, "e": 31662, "s": 31633, "text": "*args and **kwargs in Python" }, { "code": null, "e": 31699, "s": 31662, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 31735, "s": 31699, "text": "Convert integer to string in Python" }, { "code": null, "e": 31777, "s": 31735, "text": "Check if element exists in list in Python" }, { "code": null, "e": 31802, "s": 31777, "text": "sum() function in Python" } ]
How to Fix: Length of values does not match length of index - GeeksforGeeks
22 Nov, 2021 In this article we will fix the error: The length of values does not match the length of the index in Python. Python3 # importing pandasimport pandas as pd sepal_length = [5.1, 4.9, 4.7, 4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9]sepal_width = [4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9, 5.1, 5.2, 5.3]petal_length = [3.3, 4.6, 4.7, 5.6, 6.7, 5.0, 4.8]petal_width = [3.6, 5.6, 5.4, 4.6, 4.4, 5.0, 4.9] # DataFrame with 2 columnsdf = pd.DataFrame({'sepal_length(cm)': sepal_length, 'sepal_width(cm)': sepal_width}) df['petal_length(cm)'] = petal_lengthdf['petal_width(cm)'] = petal_width print(df) Output: ValueError: Length of values (7) does not match length of index (10) The length of the index of the pandas DataFrame(i.e length of the column of present DataFrame) which is 10 in this case is not equal to the length of the new list or NumPy array which is 7 in this case. pd.Index.size!=len(petal_width) This error can be fixed by preprocessing the new list or NumPy array that is going to be a column of the DataFrame by using the pandas Series() function which actually converts the list or NumPy array into the size of the DataFrame column length by adding NaN if list or NumPy array has lesser length else if the list or NumPy has greater length then it takes the list or NumPy array with the length of columns of the pandas dataframe. Syntax For list: Consider list1 as a python list df['new_column'] = pd.Series(list1) Syntax For NumPy array: Consider numarr as a numpy array df['new_column'] = pd.Series(numarr) Python3 # importing pandasimport pandas as pd # importing numpyimport numpy as npsepal_length = [5.1, 4.9, 4.7, 4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9]sepal_width = [4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9, 5.1, 5.2, 5.3]petal_length = [3.3, 4.6, 4.7, 5.6, 6.7, 5.0, 4.8] # numpy array of length 7petal_width = np.array([3.6, 5.6, 5.4, 4.6, 4.4, 5.0, 4.9]) # DataFrame with 2 columns of length 10df = pd.DataFrame({'sepal_length(cm)': sepal_length, 'sepal_width(cm)': sepal_width}) # Adding list to pandas DataFramedf['petal_length(cm)'] = pd.Series(petal_length) # Adding numpy array to pandas DataFramedf['petal_width(cm)'] = pd.Series(petal_width) print(df) Output: Picked Python How-to-fix 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 Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n22 Nov, 2021" }, { "code": null, "e": 25647, "s": 25537, "text": "In this article we will fix the error: The length of values does not match the length of the index in Python." }, { "code": null, "e": 25655, "s": 25647, "text": "Python3" }, { "code": "# importing pandasimport pandas as pd sepal_length = [5.1, 4.9, 4.7, 4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9]sepal_width = [4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9, 5.1, 5.2, 5.3]petal_length = [3.3, 4.6, 4.7, 5.6, 6.7, 5.0, 4.8]petal_width = [3.6, 5.6, 5.4, 4.6, 4.4, 5.0, 4.9] # DataFrame with 2 columnsdf = pd.DataFrame({'sepal_length(cm)': sepal_length, 'sepal_width(cm)': sepal_width}) df['petal_length(cm)'] = petal_lengthdf['petal_width(cm)'] = petal_width print(df)", "e": 26170, "s": 25655, "text": null }, { "code": null, "e": 26178, "s": 26170, "text": "Output:" }, { "code": null, "e": 26247, "s": 26178, "text": "ValueError: Length of values (7) does not match length of index (10)" }, { "code": null, "e": 26450, "s": 26247, "text": "The length of the index of the pandas DataFrame(i.e length of the column of present DataFrame) which is 10 in this case is not equal to the length of the new list or NumPy array which is 7 in this case." }, { "code": null, "e": 26482, "s": 26450, "text": "pd.Index.size!=len(petal_width)" }, { "code": null, "e": 26918, "s": 26482, "text": "This error can be fixed by preprocessing the new list or NumPy array that is going to be a column of the DataFrame by using the pandas Series() function which actually converts the list or NumPy array into the size of the DataFrame column length by adding NaN if list or NumPy array has lesser length else if the list or NumPy has greater length then it takes the list or NumPy array with the length of columns of the pandas dataframe." }, { "code": null, "e": 26935, "s": 26918, "text": "Syntax For list:" }, { "code": null, "e": 26967, "s": 26935, "text": "Consider list1 as a python list" }, { "code": null, "e": 27003, "s": 26967, "text": "df['new_column'] = pd.Series(list1)" }, { "code": null, "e": 27027, "s": 27003, "text": "Syntax For NumPy array:" }, { "code": null, "e": 27060, "s": 27027, "text": "Consider numarr as a numpy array" }, { "code": null, "e": 27097, "s": 27060, "text": "df['new_column'] = pd.Series(numarr)" }, { "code": null, "e": 27105, "s": 27097, "text": "Python3" }, { "code": "# importing pandasimport pandas as pd # importing numpyimport numpy as npsepal_length = [5.1, 4.9, 4.7, 4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9]sepal_width = [4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9, 5.1, 5.2, 5.3]petal_length = [3.3, 4.6, 4.7, 5.6, 6.7, 5.0, 4.8] # numpy array of length 7petal_width = np.array([3.6, 5.6, 5.4, 4.6, 4.4, 5.0, 4.9]) # DataFrame with 2 columns of length 10df = pd.DataFrame({'sepal_length(cm)': sepal_length, 'sepal_width(cm)': sepal_width}) # Adding list to pandas DataFramedf['petal_length(cm)'] = pd.Series(petal_length) # Adding numpy array to pandas DataFramedf['petal_width(cm)'] = pd.Series(petal_width) print(df)", "e": 27824, "s": 27105, "text": null }, { "code": null, "e": 27832, "s": 27824, "text": "Output:" }, { "code": null, "e": 27839, "s": 27832, "text": "Picked" }, { "code": null, "e": 27857, "s": 27839, "text": "Python How-to-fix" }, { "code": null, "e": 27864, "s": 27857, "text": "Python" }, { "code": null, "e": 27962, "s": 27864, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27994, "s": 27962, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28036, "s": 27994, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28078, "s": 28036, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28105, "s": 28078, "text": "Python Classes and Objects" }, { "code": null, "e": 28161, "s": 28105, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28200, "s": 28161, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28222, "s": 28200, "text": "Defaultdict in Python" }, { "code": null, "e": 28253, "s": 28222, "text": "Python | os.path.join() method" }, { "code": null, "e": 28282, "s": 28253, "text": "Create a directory in Python" } ]
Sum of the alphabetical values of the characters of a string - GeeksforGeeks
19 Mar, 2021 You are given an array of strings str, the task is to find the score of a given string s from the array. The score of a string is defined as the product of the sum of its characters’s alphabetical values with the position of the string in the array.Examples: Input: str[] = {“sahil”, “shashanak”, “sanjit”, “abhinav”, “mohit”}, s = “abhinav” Output: 228 Sum of alphabetical values of “abhinav” = 1 + 2 + 8 + 9 + 14 + 1 + 22 = 57 Position of “abhinav” in str is 4, 57 x 4 = 228 Input: str[] = {“geeksforgeeks”, “algorithms”, “stack”}, s = “algorithms” Output: 244 Approach: Find the given string in the array and store the position of the string. Then calculate the sum of the alphabetical values of the given string. Multiply the position of the string in the given array with the value calculated in the previous step and print the result. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find string scoreint strScore(string str[], string s, int n){ int score = 0, index; for (int i = 0; i < n; i++) { if (str[i] == s) { for (int j = 0; j < s.length(); j++) score += s[j] - 'a' + 1; index = i + 1; break; } } score = score * index; return score;} // Driver codeint main(){ string str[] = { "sahil", "shashanak" , "sanjit", "abhinav", "mohit" }; string s = "abhinav"; int n = sizeof(str) / sizeof(str[0]); int score = strScore(str, s, n); cout << score << endl; return 0;} // Java implementation of the approachimport java.io.*; class GFG { // Function to find string scorestatic int strScore(String str[], String s, int n){ int score = 0, index=0; for (int i = 0; i < n; i++) { if (str[i] == s) { for (int j = 0; j < s.length(); j++) score += s.charAt(j) - 'a' + 1; index = i + 1; break; } } score = score * index; return score;} // Driver code public static void main (String[] args) { String str[] = { "sahil", "shashanak" , "sanjit", "abhinav", "mohit" }; String s = "abhinav"; int n = str.length; int score = strScore(str, s, n); System.out.println( score); }}// This code is contributed by anuj_67.. # Python3 implementation of the approach# Function to find string scoredef strScore(str, s, n): score = 0 index = 0 for i in range(n): if (str[i] == s): for j in range(len(s)): score += (ord(s[j]) - ord('a') + 1) index = i + 1 break score = score * index return score # Driver codestr = ["sahil", "shashanak", "sanjit", "abhinav", "mohit" ]s = "abhinav"n = len(str)score = strScore(str, s, n);print(score) # This code is contributed# by sahishelangia // C# implementation of the approachusing System; class GFG{ // Function to find string scorestatic int strScore(String []str, String s, int n){ int score = 0, index = 0; for (int i = 0; i < n; i++) { if (str[i] == s) { for (int j = 0; j < s.Length; j++) score += s[j] - 'a' + 1; index = i + 1; break; } } score = score * index; return score;} // Driver codepublic static void Main (String[] args){ String []str = { "sahil", "shashanak", "sanjit", "abhinav", "mohit" }; String s = "abhinav"; int n = str.Length; int score = strScore(str, s, n); Console.Write( score);}} // This code is contributed by 29AjayKumar <?php // Function to find string scorefunction strScore($str, $s, $n){ $score = 0; $index; for ($i = 0; $i < $n; $i++) { if ($str[$i] == $s) { for ($j = 0; $j < strlen($s); $j++) $score += (ord($s[$j]) - ord('a')) + 1; $index = ($i + 1); break; } } $score = $score * $index; return $score;} // Driver code$str = array( "sahil", "shashanak", "sanjit", "abhinav", "mohit" );$s = "abhinav";$n = sizeof($str);$score = strScore($str, $s, $n);echo $score, "\n"; // This code is contributed by jit_t?> <script> // javascript implementation of the approach // Function to find string scorefunction strScore(str, s , n){ var score = 0, index=0; for (i = 0; i < n; i++) { if (str[i] == s) { for (j = 0; j < s.length; j++){ score += s.charAt(j).charCodeAt(0) - ('a').charCodeAt(0) + 1; } index = i + 1; break; } } score = score * index; return score;} // Driver codestr = [ "sahil", "shashanak" , "sanjit", "abhinav", "mohit" ]; s = "abhinav"; var n = str.length; var score = strScore(str, s, n); document.write( score); // This code contributed by shikhasingrajput</script> 228 vt_m 29AjayKumar sahilshelangia jit_t shikhasingrajput ASCII Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Different methods to reverse a string in C/C++ Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Check whether two strings are anagram of each other Top 50 String Coding Problems for Interviews
[ { "code": null, "e": 26565, "s": 26537, "text": "\n19 Mar, 2021" }, { "code": null, "e": 26826, "s": 26565, "text": "You are given an array of strings str, the task is to find the score of a given string s from the array. The score of a string is defined as the product of the sum of its characters’s alphabetical values with the position of the string in the array.Examples: " }, { "code": null, "e": 27132, "s": 26826, "text": "Input: str[] = {“sahil”, “shashanak”, “sanjit”, “abhinav”, “mohit”}, s = “abhinav” Output: 228 Sum of alphabetical values of “abhinav” = 1 + 2 + 8 + 9 + 14 + 1 + 22 = 57 Position of “abhinav” in str is 4, 57 x 4 = 228 Input: str[] = {“geeksforgeeks”, “algorithms”, “stack”}, s = “algorithms” Output: 244 " }, { "code": null, "e": 27146, "s": 27134, "text": "Approach: " }, { "code": null, "e": 27219, "s": 27146, "text": "Find the given string in the array and store the position of the string." }, { "code": null, "e": 27290, "s": 27219, "text": "Then calculate the sum of the alphabetical values of the given string." }, { "code": null, "e": 27414, "s": 27290, "text": "Multiply the position of the string in the given array with the value calculated in the previous step and print the result." }, { "code": null, "e": 27467, "s": 27414, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27471, "s": 27467, "text": "C++" }, { "code": null, "e": 27476, "s": 27471, "text": "Java" }, { "code": null, "e": 27484, "s": 27476, "text": "Python3" }, { "code": null, "e": 27487, "s": 27484, "text": "C#" }, { "code": null, "e": 27491, "s": 27487, "text": "PHP" }, { "code": null, "e": 27502, "s": 27491, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find string scoreint strScore(string str[], string s, int n){ int score = 0, index; for (int i = 0; i < n; i++) { if (str[i] == s) { for (int j = 0; j < s.length(); j++) score += s[j] - 'a' + 1; index = i + 1; break; } } score = score * index; return score;} // Driver codeint main(){ string str[] = { \"sahil\", \"shashanak\" , \"sanjit\", \"abhinav\", \"mohit\" }; string s = \"abhinav\"; int n = sizeof(str) / sizeof(str[0]); int score = strScore(str, s, n); cout << score << endl; return 0;}", "e": 28201, "s": 27502, "text": null }, { "code": "// Java implementation of the approachimport java.io.*; class GFG { // Function to find string scorestatic int strScore(String str[], String s, int n){ int score = 0, index=0; for (int i = 0; i < n; i++) { if (str[i] == s) { for (int j = 0; j < s.length(); j++) score += s.charAt(j) - 'a' + 1; index = i + 1; break; } } score = score * index; return score;} // Driver code public static void main (String[] args) { String str[] = { \"sahil\", \"shashanak\" , \"sanjit\", \"abhinav\", \"mohit\" }; String s = \"abhinav\"; int n = str.length; int score = strScore(str, s, n); System.out.println( score); }}// This code is contributed by anuj_67..", "e": 28964, "s": 28201, "text": null }, { "code": "# Python3 implementation of the approach# Function to find string scoredef strScore(str, s, n): score = 0 index = 0 for i in range(n): if (str[i] == s): for j in range(len(s)): score += (ord(s[j]) - ord('a') + 1) index = i + 1 break score = score * index return score # Driver codestr = [\"sahil\", \"shashanak\", \"sanjit\", \"abhinav\", \"mohit\" ]s = \"abhinav\"n = len(str)score = strScore(str, s, n);print(score) # This code is contributed# by sahishelangia", "e": 29527, "s": 28964, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to find string scorestatic int strScore(String []str, String s, int n){ int score = 0, index = 0; for (int i = 0; i < n; i++) { if (str[i] == s) { for (int j = 0; j < s.Length; j++) score += s[j] - 'a' + 1; index = i + 1; break; } } score = score * index; return score;} // Driver codepublic static void Main (String[] args){ String []str = { \"sahil\", \"shashanak\", \"sanjit\", \"abhinav\", \"mohit\" }; String s = \"abhinav\"; int n = str.Length; int score = strScore(str, s, n); Console.Write( score);}} // This code is contributed by 29AjayKumar", "e": 30282, "s": 29527, "text": null }, { "code": "<?php // Function to find string scorefunction strScore($str, $s, $n){ $score = 0; $index; for ($i = 0; $i < $n; $i++) { if ($str[$i] == $s) { for ($j = 0; $j < strlen($s); $j++) $score += (ord($s[$j]) - ord('a')) + 1; $index = ($i + 1); break; } } $score = $score * $index; return $score;} // Driver code$str = array( \"sahil\", \"shashanak\", \"sanjit\", \"abhinav\", \"mohit\" );$s = \"abhinav\";$n = sizeof($str);$score = strScore($str, $s, $n);echo $score, \"\\n\"; // This code is contributed by jit_t?>", "e": 30881, "s": 30282, "text": null }, { "code": "<script> // javascript implementation of the approach // Function to find string scorefunction strScore(str, s , n){ var score = 0, index=0; for (i = 0; i < n; i++) { if (str[i] == s) { for (j = 0; j < s.length; j++){ score += s.charAt(j).charCodeAt(0) - ('a').charCodeAt(0) + 1; } index = i + 1; break; } } score = score * index; return score;} // Driver codestr = [ \"sahil\", \"shashanak\" , \"sanjit\", \"abhinav\", \"mohit\" ]; s = \"abhinav\"; var n = str.length; var score = strScore(str, s, n); document.write( score); // This code contributed by shikhasingrajput</script>", "e": 31593, "s": 30881, "text": null }, { "code": null, "e": 31597, "s": 31593, "text": "228" }, { "code": null, "e": 31604, "s": 31599, "text": "vt_m" }, { "code": null, "e": 31616, "s": 31604, "text": "29AjayKumar" }, { "code": null, "e": 31631, "s": 31616, "text": "sahilshelangia" }, { "code": null, "e": 31637, "s": 31631, "text": "jit_t" }, { "code": null, "e": 31654, "s": 31637, "text": "shikhasingrajput" }, { "code": null, "e": 31660, "s": 31654, "text": "ASCII" }, { "code": null, "e": 31668, "s": 31660, "text": "Strings" }, { "code": null, "e": 31676, "s": 31668, "text": "Strings" }, { "code": null, "e": 31774, "s": 31676, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31849, "s": 31774, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 31906, "s": 31849, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 31942, "s": 31906, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 31989, "s": 31942, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 32042, "s": 31989, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 32078, "s": 32042, "text": "Convert string to char array in C++" }, { "code": null, "e": 32116, "s": 32078, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 32146, "s": 32116, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 32198, "s": 32146, "text": "Check whether two strings are anagram of each other" } ]
Python | sympy.rewrite() method - GeeksforGeeks
07 Jul, 2019 With the help of sympy.rewrite() method, we can represent any mathematical function in terms of another function. Syntax: expression.rewrite(function) Parameters:expression – It is mathematical expression which is to be represented by another function.function – It is the mathematical function used to rewrite the given expression. Returns: Returns a mathematical expression corresponding to the input in terms of specified function. Example #1: # import sympy from sympy import * x = symbols('x')expr = tan(x)print("Expression = {}".format(expr)) # Use sympy.rewrite() method expr_in_terms_of_sin = expr.rewrite(sin) print("Expression in terms of sin() : {}".format(expr_in_terms_of_sin)) Output: Expression = tan(x) Expression in terms of sin() : 2*sin(x)**2/sin(2*x) Example #2: # import sympy from sympy import * x = symbols('x')expr = factorial(x)print("Expression = {}".format(expr)) # Use sympy.rewrite() method expr_in_terms_of_gamma = expr.rewrite(gamma) print("Expression in terms of gamma() : {}".format(expr_in_terms_of_gamma)) Output: Expression = factorial(x) Expression in terms of gamma() : gamma(x + 1) SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python sum() function in Python
[ { "code": null, "e": 26061, "s": 26033, "text": "\n07 Jul, 2019" }, { "code": null, "e": 26175, "s": 26061, "text": "With the help of sympy.rewrite() method, we can represent any mathematical function in terms of another function." }, { "code": null, "e": 26212, "s": 26175, "text": "Syntax: expression.rewrite(function)" }, { "code": null, "e": 26394, "s": 26212, "text": "Parameters:expression – It is mathematical expression which is to be represented by another function.function – It is the mathematical function used to rewrite the given expression." }, { "code": null, "e": 26496, "s": 26394, "text": "Returns: Returns a mathematical expression corresponding to the input in terms of specified function." }, { "code": null, "e": 26508, "s": 26496, "text": "Example #1:" }, { "code": "# import sympy from sympy import * x = symbols('x')expr = tan(x)print(\"Expression = {}\".format(expr)) # Use sympy.rewrite() method expr_in_terms_of_sin = expr.rewrite(sin) print(\"Expression in terms of sin() : {}\".format(expr_in_terms_of_sin)) ", "e": 26765, "s": 26508, "text": null }, { "code": null, "e": 26773, "s": 26765, "text": "Output:" }, { "code": null, "e": 26846, "s": 26773, "text": "Expression = tan(x)\nExpression in terms of sin() : 2*sin(x)**2/sin(2*x)\n" }, { "code": null, "e": 26858, "s": 26846, "text": "Example #2:" }, { "code": "# import sympy from sympy import * x = symbols('x')expr = factorial(x)print(\"Expression = {}\".format(expr)) # Use sympy.rewrite() method expr_in_terms_of_gamma = expr.rewrite(gamma) print(\"Expression in terms of gamma() : {}\".format(expr_in_terms_of_gamma)) ", "e": 27129, "s": 26858, "text": null }, { "code": null, "e": 27137, "s": 27129, "text": "Output:" }, { "code": null, "e": 27210, "s": 27137, "text": "Expression = factorial(x)\nExpression in terms of gamma() : gamma(x + 1)\n" }, { "code": null, "e": 27216, "s": 27210, "text": "SymPy" }, { "code": null, "e": 27223, "s": 27216, "text": "Python" }, { "code": null, "e": 27321, "s": 27223, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27339, "s": 27321, "text": "Python Dictionary" }, { "code": null, "e": 27371, "s": 27339, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27393, "s": 27371, "text": "Enumerate() in Python" }, { "code": null, "e": 27435, "s": 27393, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27464, "s": 27435, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27508, "s": 27464, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27545, "s": 27508, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27581, "s": 27545, "text": "Convert integer to string in Python" }, { "code": null, "e": 27623, "s": 27581, "text": "Check if element exists in list in Python" } ]
How to create Emoji Picker in ReactJS ? - GeeksforGeeks
08 Nov, 2021 In this article, we are going to learn how we can create Emoji Picker in ReactJs. React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies. Approach: To create our Spreadsheet we are going to use the emoji-picker-react package because it is powerful, lightweight, and fully customizable. After that, we will add an emoji picker on our homepage using the installed package. Create ReactJs Application: You can create a new ReactJs project using the below command: npx create-react-app gfg Module Installation: Install the emoji-picker-react package using the below command: npm i emoji-picker-react Project Structure: It will look like this. Filename: App.js In this example, we are going to add the emoji picker on the homepage of our app using the package that we installed. For this, add the below content in the App.js file. Javascript import React, { useState } from 'react';import Picker from 'emoji-picker-react'; export default function Emoji(){ const [chosenEmoji, setChosenEmoji] = useState(null); const onEmojiClick = (event, emojiObject) => { setChosenEmoji(emojiObject); }; return ( <div> <h3>GeeksforGeeks Emoji Picker</h3> {chosenEmoji ? ( <span>Your Emoji: {chosenEmoji.emoji}</span> ) : ( <span>No Emoji</span> )} <Picker onEmojiClick={onEmojiClick} /> </div> );}; Explanation: In the above example first, we are importing the Picker component from the emoji-picker-react package. After that, we are using our useState to add the initial data and update the emoji. Then we are adding our Emoji PIcker using the Picker component. Steps to run the application: Run the below command in the terminal to run the app. npm start Output: React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ReactJS useNavigate() Hook How to set background images in ReactJS ? Axios in React: A Guide for Beginners How to create a table in ReactJS ? How to navigate on path by button click in react router ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26071, "s": 26043, "text": "\n08 Nov, 2021" }, { "code": null, "e": 26346, "s": 26071, "text": "In this article, we are going to learn how we can create Emoji Picker in ReactJs. React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies." }, { "code": null, "e": 26579, "s": 26346, "text": "Approach: To create our Spreadsheet we are going to use the emoji-picker-react package because it is powerful, lightweight, and fully customizable. After that, we will add an emoji picker on our homepage using the installed package." }, { "code": null, "e": 26669, "s": 26579, "text": "Create ReactJs Application: You can create a new ReactJs project using the below command:" }, { "code": null, "e": 26694, "s": 26669, "text": "npx create-react-app gfg" }, { "code": null, "e": 26779, "s": 26694, "text": "Module Installation: Install the emoji-picker-react package using the below command:" }, { "code": null, "e": 26804, "s": 26779, "text": "npm i emoji-picker-react" }, { "code": null, "e": 26847, "s": 26804, "text": "Project Structure: It will look like this." }, { "code": null, "e": 27034, "s": 26847, "text": "Filename: App.js In this example, we are going to add the emoji picker on the homepage of our app using the package that we installed. For this, add the below content in the App.js file." }, { "code": null, "e": 27045, "s": 27034, "text": "Javascript" }, { "code": "import React, { useState } from 'react';import Picker from 'emoji-picker-react'; export default function Emoji(){ const [chosenEmoji, setChosenEmoji] = useState(null); const onEmojiClick = (event, emojiObject) => { setChosenEmoji(emojiObject); }; return ( <div> <h3>GeeksforGeeks Emoji Picker</h3> {chosenEmoji ? ( <span>Your Emoji: {chosenEmoji.emoji}</span> ) : ( <span>No Emoji</span> )} <Picker onEmojiClick={onEmojiClick} /> </div> );};", "e": 27545, "s": 27045, "text": null }, { "code": null, "e": 27809, "s": 27545, "text": "Explanation: In the above example first, we are importing the Picker component from the emoji-picker-react package. After that, we are using our useState to add the initial data and update the emoji. Then we are adding our Emoji PIcker using the Picker component." }, { "code": null, "e": 27893, "s": 27809, "text": "Steps to run the application: Run the below command in the terminal to run the app." }, { "code": null, "e": 27903, "s": 27893, "text": "npm start" }, { "code": null, "e": 27911, "s": 27903, "text": "Output:" }, { "code": null, "e": 27927, "s": 27911, "text": "React-Questions" }, { "code": null, "e": 27935, "s": 27927, "text": "ReactJS" }, { "code": null, "e": 27952, "s": 27935, "text": "Web Technologies" }, { "code": null, "e": 28050, "s": 27952, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28077, "s": 28050, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 28119, "s": 28077, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 28157, "s": 28119, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 28192, "s": 28157, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 28250, "s": 28192, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 28290, "s": 28250, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28323, "s": 28290, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28368, "s": 28323, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28418, "s": 28368, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to push data in a MongoDB document ? - GeeksforGeeks
12 Nov, 2021 The insertOne() and insertMany() are the two methods of the MongoDB module in node.js that are used to push the documents in the collections of the MongoDB database. The insertOne() method inserts one data at a time into the collection and insertMany() method inserts multiple data into the collection of the MongoDB database. In this article, we will discuss how to push data in MongoDB collection using MongoDB module methods. Installing module: You can install mongodb module using the following command. node install mongodb Project Structure: It will look like the following. Running Server on Local IP: Data is the directory where MongoDB server is present. mongod --dbpath=data --bind_ip 127.0.0.1 index.js const MongoClient = require("mongodb"); // Server running const url = 'mongodb://localhost:27017/'; // Database nameconst databasename = "GFG"; MongoClient.connect(url).then((client) => { // Connecting to the database const connect = client.db(databasename); // Database collection const collection = connect .collection("GFGcollections"); // Inserting single document collection.insertOne({ "name": "aayush", "class": "GFG" }); // Inserting multiple document collection.insertMany([ { "name": "saini", "class": "GFG" }, { "name": "GfGnew", "class": "GFGNEW" } ]); console.log("Insertion Successful")}).catch(err) => { // If error occured show the error message console.log(err.Message);} Run index.js file using the following command: node index.js Output: MongoDB Database: clintra MongoDB Node.js-Methods NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect Node.js with React.js ? Node.js Export Module Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Mongoose find() Function Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26267, "s": 26239, "text": "\n12 Nov, 2021" }, { "code": null, "e": 26696, "s": 26267, "text": "The insertOne() and insertMany() are the two methods of the MongoDB module in node.js that are used to push the documents in the collections of the MongoDB database. The insertOne() method inserts one data at a time into the collection and insertMany() method inserts multiple data into the collection of the MongoDB database. In this article, we will discuss how to push data in MongoDB collection using MongoDB module methods." }, { "code": null, "e": 26776, "s": 26696, "text": "Installing module: You can install mongodb module using the following command. " }, { "code": null, "e": 26797, "s": 26776, "text": "node install mongodb" }, { "code": null, "e": 26849, "s": 26797, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26932, "s": 26849, "text": "Running Server on Local IP: Data is the directory where MongoDB server is present." }, { "code": null, "e": 26973, "s": 26932, "text": "mongod --dbpath=data --bind_ip 127.0.0.1" }, { "code": null, "e": 26982, "s": 26973, "text": "index.js" }, { "code": "const MongoClient = require(\"mongodb\"); // Server running const url = 'mongodb://localhost:27017/'; // Database nameconst databasename = \"GFG\"; MongoClient.connect(url).then((client) => { // Connecting to the database const connect = client.db(databasename); // Database collection const collection = connect .collection(\"GFGcollections\"); // Inserting single document collection.insertOne({ \"name\": \"aayush\", \"class\": \"GFG\" }); // Inserting multiple document collection.insertMany([ { \"name\": \"saini\", \"class\": \"GFG\" }, { \"name\": \"GfGnew\", \"class\": \"GFGNEW\" } ]); console.log(\"Insertion Successful\")}).catch(err) => { // If error occured show the error message console.log(err.Message);}", "e": 27757, "s": 26982, "text": null }, { "code": null, "e": 27804, "s": 27757, "text": "Run index.js file using the following command:" }, { "code": null, "e": 27818, "s": 27804, "text": "node index.js" }, { "code": null, "e": 27826, "s": 27818, "text": "Output:" }, { "code": null, "e": 27844, "s": 27826, "text": "MongoDB Database:" }, { "code": null, "e": 27852, "s": 27844, "text": "clintra" }, { "code": null, "e": 27860, "s": 27852, "text": "MongoDB" }, { "code": null, "e": 27876, "s": 27860, "text": "Node.js-Methods" }, { "code": null, "e": 27893, "s": 27876, "text": "NodeJS-Questions" }, { "code": null, "e": 27900, "s": 27893, "text": "Picked" }, { "code": null, "e": 27908, "s": 27900, "text": "Node.js" }, { "code": null, "e": 27925, "s": 27908, "text": "Web Technologies" }, { "code": null, "e": 28023, "s": 27925, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28062, "s": 28023, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 28084, "s": 28062, "text": "Node.js Export Module" }, { "code": null, "e": 28154, "s": 28084, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 28181, "s": 28154, "text": "Mongoose Populate() Method" }, { "code": null, "e": 28206, "s": 28181, "text": "Mongoose find() Function" }, { "code": null, "e": 28246, "s": 28206, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28291, "s": 28246, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28334, "s": 28291, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28396, "s": 28334, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Powershell - Create CSV File
New-Item cmdlet is used to create a csv file and Set-Content cmdlet to put content into it. In this example, we're creating a new csv file named test.csv Type the following command in PowerShell ISE Console New-Item D:\temp\test\test.csv -ItemType File You can see the test.csv created in D:\temp\test directory. In this example, we're adding content to test.csv. Type the following command in PowerShell ISE Console Set-Content D:\temp\test\test.csv 'Mahesh,Suresh,Ramesh' In this example, we're reading content of test.csv. Get-Content D:\temp\test\test.csv You can see following output in PowerShell console. Mahesh,Suresh,Ramesh 15 Lectures 3.5 hours Fabrice Chrzanowski 35 Lectures 2.5 hours Vijay Saini 145 Lectures 12.5 hours Fettah Ben Print Add Notes Bookmark this page
[ { "code": null, "e": 2126, "s": 2034, "text": "New-Item cmdlet is used to create a csv file and Set-Content cmdlet to put content into it." }, { "code": null, "e": 2188, "s": 2126, "text": "In this example, we're creating a new csv file named test.csv" }, { "code": null, "e": 2241, "s": 2188, "text": "Type the following command in PowerShell ISE Console" }, { "code": null, "e": 2287, "s": 2241, "text": "New-Item D:\\temp\\test\\test.csv -ItemType File" }, { "code": null, "e": 2347, "s": 2287, "text": "You can see the test.csv created in D:\\temp\\test directory." }, { "code": null, "e": 2398, "s": 2347, "text": "In this example, we're adding content to test.csv." }, { "code": null, "e": 2451, "s": 2398, "text": "Type the following command in PowerShell ISE Console" }, { "code": null, "e": 2508, "s": 2451, "text": "Set-Content D:\\temp\\test\\test.csv 'Mahesh,Suresh,Ramesh'" }, { "code": null, "e": 2560, "s": 2508, "text": "In this example, we're reading content of test.csv." }, { "code": null, "e": 2595, "s": 2560, "text": "Get-Content D:\\temp\\test\\test.csv\n" }, { "code": null, "e": 2647, "s": 2595, "text": "You can see following output in PowerShell console." }, { "code": null, "e": 2669, "s": 2647, "text": "Mahesh,Suresh,Ramesh\n" }, { "code": null, "e": 2704, "s": 2669, "text": "\n 15 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2725, "s": 2704, "text": " Fabrice Chrzanowski" }, { "code": null, "e": 2760, "s": 2725, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2773, "s": 2760, "text": " Vijay Saini" }, { "code": null, "e": 2810, "s": 2773, "text": "\n 145 Lectures \n 12.5 hours \n" }, { "code": null, "e": 2822, "s": 2810, "text": " Fettah Ben" }, { "code": null, "e": 2829, "s": 2822, "text": " Print" }, { "code": null, "e": 2840, "s": 2829, "text": " Add Notes" } ]
Tryit Editor v3.7
Tryit: Set border colors
[]
Analyzing World Stock Indices Performances with Python | by Intan Dea Yutami | Towards Data Science
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. The stock index is a list of selected companies, where its averaged price (or weighted-average) reflects the stock market. Stock indices also may reflect a certain industry or region that they cover. They are also often referred to as a benchmark to measure the performance of funds. The more important part of the stock index than its current price is the performance or price changes to a definitive previous moment, whether it is the day or three months before. In the later part of this article is an introduction in how to evaluate stock indices performances in Python. Data related to stock indices can be retrieved from Yahoo! Finance. In Python, there has been a popular module to retrieve data more easily from Yahoo! Finance. If it has not been installed yet, you can install it in your Jupyter Notebook by typing this chunk of codes, followed by importing the needed libraries/modules for processing. Then, how do we get the stock data? Since this article is to analyze performances of world major indices, the next step to do is to get the list of world major indices from the Yahoo! Finance Website. Now, here is the head/beginning content of the list taken from the website: We can see that for each stock indices, there will be names and symbols in each row. The symbols will be important to retrieve the data. Now, it’s time to collect historical data for these stock indices. To collect historical data per stock index, first, we need to call the Ticker module with the parameter of the symbol. For example, if we want to get the historical data of the S&P 500, we can type: We also need to define the period of data retrieval. Should we get daily data or week data? It has to be inputted in the ‘period’ parameter. The start and end dates also have to be defined. Here, the data will be retrieved daily (‘1d’) and started from 1 January 2020 until 30 September 2020. The end date stated in the parameter will not be included in the retrieved data (so, only retrieving until the day before that) Now it’s time to collect historical data of ALL stock indices. In the previous part, we have successfully collected historical stock data for world major stock indices from January 2010 until 30 September 2020. Now, it’s time to do some pre-processing for the analysis. The first step that I would like to do is to categorize each index by the region. Here is my definition of the region: Now, make a new column for the region. def getRegion(ticker): for k in region_idx.keys(): if ticker in region_idx[k]: return kmsi['region']= msi.ticker.apply(lambda x: getRegion(x)) Since the stock prices are in different currencies, to get a general view of the performance, it would better to view that in the same unit or metric. Now, let’s see the price changes through the decade since 4 January 2010 for each of those indices. The changes will be represented percentage (%). The price change is using the Closing Price (‘Close’) for the day. In the code chunk above, a new function is defined to calculate the price change. Then, for each row in the main dataset, that function is called to output the price change. Now, for an easier process, let’s transform the dataset into tickers as columns, and rows as the price change for each date. Now, the new data frame for price change will look like this: It’s time to plot these price changes. For this part, the plots will be in regions. Seen from the plot above, US-based stock indices have grown rapidly since 2016. NASDAQ stock price has been 5x higher since 2010. The other US-based stock indices such as S&P 500, Russell 2000, and Dow 30 have also multiplied their stock prices but not in the same performance as NASDAQ. Some indices from other regions also have had their prices increased by 1–2.5x maximumly. Nikkei 225 (Japan), S&P/NZX 50 (New Zealand), S&P BSE SENSEX (India), and DAX (Germany) are the most profitable stock indices (if you invested somehow in them or some fund that reflects on them since January 2010) among the indices in their respective region. We also can not leave to mention that all these stock indices were impacted by COVID-19. They all dropped significantly around the beginning of 2020, but generally, most of them have been crawling higher since then. Short to Long Term Price Changes/Returns When we are talking about stocks, usually we compare the current price to the historical prices in some previous months or years before. For this part, we are going to analyze the price changes in the short to long-term period. To be clear and detailed, we compare on the same day but periods before. So, 6M (six months) on 30 September 2020 means the day 6 months before 30 September 2020, which is 30 March 2020. 1Y (one year) on the same date means 30 September 2019, and so on. First, we subset the dataset to only 30 September 2020. Now, to get historical prices, it’s a bit tricky. It can be that the day we want to refer to (past date) was not a business day. In addition to that, business days are not the same in every country. So, to handle that, let’s choose the last business day before that past date. Now, let’s get the price changes in some definitive moments before. Let’s plot the price change/return for those stock indices. Referring to the plot above, all major stock indices performed positively (prices are increasing) in a period of 6 months. On the other hand, for other periods, there is a mix of performances among those indices. For 10 year period, most of the stock indices have been profitable, except for STI Index (but only a slight drop). In conclusion, referring to the same plot, the most consistently profitable stock indices in general are: S&P 500 (USA) Dow 300 (USA) NASDAQ (USA) Nikkei 225 (Japan) Shenzen Component Index (China) S&P/NZX 50 Index Gross (New Zealand) TSEC Weighted Index (Taiwan) Please check the code for further reference in the link below:
[ { "code": null, "e": 472, "s": 172, "text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details." }, { "code": null, "e": 937, "s": 472, "text": "The stock index is a list of selected companies, where its averaged price (or weighted-average) reflects the stock market. Stock indices also may reflect a certain industry or region that they cover. They are also often referred to as a benchmark to measure the performance of funds. The more important part of the stock index than its current price is the performance or price changes to a definitive previous moment, whether it is the day or three months before." }, { "code": null, "e": 1047, "s": 937, "text": "In the later part of this article is an introduction in how to evaluate stock indices performances in Python." }, { "code": null, "e": 1384, "s": 1047, "text": "Data related to stock indices can be retrieved from Yahoo! Finance. In Python, there has been a popular module to retrieve data more easily from Yahoo! Finance. If it has not been installed yet, you can install it in your Jupyter Notebook by typing this chunk of codes, followed by importing the needed libraries/modules for processing." }, { "code": null, "e": 1585, "s": 1384, "text": "Then, how do we get the stock data? Since this article is to analyze performances of world major indices, the next step to do is to get the list of world major indices from the Yahoo! Finance Website." }, { "code": null, "e": 1661, "s": 1585, "text": "Now, here is the head/beginning content of the list taken from the website:" }, { "code": null, "e": 1865, "s": 1661, "text": "We can see that for each stock indices, there will be names and symbols in each row. The symbols will be important to retrieve the data. Now, it’s time to collect historical data for these stock indices." }, { "code": null, "e": 2064, "s": 1865, "text": "To collect historical data per stock index, first, we need to call the Ticker module with the parameter of the symbol. For example, if we want to get the historical data of the S&P 500, we can type:" }, { "code": null, "e": 2254, "s": 2064, "text": "We also need to define the period of data retrieval. Should we get daily data or week data? It has to be inputted in the ‘period’ parameter. The start and end dates also have to be defined." }, { "code": null, "e": 2485, "s": 2254, "text": "Here, the data will be retrieved daily (‘1d’) and started from 1 January 2020 until 30 September 2020. The end date stated in the parameter will not be included in the retrieved data (so, only retrieving until the day before that)" }, { "code": null, "e": 2548, "s": 2485, "text": "Now it’s time to collect historical data of ALL stock indices." }, { "code": null, "e": 2755, "s": 2548, "text": "In the previous part, we have successfully collected historical stock data for world major stock indices from January 2010 until 30 September 2020. Now, it’s time to do some pre-processing for the analysis." }, { "code": null, "e": 2874, "s": 2755, "text": "The first step that I would like to do is to categorize each index by the region. Here is my definition of the region:" }, { "code": null, "e": 2913, "s": 2874, "text": "Now, make a new column for the region." }, { "code": null, "e": 3077, "s": 2913, "text": "def getRegion(ticker): for k in region_idx.keys(): if ticker in region_idx[k]: return kmsi['region']= msi.ticker.apply(lambda x: getRegion(x))" }, { "code": null, "e": 3443, "s": 3077, "text": "Since the stock prices are in different currencies, to get a general view of the performance, it would better to view that in the same unit or metric. Now, let’s see the price changes through the decade since 4 January 2010 for each of those indices. The changes will be represented percentage (%). The price change is using the Closing Price (‘Close’) for the day." }, { "code": null, "e": 3617, "s": 3443, "text": "In the code chunk above, a new function is defined to calculate the price change. Then, for each row in the main dataset, that function is called to output the price change." }, { "code": null, "e": 3742, "s": 3617, "text": "Now, for an easier process, let’s transform the dataset into tickers as columns, and rows as the price change for each date." }, { "code": null, "e": 3804, "s": 3742, "text": "Now, the new data frame for price change will look like this:" }, { "code": null, "e": 3888, "s": 3804, "text": "It’s time to plot these price changes. For this part, the plots will be in regions." }, { "code": null, "e": 4176, "s": 3888, "text": "Seen from the plot above, US-based stock indices have grown rapidly since 2016. NASDAQ stock price has been 5x higher since 2010. The other US-based stock indices such as S&P 500, Russell 2000, and Dow 30 have also multiplied their stock prices but not in the same performance as NASDAQ." }, { "code": null, "e": 4526, "s": 4176, "text": "Some indices from other regions also have had their prices increased by 1–2.5x maximumly. Nikkei 225 (Japan), S&P/NZX 50 (New Zealand), S&P BSE SENSEX (India), and DAX (Germany) are the most profitable stock indices (if you invested somehow in them or some fund that reflects on them since January 2010) among the indices in their respective region." }, { "code": null, "e": 4742, "s": 4526, "text": "We also can not leave to mention that all these stock indices were impacted by COVID-19. They all dropped significantly around the beginning of 2020, but generally, most of them have been crawling higher since then." }, { "code": null, "e": 4783, "s": 4742, "text": "Short to Long Term Price Changes/Returns" }, { "code": null, "e": 5011, "s": 4783, "text": "When we are talking about stocks, usually we compare the current price to the historical prices in some previous months or years before. For this part, we are going to analyze the price changes in the short to long-term period." }, { "code": null, "e": 5265, "s": 5011, "text": "To be clear and detailed, we compare on the same day but periods before. So, 6M (six months) on 30 September 2020 means the day 6 months before 30 September 2020, which is 30 March 2020. 1Y (one year) on the same date means 30 September 2019, and so on." }, { "code": null, "e": 5321, "s": 5265, "text": "First, we subset the dataset to only 30 September 2020." }, { "code": null, "e": 5598, "s": 5321, "text": "Now, to get historical prices, it’s a bit tricky. It can be that the day we want to refer to (past date) was not a business day. In addition to that, business days are not the same in every country. So, to handle that, let’s choose the last business day before that past date." }, { "code": null, "e": 5666, "s": 5598, "text": "Now, let’s get the price changes in some definitive moments before." }, { "code": null, "e": 5726, "s": 5666, "text": "Let’s plot the price change/return for those stock indices." }, { "code": null, "e": 6054, "s": 5726, "text": "Referring to the plot above, all major stock indices performed positively (prices are increasing) in a period of 6 months. On the other hand, for other periods, there is a mix of performances among those indices. For 10 year period, most of the stock indices have been profitable, except for STI Index (but only a slight drop)." }, { "code": null, "e": 6160, "s": 6054, "text": "In conclusion, referring to the same plot, the most consistently profitable stock indices in general are:" }, { "code": null, "e": 6174, "s": 6160, "text": "S&P 500 (USA)" }, { "code": null, "e": 6188, "s": 6174, "text": "Dow 300 (USA)" }, { "code": null, "e": 6201, "s": 6188, "text": "NASDAQ (USA)" }, { "code": null, "e": 6220, "s": 6201, "text": "Nikkei 225 (Japan)" }, { "code": null, "e": 6252, "s": 6220, "text": "Shenzen Component Index (China)" }, { "code": null, "e": 6289, "s": 6252, "text": "S&P/NZX 50 Index Gross (New Zealand)" }, { "code": null, "e": 6318, "s": 6289, "text": "TSEC Weighted Index (Taiwan)" } ]
Inverse Permutation | Practice | GeeksforGeeks
Given an array A of size n of integers in the range from 1 to n, we need to find the inverse permutation of that array. Inverse Permutation is a permutation which you will get by inserting position of an element at the position specified by the element value in the array. For better understanding, consider the following example: Suppose we found element 4 at position 3 in an array, then in reverse permutation, we insert 3 (position of element 4 in the array) in position 4 (element value). Example 1: Input: N = 4 Arr[] = {1, 4, 3, 2} Output: 1 4 3 2 Explanation: For element 1 we insert position of 1 from arr1 i.e 1 at position 1 in arr2. For element 4 in arr1, we insert 2 from arr1 at position 4 in arr2. Similarly, for element 2 in arr1, we insert position of 2 i.e 4 in arr2. Example 2: Input: N = 5 Arr[] = {2, 3, 4, 5, 1} Output: 5 1 2 3 4 Explanation: As index 1 has value 2 so 1 will b placed at index 2, similarly 2 has 3 so 2 will be placed at index 3 similarly 3 has 4 so placed at 4, 4 has 5 so 4 placed at 5 and 5 has 1 so placed at index 1. Your Task: You don't need to read input or print anything. Your task is to complete the function inversePermutation() which takes the array Arr[] and its size N as inputs and returns the vector array after performing inverse permutation on Arr. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 1 ≤ N ≤ 105 1 ≤ A[i] ≤ N Note: Array should contain unique elements and should have all elements from 1 to N. 0 yesbro3 weeks ago public static ArrayList<Integer> inversePermutation (int arr[], int n) { //Complete the function int index = 0; int value = 0; int[] a = new int[n]; ArrayList<Integer> list = new ArrayList<Integer>(n); for(int i=0;i<n;i++){ index = arr[i]; value = i; a[index-1] = value+1; } for(int i=0;i<n;i++){ list.add(a[i]); } return list; } 0 priyaranjandash1 month ago ******java***** class Complete{ // Function for finding maximum and value pair public static ArrayList<Integer> inversePermutation (int arr[], int n) { ArrayList<Integer> list = new ArrayList<Integer>(n); int b[] = new int[n]; for(int i=0;i<n;i++) { int value = arr[i]; b[value-1] = i+1; } for(int i=0;i<n;i++) { list.add(b[i]); } return list; } } 0 dangrio2 months ago vector<int> ansVec(size); for(int i=0;i<size;i++){ ansVec[arr[i]-1] = i+1; } return ansVec; -1 vishwajeetofficial20222 months ago //JAVA SOLUTION class Complete{ // Function for finding maximum and value pair public static ArrayList<Integer> inversePermutation (int arr[], int n) { //Complete the function ArrayList<Integer> aL = new ArrayList<Integer>(); int [] tempArr; if (arr.length > 0 && n > 0) { tempArr = new int[arr.length]; for (int i =0; i < arr.length; i++) { tempArr[arr[i]-1] = i+1; } for (int temp : tempArr) aL.add(temp); } return aL; } } 0 paurushbatish3 months ago vector<int> inversePermutation(int arr[], int size) { vector<int>v(size,0); for(int i = 0;i<size;i++){ v[arr[i]-1] = i+1; } return v; } 0 chrisfaraglia4 months ago class Complete{ public static ArrayList<Integer> inversePermutation (int arr[], int n) { ArrayList<Integer> inverseArr = new ArrayList<Integer>(); int [] tempArr; if (arr.length > 0 && n > 0) { tempArr = new int[arr.length]; for (int i =0; i < arr.length; i++) { tempArr[arr[i]-1] = i+1; } for (int temp : tempArr) inverseArr.add(temp); } return inverseArr; } } 0 patelt92384 months ago // why is it not working vector<int> inversePermutation(int arr[], int size) { vector<int> v; int a[size]; for(int i=0;i<size;i++){ a[arr[i]]=i+1; } for(int i=0;i<size;i++){ v.push_back(a[i]); } return v;} +2 priyankarajpoot2015 months ago Java Solution- class Complete{ // Function for finding maximum and value pair public static ArrayList<Integer> inversePermutation (int arr[], int n) { ArrayList<Integer> list = new ArrayList<>(); int[] a = new int[n+1]; for(int i=0;i<n;i++){ a[arr[i]] = i+1; } for(int i=1;i<=n;i++){ list.add(a[i]); } return list; }} +1 badgujarsachin836 months ago vector<int> inversePermutation(int arr[], int size) { vector<int> v; map<int,int> mp; for(int i=0;i<size;i++){ mp[arr[i]]=i+1; } for(auto it:mp){ v.push_back(it.second); } return v; } -9 rohitvishwakarma18197 months ago successfully tried it without using extra space. But used it to match the return type 😉 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": 734, "s": 238, "text": "Given an array A of size n of integers in the range from 1 to n, we need to find the inverse permutation of that array.\nInverse Permutation is a permutation which you will get by inserting position of an element at the position specified by the element value in the array. For better understanding, consider the following example:\nSuppose we found element 4 at position 3 in an array, then in reverse permutation, we insert 3 (position of element 4 in the array) in position 4 (element value).\n " }, { "code": null, "e": 745, "s": 734, "text": "Example 1:" }, { "code": null, "e": 1026, "s": 745, "text": "Input:\nN = 4\nArr[] = {1, 4, 3, 2}\nOutput:\n1 4 3 2\nExplanation:\nFor element 1 we insert position of 1 from\narr1 i.e 1 at position 1 in arr2. For element\n4 in arr1, we insert 2 from arr1 at position\n4 in arr2. Similarly, for element 2 in arr1,\nwe insert position of 2 i.e 4 in arr2." }, { "code": null, "e": 1038, "s": 1026, "text": "\nExample 2:" }, { "code": null, "e": 1305, "s": 1038, "text": "Input:\nN = 5\nArr[] = {2, 3, 4, 5, 1}\nOutput:\n5 1 2 3 4\nExplanation:\nAs index 1 has value 2 so 1 will b \nplaced at index 2, similarly 2 has\n3 so 2 will be placed at index 3\nsimilarly 3 has 4 so placed at 4,\n4 has 5 so 4 placed at 5 and 5 \nhas 1 so placed at index 1. " }, { "code": null, "e": 1554, "s": 1307, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function inversePermutation() which takes the array Arr[] and its size N as inputs and returns the vector array after performing inverse permutation on Arr." }, { "code": null, "e": 1618, "s": 1556, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1746, "s": 1620, "text": "Constraints:\n1 ≤ N ≤ 105\n1 ≤ A[i] ≤ N\nNote: Array should contain unique elements and should\n have all elements from 1 to N. " }, { "code": null, "e": 1748, "s": 1746, "text": "0" }, { "code": null, "e": 1766, "s": 1748, "text": "yesbro3 weeks ago" }, { "code": null, "e": 2228, "s": 1766, "text": "public static ArrayList<Integer> inversePermutation (int arr[], int n) {\n //Complete the function\n int index = 0;\n int value = 0;\n int[] a = new int[n];\n ArrayList<Integer> list = new ArrayList<Integer>(n);\n for(int i=0;i<n;i++){\n index = arr[i];\n value = i;\n a[index-1] = value+1;\n }\n for(int i=0;i<n;i++){\n list.add(a[i]);\n }\n return list;\n }" }, { "code": null, "e": 2230, "s": 2228, "text": "0" }, { "code": null, "e": 2257, "s": 2230, "text": "priyaranjandash1 month ago" }, { "code": null, "e": 2273, "s": 2257, "text": "******java*****" }, { "code": null, "e": 2664, "s": 2273, "text": "class Complete{ // Function for finding maximum and value pair public static ArrayList<Integer> inversePermutation (int arr[], int n) { ArrayList<Integer> list = new ArrayList<Integer>(n); int b[] = new int[n]; for(int i=0;i<n;i++) { int value = arr[i]; b[value-1] = i+1; } for(int i=0;i<n;i++) { list.add(b[i]); } return list; } }" }, { "code": null, "e": 2666, "s": 2664, "text": "0" }, { "code": null, "e": 2686, "s": 2666, "text": "dangrio2 months ago" }, { "code": null, "e": 2791, "s": 2686, "text": " vector<int> ansVec(size); for(int i=0;i<size;i++){ ansVec[arr[i]-1] = i+1; } return ansVec;" }, { "code": null, "e": 2794, "s": 2791, "text": "-1" }, { "code": null, "e": 2829, "s": 2794, "text": "vishwajeetofficial20222 months ago" }, { "code": null, "e": 3471, "s": 2829, "text": "//JAVA SOLUTION\n\nclass Complete{\n \n \n // Function for finding maximum and value pair\n public static ArrayList<Integer> inversePermutation (int arr[], int n) {\n //Complete the function\n ArrayList<Integer> aL = new ArrayList<Integer>();\n int [] tempArr;\n \n if (arr.length > 0 && n > 0) {\n \n tempArr = new int[arr.length];\n \n for (int i =0; i < arr.length; i++) {\n \n tempArr[arr[i]-1] = i+1;\n }\n \n for (int temp : tempArr)\n aL.add(temp);\n }\n \n return aL;\n }\n \n \n}\n\n\n" }, { "code": null, "e": 3473, "s": 3471, "text": "0" }, { "code": null, "e": 3499, "s": 3473, "text": "paurushbatish3 months ago" }, { "code": null, "e": 3659, "s": 3499, "text": "vector<int> inversePermutation(int arr[], int size) {\n vector<int>v(size,0);\n for(int i = 0;i<size;i++){\n v[arr[i]-1] = i+1;\n }\n return v;\n}" }, { "code": null, "e": 3661, "s": 3659, "text": "0" }, { "code": null, "e": 3687, "s": 3661, "text": "chrisfaraglia4 months ago" }, { "code": null, "e": 4239, "s": 3687, "text": "class Complete{\n \n public static ArrayList<Integer> inversePermutation (int arr[], int n) {\n \n ArrayList<Integer> inverseArr = new ArrayList<Integer>();\n int [] tempArr;\n \n if (arr.length > 0 && n > 0) {\n \n tempArr = new int[arr.length];\n \n for (int i =0; i < arr.length; i++) {\n \n tempArr[arr[i]-1] = i+1;\n }\n \n for (int temp : tempArr)\n inverseArr.add(temp);\n }\n \n return inverseArr;\n }\n}" }, { "code": null, "e": 4241, "s": 4239, "text": "0" }, { "code": null, "e": 4264, "s": 4241, "text": "patelt92384 months ago" }, { "code": null, "e": 4290, "s": 4264, "text": "// why is it not working " }, { "code": null, "e": 4493, "s": 4290, "text": "vector<int> inversePermutation(int arr[], int size) { vector<int> v; int a[size]; for(int i=0;i<size;i++){ a[arr[i]]=i+1; } for(int i=0;i<size;i++){ v.push_back(a[i]); } return v;}" }, { "code": null, "e": 4496, "s": 4493, "text": "+2" }, { "code": null, "e": 4527, "s": 4496, "text": "priyankarajpoot2015 months ago" }, { "code": null, "e": 4542, "s": 4527, "text": "Java Solution-" }, { "code": null, "e": 4913, "s": 4542, "text": "class Complete{ // Function for finding maximum and value pair public static ArrayList<Integer> inversePermutation (int arr[], int n) { ArrayList<Integer> list = new ArrayList<>(); int[] a = new int[n+1]; for(int i=0;i<n;i++){ a[arr[i]] = i+1; } for(int i=1;i<=n;i++){ list.add(a[i]); } return list; }}" }, { "code": null, "e": 4916, "s": 4913, "text": "+1" }, { "code": null, "e": 4945, "s": 4916, "text": "badgujarsachin836 months ago" }, { "code": null, "e": 5173, "s": 4945, "text": "vector<int> inversePermutation(int arr[], int size) {\n vector<int> v;\n map<int,int> mp;\n for(int i=0;i<size;i++){\n mp[arr[i]]=i+1;\n }\n for(auto it:mp){\n v.push_back(it.second);\n }\n return v;\n}" }, { "code": null, "e": 5176, "s": 5173, "text": "-9" }, { "code": null, "e": 5209, "s": 5176, "text": "rohitvishwakarma18197 months ago" }, { "code": null, "e": 5297, "s": 5209, "text": "successfully tried it without using extra space. But used it to match the return type 😉" }, { "code": null, "e": 5443, "s": 5297, "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": 5479, "s": 5443, "text": " Login to access your submissions. " }, { "code": null, "e": 5489, "s": 5479, "text": "\nProblem\n" }, { "code": null, "e": 5499, "s": 5489, "text": "\nContest\n" }, { "code": null, "e": 5562, "s": 5499, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5710, "s": 5562, "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": 5918, "s": 5710, "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": 6024, "s": 5918, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Scikit Learn - Ridge Regression
Ridge regression or Tikhonov regularization is the regularization technique that performs L2 regularization. It modifies the loss function by adding the penalty (shrinkage quantity) equivalent to the square of the magnitude of coefficients. sklearn.linear_model.Ridge is the module used to solve a regression model where loss function is the linear least squares function and regularization is L2. sklearn.linear_model.Ridge is the module used to solve a regression model where loss function is the linear least squares function and regularization is L2. Following table consists the parameters used by Ridge module − alpha − {float, array-like}, shape(n_targets) Alpha is the tuning parameter that decides how much we want to penalize the model. fit_intercept − Boolean This parameter specifies that a constant (bias or intercept) should be added to the decision function. No intercept will be used in calculation, if it will set to false. tol − float, optional, default=1e-4 It represents the precision of the solution. normalize − Boolean, optional, default = False If this parameter is set to True, the regressor X will be normalized before regression. The normalization will be done by subtracting the mean and dividing it by L2 norm. If fit_intercept = False, this parameter will be ignored. copy_X − Boolean, optional, default = True By default, it is true which means X will be copied. But if it is set to false, X may be overwritten. max_iter − int, optional As name suggest, it represents the maximum number of iterations taken for conjugate gradient solvers. solver − str, {‘auto’, ‘svd’, ‘cholesky’, ‘lsqr’, ‘sparse_cg’, ‘sag’, ‘saga’}’ This parameter represents which solver to use in the computational routines. Following are the properties of options under this parameter auto − It let choose the solver automatically based on the type of data. auto − It let choose the solver automatically based on the type of data. svd − In order to calculate the Ridge coefficients, this parameter uses a Singular Value Decomposition of X. svd − In order to calculate the Ridge coefficients, this parameter uses a Singular Value Decomposition of X. cholesky − This parameter uses the standard scipy.linalg.solve() function to get a closed-form solution. cholesky − This parameter uses the standard scipy.linalg.solve() function to get a closed-form solution. lsqr − It is the fastest and uses the dedicated regularized least-squares routine scipy.sparse.linalg.lsqr. lsqr − It is the fastest and uses the dedicated regularized least-squares routine scipy.sparse.linalg.lsqr. sag − It uses iterative process and a Stochastic Average Gradient descent. sag − It uses iterative process and a Stochastic Average Gradient descent. saga − It also uses iterative process and an improved Stochastic Average Gradient descent. saga − It also uses iterative process and an improved Stochastic Average Gradient descent. random_state − int, RandomState instance or None, optional, default = none This parameter represents the seed of the pseudo random number generated which is used while shuffling the data. Following are the options − int − In this case, random_state is the seed used by random number generator. int − In this case, random_state is the seed used by random number generator. RandomState instance − In this case, random_state is the random number generator. RandomState instance − In this case, random_state is the random number generator. None − In this case, the random number generator is the RandonState instance used by np.random. None − In this case, the random number generator is the RandonState instance used by np.random. Followings table consist the attributes used by Ridge module − coef_ − array, shape(n_features,) or (n_target, n_features) This attribute provides the weight vectors. Intercept_ − float | array, shape = (n_targets) It represents the independent term in decision function. n_iter_ − array or None, shape (n_targets) Available for only ‘sag’ and ‘lsqr’ solver, returns the actual number of iterations for each target. Following Python script provides a simple example of implementing Ridge Regression. We are using 15 samples and 10 features. The value of alpha is 0.5 in our case. There are two methods namely fit() and score() used to fit this model and calculate the score respectively. from sklearn.linear_model import Ridge import numpy as np n_samples, n_features = 15, 10 rng = np.random.RandomState(0) y = rng.randn(n_samples) X = rng.randn(n_samples, n_features) rdg = Ridge(alpha = 0.5) rdg.fit(X, y) rdg.score(X,y) 0.76294987 The output shows that the above Ridge Regression model gave the score of around 76 percent. For more accuracy, we can increase the number of samples and features. For the above example, we can get the weight vector with the help of following python script − rdg.coef_ array([ 0.32720254, -0.34503436, -0.2913278 , 0.2693125 , -0.22832508, -0.8635094 , -0.17079403, -0.36288055, -0.17241081, -0.43136046]) Similarly, we can get the value of intercept with the help of following python script − rdg.intercept_ 0.527486 11 Lectures 2 hours PARTHA MAJUMDAR Print Add Notes Bookmark this page
[ { "code": null, "e": 2462, "s": 2221, "text": "Ridge regression or Tikhonov regularization is the regularization technique that performs L2 regularization. It modifies the loss function by adding the penalty (shrinkage quantity) equivalent to the square of the magnitude of coefficients." }, { "code": null, "e": 2619, "s": 2462, "text": "sklearn.linear_model.Ridge is the module used to solve a regression model where loss function is the linear least squares function and regularization is L2." }, { "code": null, "e": 2776, "s": 2619, "text": "sklearn.linear_model.Ridge is the module used to solve a regression model where loss function is the linear least squares function and regularization is L2." }, { "code": null, "e": 2839, "s": 2776, "text": "Following table consists the parameters used by Ridge module −" }, { "code": null, "e": 2885, "s": 2839, "text": "alpha − {float, array-like}, shape(n_targets)" }, { "code": null, "e": 2968, "s": 2885, "text": "Alpha is the tuning parameter that decides how much we want to penalize the model." }, { "code": null, "e": 2992, "s": 2968, "text": "fit_intercept − Boolean" }, { "code": null, "e": 3162, "s": 2992, "text": "This parameter specifies that a constant (bias or intercept) should be added to the decision function. No intercept will be used in calculation, if it will set to false." }, { "code": null, "e": 3198, "s": 3162, "text": "tol − float, optional, default=1e-4" }, { "code": null, "e": 3243, "s": 3198, "text": "It represents the precision of the solution." }, { "code": null, "e": 3290, "s": 3243, "text": "normalize − Boolean, optional, default = False" }, { "code": null, "e": 3519, "s": 3290, "text": "If this parameter is set to True, the regressor X will be normalized before regression. The normalization will be done by subtracting the mean and dividing it by L2 norm. If fit_intercept = False, this parameter will be ignored." }, { "code": null, "e": 3562, "s": 3519, "text": "copy_X − Boolean, optional, default = True" }, { "code": null, "e": 3664, "s": 3562, "text": "By default, it is true which means X will be copied. But if it is set to false, X may be overwritten." }, { "code": null, "e": 3689, "s": 3664, "text": "max_iter − int, optional" }, { "code": null, "e": 3791, "s": 3689, "text": "As name suggest, it represents the maximum number of iterations taken for conjugate gradient solvers." }, { "code": null, "e": 3870, "s": 3791, "text": "solver − str, {‘auto’, ‘svd’, ‘cholesky’, ‘lsqr’, ‘sparse_cg’, ‘sag’, ‘saga’}’" }, { "code": null, "e": 4008, "s": 3870, "text": "This parameter represents which solver to use in the computational routines. Following are the properties of options under this parameter" }, { "code": null, "e": 4081, "s": 4008, "text": "auto − It let choose the solver automatically based on the type of data." }, { "code": null, "e": 4154, "s": 4081, "text": "auto − It let choose the solver automatically based on the type of data." }, { "code": null, "e": 4263, "s": 4154, "text": "svd − In order to calculate the Ridge coefficients, this parameter uses a Singular Value Decomposition of X." }, { "code": null, "e": 4372, "s": 4263, "text": "svd − In order to calculate the Ridge coefficients, this parameter uses a Singular Value Decomposition of X." }, { "code": null, "e": 4477, "s": 4372, "text": "cholesky − This parameter uses the standard scipy.linalg.solve() function to get a closed-form solution." }, { "code": null, "e": 4582, "s": 4477, "text": "cholesky − This parameter uses the standard scipy.linalg.solve() function to get a closed-form solution." }, { "code": null, "e": 4690, "s": 4582, "text": "lsqr − It is the fastest and uses the dedicated regularized least-squares routine scipy.sparse.linalg.lsqr." }, { "code": null, "e": 4798, "s": 4690, "text": "lsqr − It is the fastest and uses the dedicated regularized least-squares routine scipy.sparse.linalg.lsqr." }, { "code": null, "e": 4873, "s": 4798, "text": "sag − It uses iterative process and a Stochastic Average Gradient descent." }, { "code": null, "e": 4948, "s": 4873, "text": "sag − It uses iterative process and a Stochastic Average Gradient descent." }, { "code": null, "e": 5039, "s": 4948, "text": "saga − It also uses iterative process and an improved Stochastic Average Gradient descent." }, { "code": null, "e": 5130, "s": 5039, "text": "saga − It also uses iterative process and an improved Stochastic Average Gradient descent." }, { "code": null, "e": 5205, "s": 5130, "text": "random_state − int, RandomState instance or None, optional, default = none" }, { "code": null, "e": 5346, "s": 5205, "text": "This parameter represents the seed of the pseudo random number generated which is used while shuffling the data. Following are the options −" }, { "code": null, "e": 5424, "s": 5346, "text": "int − In this case, random_state is the seed used by random number generator." }, { "code": null, "e": 5502, "s": 5424, "text": "int − In this case, random_state is the seed used by random number generator." }, { "code": null, "e": 5584, "s": 5502, "text": "RandomState instance − In this case, random_state is the random number generator." }, { "code": null, "e": 5666, "s": 5584, "text": "RandomState instance − In this case, random_state is the random number generator." }, { "code": null, "e": 5762, "s": 5666, "text": "None − In this case, the random number generator is the RandonState instance used by np.random." }, { "code": null, "e": 5858, "s": 5762, "text": "None − In this case, the random number generator is the RandonState instance used by np.random." }, { "code": null, "e": 5921, "s": 5858, "text": "Followings table consist the attributes used by Ridge module −" }, { "code": null, "e": 5981, "s": 5921, "text": "coef_ − array, shape(n_features,) or (n_target, n_features)" }, { "code": null, "e": 6025, "s": 5981, "text": "This attribute provides the weight vectors." }, { "code": null, "e": 6073, "s": 6025, "text": "Intercept_ − float | array, shape = (n_targets)" }, { "code": null, "e": 6130, "s": 6073, "text": "It represents the independent term in decision function." }, { "code": null, "e": 6173, "s": 6130, "text": "n_iter_ − array or None, shape (n_targets)" }, { "code": null, "e": 6274, "s": 6173, "text": "Available for only ‘sag’ and ‘lsqr’ solver, returns the actual number of iterations for each target." }, { "code": null, "e": 6546, "s": 6274, "text": "Following Python script provides a simple example of implementing Ridge Regression. We are using 15 samples and 10 features. The value of alpha is 0.5 in our case. There are two methods namely fit() and score() used to fit this model and calculate the score respectively." }, { "code": null, "e": 6782, "s": 6546, "text": "from sklearn.linear_model import Ridge\nimport numpy as np\nn_samples, n_features = 15, 10\nrng = np.random.RandomState(0)\ny = rng.randn(n_samples)\nX = rng.randn(n_samples, n_features)\nrdg = Ridge(alpha = 0.5)\nrdg.fit(X, y)\nrdg.score(X,y)" }, { "code": null, "e": 6794, "s": 6782, "text": "0.76294987\n" }, { "code": null, "e": 6957, "s": 6794, "text": "The output shows that the above Ridge Regression model gave the score of around 76 percent. For more accuracy, we can increase the number of samples and features." }, { "code": null, "e": 7052, "s": 6957, "text": "For the above example, we can get the weight vector with the help of following python script −" }, { "code": null, "e": 7062, "s": 7052, "text": "rdg.coef_" }, { "code": null, "e": 7203, "s": 7062, "text": "array([ 0.32720254, -0.34503436, -0.2913278 , 0.2693125 , -0.22832508,\n -0.8635094 , -0.17079403, -0.36288055, -0.17241081, -0.43136046])\n" }, { "code": null, "e": 7291, "s": 7203, "text": "Similarly, we can get the value of intercept with the help of following python script −" }, { "code": null, "e": 7306, "s": 7291, "text": "rdg.intercept_" }, { "code": null, "e": 7316, "s": 7306, "text": "0.527486\n" }, { "code": null, "e": 7349, "s": 7316, "text": "\n 11 Lectures \n 2 hours \n" }, { "code": null, "e": 7366, "s": 7349, "text": " PARTHA MAJUMDAR" }, { "code": null, "e": 7373, "s": 7366, "text": " Print" }, { "code": null, "e": 7384, "s": 7373, "text": " Add Notes" } ]
How to aggregate two collections where a field from one collection is greater than the other in MongoDB?
For this, you can use $lookup. Let us create a collection with documents − > db.demo446.insert([ ... { "ProductName": "Product1", "ProductPrice": 60 }, ... { "ProductName": "Product2", "ProductPrice": 90 } ... ]) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 2, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) Display all documents from a collection with the help of find() method − > db.demo446.find(); This will produce the following output − { "_id" : ObjectId("5e790766bbc41e36cc3caec3"), "ProductName" : "Product1", "ProductPrice" : 60 } { "_id" : ObjectId("5e790766bbc41e36cc3caec4"), "ProductName" : "Product2", "ProductPrice" : 90 } Following is the query to create second collection with documents − > db.demo447.insert([ ... ... { "ProductName": "Product1", "ProductPrice": 40 }, ... { "ProductName": "Product2", "ProductPrice": 70 } ... ]) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 2, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) Display all documents from a collection with the help of find() method − > db.demo447.find(); This will produce the following output − { "_id" : ObjectId("5e790789bbc41e36cc3caec5"), "ProductName" : "Product1", "ProductPrice" : 40 } { "_id" : ObjectId("5e790789bbc41e36cc3caec6"), "ProductName" : "Product2", "ProductPrice" : 70 } Following is the query to aggregate two collections where a field from one collection is greater than the other − > var rate = 1; > db.demo446.aggregate([ ... { "$match": { "ProductPrice": { "$exists": true }, "ProductName": { "$exists": true } } }, ... { ... "$lookup": { ... "from": "demo447", ... "localField": "ProductName", ... "foreignField": "ProductName", ... "as": "demo447" ... } ... }, ... { "$unwind": "$demo447" }, ... { ... "$redact": { ... "$cond": [ ... { ... "$gt": [ ... "$ProductPrice", { ... "$add": [ ... { "$multiply": [ "$demo447.ProductPrice",rate ] }, ... 3 ... ] ... } ... ] ... }, ... "$$KEEP", ... "$$PRUNE" ... ] ... } ... } ... ]) This will produce the following output − { "_id" : ObjectId("5e790766bbc41e36cc3caec3"), "ProductName" : "Product1", "ProductPrice" : 60, "demo447" : { "_id" : ObjectId("5e790789bbc41e36cc3caec5"), "ProductName" : "Product1", "ProductPrice" : 40 } } { "_id" : ObjectId("5e790766bbc41e36cc3caec4"), "ProductName" : "Product2", "ProductPrice" : 90, "demo447" : { "_id" : ObjectId("5e790789bbc41e36cc3caec6"), "ProductName" : "Product2", "ProductPrice" : 70 } }
[ { "code": null, "e": 1137, "s": 1062, "text": "For this, you can use $lookup. Let us create a collection with documents −" }, { "code": null, "e": 1475, "s": 1137, "text": "> db.demo446.insert([\n... { \"ProductName\": \"Product1\", \"ProductPrice\": 60 },\n... { \"ProductName\": \"Product2\", \"ProductPrice\": 90 }\n... ])\nBulkWriteResult({\n \"writeErrors\" : [ ],\n \"writeConcernErrors\" : [ ],\n \"nInserted\" : 2,\n \"nUpserted\" : 0,\n \"nMatched\" : 0,\n \"nModified\" : 0,\n \"nRemoved\" : 0,\n \"upserted\" : [ ]\n})" }, { "code": null, "e": 1548, "s": 1475, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1569, "s": 1548, "text": "> db.demo446.find();" }, { "code": null, "e": 1610, "s": 1569, "text": "This will produce the following output −" }, { "code": null, "e": 1806, "s": 1610, "text": "{ \"_id\" : ObjectId(\"5e790766bbc41e36cc3caec3\"), \"ProductName\" : \"Product1\", \"ProductPrice\" : 60 }\n{ \"_id\" : ObjectId(\"5e790766bbc41e36cc3caec4\"), \"ProductName\" : \"Product2\", \"ProductPrice\" : 90 }" }, { "code": null, "e": 1874, "s": 1806, "text": "Following is the query to create second collection with documents −" }, { "code": null, "e": 2216, "s": 1874, "text": "> db.demo447.insert([\n...\n... { \"ProductName\": \"Product1\", \"ProductPrice\": 40 },\n... { \"ProductName\": \"Product2\", \"ProductPrice\": 70 }\n... ])\nBulkWriteResult({\n \"writeErrors\" : [ ],\n \"writeConcernErrors\" : [ ],\n \"nInserted\" : 2,\n \"nUpserted\" : 0,\n \"nMatched\" : 0,\n \"nModified\" : 0,\n \"nRemoved\" : 0,\n \"upserted\" : [ ]\n})" }, { "code": null, "e": 2289, "s": 2216, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 2310, "s": 2289, "text": "> db.demo447.find();" }, { "code": null, "e": 2351, "s": 2310, "text": "This will produce the following output −" }, { "code": null, "e": 2547, "s": 2351, "text": "{ \"_id\" : ObjectId(\"5e790789bbc41e36cc3caec5\"), \"ProductName\" : \"Product1\", \"ProductPrice\" : 40 }\n{ \"_id\" : ObjectId(\"5e790789bbc41e36cc3caec6\"), \"ProductName\" : \"Product2\", \"ProductPrice\" : 70 }" }, { "code": null, "e": 2661, "s": 2547, "text": "Following is the query to aggregate two collections where a field from one collection is greater than the other −" }, { "code": null, "e": 3457, "s": 2661, "text": "> var rate = 1;\n> db.demo446.aggregate([\n... { \"$match\": { \"ProductPrice\": { \"$exists\": true }, \"ProductName\": { \"$exists\": true } } },\n... {\n... \"$lookup\": {\n... \"from\": \"demo447\",\n... \"localField\": \"ProductName\",\n... \"foreignField\": \"ProductName\",\n... \"as\": \"demo447\"\n... }\n... },\n... { \"$unwind\": \"$demo447\" },\n... {\n... \"$redact\": {\n... \"$cond\": [\n... {\n... \"$gt\": [\n... \"$ProductPrice\", {\n... \"$add\": [\n... { \"$multiply\": [ \"$demo447.ProductPrice\",rate ] },\n... 3\n... ]\n... }\n... ]\n... },\n... \"$$KEEP\",\n... \"$$PRUNE\"\n... ]\n... }\n... }\n... ])" }, { "code": null, "e": 3498, "s": 3457, "text": "This will produce the following output −" }, { "code": null, "e": 3916, "s": 3498, "text": "{ \"_id\" : ObjectId(\"5e790766bbc41e36cc3caec3\"), \"ProductName\" : \"Product1\", \"ProductPrice\" : 60, \"demo447\" : { \"_id\" : ObjectId(\"5e790789bbc41e36cc3caec5\"), \"ProductName\" : \"Product1\", \"ProductPrice\" : 40 } }\n{ \"_id\" : ObjectId(\"5e790766bbc41e36cc3caec4\"), \"ProductName\" : \"Product2\", \"ProductPrice\" : 90, \"demo447\" : { \"_id\" : ObjectId(\"5e790789bbc41e36cc3caec6\"), \"ProductName\" : \"Product2\", \"ProductPrice\" : 70 } }" } ]
Common Pipenv Errors and How to Solve Them: Why Won’t it Lock?! | by Edward Krueger | Towards Data Science
By: Edward Krueger and Douglas Franklin. This article is one of many covering Python package and environment management with Pipenv. Here, you’ll learn how to troubleshoot Pipenv installation and locking issues. For more information on Pipenv, or environments, check out this Medium article! Pipenv combines package management and virtual environment control into one tool for installing, removing, tracking, and documenting your dependencies; and to create, use, and manage your virtual environments. Pipenv is essentially pip and virtualenv wrapped together into a single product. When you begin a project with Pipenv, the tool automatically creates a virtual environment, a Pipfile, and a Pipfile.lock. The Pipfile is very similar to a requirements.txt file. When you install a package with pipenv install, the Pipfile is automatically updated with the new dependency. Pipfile won’t lock when it tries to install packages that don’t exist, i.e., typos. For Example: pipenv install panadas Pipenv looks for the package you specify, whether it exists or not. You see the following errors and many more in the terminal when the package does not exist or can’t be found for another reason. For now, we will focus on these two. Locking Failed! Notice that ‘panadas’ is added to the Pipfile’s packages. This typo will be an issue because now our Pipfile contains an error, and anyone who uses this Pipfile will encounter locking and dependency errors. Be aware that the ‘Installation Succeeded’ alert is untrue; there is no Panadas to install. All that s occurred is the addition of ‘panadas’ to the Pipfile. Typos in the Pipfile are the most common reason that locking fails. As long as this typo remains in the Pipfile, installing a package, existent or not, causes the locking to fail. You’ll need to fix the Pipfile in a text editor. I’m using nano. You can use whatever editor you are comfortable with; Sublime, VS Code, Atom, etc. Simply correct Panadas to Pandas then pipenv install. Now let’s look at some other error messages that populated the console when locking failed. Notice the suggestion pipenv install --skip-lock. This ought to be only used in extreme or causal programming circumstances as it bypasses the Pipfile .lock's primary purpose; locking package versions and creating the formula for installing the environment dependencies. The second most common reason locking fails is that we attempt to install a package that is a pre-release version. You can resolve pre-release version conflicts by adding the--pre flag to the installation. pipenv install --pre After this command, your Pipfile has a new variable; allow_prereleases = true. Note that this will allow the installation of any pre-release package into your environment. Now is when pinning specific package versions is useful. Pinning versions is an excellent habit to possess and can prevent dependency issues in the future. Notice in the Pipfile image above under the requires section; you see python_version = 3.7. The Pipfile specifies the Python version here. To build a Pipfile or environment with a specific Python version, use the following syntax. pipenv --python 3 Package versions can be also be specified when needed. pipenv install django=1.11.10 With Pipenv and the Pipfile, you present to others a standardized way to install project dependencies and testing and development requirements. Anyone who has a copy of your Pipfile can recreate your environment with the following command. pipenv install This creates an environment specified by the Pipfile. Be sure the Pipfile is typo-free and that it specifies proper package and Python versions before sharing it! If this wasn’t the pipenv solution you were looking for, check out this Medium article for help with other Pipenv errors!
[ { "code": null, "e": 213, "s": 172, "text": "By: Edward Krueger and Douglas Franklin." }, { "code": null, "e": 464, "s": 213, "text": "This article is one of many covering Python package and environment management with Pipenv. Here, you’ll learn how to troubleshoot Pipenv installation and locking issues. For more information on Pipenv, or environments, check out this Medium article!" }, { "code": null, "e": 755, "s": 464, "text": "Pipenv combines package management and virtual environment control into one tool for installing, removing, tracking, and documenting your dependencies; and to create, use, and manage your virtual environments. Pipenv is essentially pip and virtualenv wrapped together into a single product." }, { "code": null, "e": 1044, "s": 755, "text": "When you begin a project with Pipenv, the tool automatically creates a virtual environment, a Pipfile, and a Pipfile.lock. The Pipfile is very similar to a requirements.txt file. When you install a package with pipenv install, the Pipfile is automatically updated with the new dependency." }, { "code": null, "e": 1128, "s": 1044, "text": "Pipfile won’t lock when it tries to install packages that don’t exist, i.e., typos." }, { "code": null, "e": 1141, "s": 1128, "text": "For Example:" }, { "code": null, "e": 1164, "s": 1141, "text": "pipenv install panadas" }, { "code": null, "e": 1398, "s": 1164, "text": "Pipenv looks for the package you specify, whether it exists or not. You see the following errors and many more in the terminal when the package does not exist or can’t be found for another reason. For now, we will focus on these two." }, { "code": null, "e": 1846, "s": 1398, "text": "Locking Failed! Notice that ‘panadas’ is added to the Pipfile’s packages. This typo will be an issue because now our Pipfile contains an error, and anyone who uses this Pipfile will encounter locking and dependency errors. Be aware that the ‘Installation Succeeded’ alert is untrue; there is no Panadas to install. All that s occurred is the addition of ‘panadas’ to the Pipfile. Typos in the Pipfile are the most common reason that locking fails." }, { "code": null, "e": 2160, "s": 1846, "text": "As long as this typo remains in the Pipfile, installing a package, existent or not, causes the locking to fail. You’ll need to fix the Pipfile in a text editor. I’m using nano. You can use whatever editor you are comfortable with; Sublime, VS Code, Atom, etc. Simply correct Panadas to Pandas then pipenv install." }, { "code": null, "e": 2252, "s": 2160, "text": "Now let’s look at some other error messages that populated the console when locking failed." }, { "code": null, "e": 2523, "s": 2252, "text": "Notice the suggestion pipenv install --skip-lock. This ought to be only used in extreme or causal programming circumstances as it bypasses the Pipfile .lock's primary purpose; locking package versions and creating the formula for installing the environment dependencies." }, { "code": null, "e": 2729, "s": 2523, "text": "The second most common reason locking fails is that we attempt to install a package that is a pre-release version. You can resolve pre-release version conflicts by adding the--pre flag to the installation." }, { "code": null, "e": 2750, "s": 2729, "text": "pipenv install --pre" }, { "code": null, "e": 3078, "s": 2750, "text": "After this command, your Pipfile has a new variable; allow_prereleases = true. Note that this will allow the installation of any pre-release package into your environment. Now is when pinning specific package versions is useful. Pinning versions is an excellent habit to possess and can prevent dependency issues in the future." }, { "code": null, "e": 3217, "s": 3078, "text": "Notice in the Pipfile image above under the requires section; you see python_version = 3.7. The Pipfile specifies the Python version here." }, { "code": null, "e": 3309, "s": 3217, "text": "To build a Pipfile or environment with a specific Python version, use the following syntax." }, { "code": null, "e": 3327, "s": 3309, "text": "pipenv --python 3" }, { "code": null, "e": 3382, "s": 3327, "text": "Package versions can be also be specified when needed." }, { "code": null, "e": 3412, "s": 3382, "text": "pipenv install django=1.11.10" }, { "code": null, "e": 3652, "s": 3412, "text": "With Pipenv and the Pipfile, you present to others a standardized way to install project dependencies and testing and development requirements. Anyone who has a copy of your Pipfile can recreate your environment with the following command." }, { "code": null, "e": 3667, "s": 3652, "text": "pipenv install" }, { "code": null, "e": 3830, "s": 3667, "text": "This creates an environment specified by the Pipfile. Be sure the Pipfile is typo-free and that it specifies proper package and Python versions before sharing it!" } ]
VBA - Erase Function
The Erase Function is used to reset the values of fixed size arrays and free the memory of the dynamic arrays. It behaves depending upon the type of the arrays. Erase ArrayName Fixed numeric array, each element in an array is reset to Zero. Fixed string array, each element in an array is reset to Zero length " ". Array of objects, each element in an array is reset to special value Nothing. Add a button and add the following function. Private Sub Constant_demo_Click() Dim NumArray(3) NumArray(0) = "VBScript" NumArray(1) = 1.05 NumArray(2) = 25 NumArray(3) = #23/04/2013# Dim DynamicArray() ReDim DynamicArray(9) ' Allocate storage space. Erase NumArray ' Each element is reinitialized. Erase DynamicArray ' Free memory used by array. ' All values would be erased. msgbox("The value at Zeroth index of NumArray is " & NumArray(0)) msgbox("The value at First index of NumArray is " & NumArray(1)) msgbox("The value at Second index of NumArray is " & NumArray(2)) msgbox("The value at Third index of NumArray is " & NumArray(3)) End Sub When you execute the above function, it produces the following output. The value at Zeroth index of NumArray is The value at First index of NumArray is The value at Second index of NumArray is The value at Third index of NumArray is 101 Lectures 6 hours Pavan Lalwani 41 Lectures 3 hours Arnold Higuit 80 Lectures 5.5 hours Prashant Panchal 25 Lectures 2 hours Prashant Panchal 26 Lectures 2 hours Arnold Higuit 92 Lectures 10.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2096, "s": 1935, "text": "The Erase Function is used to reset the values of fixed size arrays and free the memory of the dynamic arrays. It behaves depending upon the type of the arrays." }, { "code": null, "e": 2113, "s": 2096, "text": "Erase ArrayName\n" }, { "code": null, "e": 2177, "s": 2113, "text": "Fixed numeric array, each element in an array is reset to Zero." }, { "code": null, "e": 2251, "s": 2177, "text": "Fixed string array, each element in an array is reset to Zero length \" \"." }, { "code": null, "e": 2329, "s": 2251, "text": "Array of objects, each element in an array is reset to special value Nothing." }, { "code": null, "e": 2374, "s": 2329, "text": "Add a button and add the following function." }, { "code": null, "e": 3042, "s": 2374, "text": "Private Sub Constant_demo_Click()\n Dim NumArray(3)\n NumArray(0) = \"VBScript\"\n NumArray(1) = 1.05\n NumArray(2) = 25\n NumArray(3) = #23/04/2013#\n \n Dim DynamicArray()\n ReDim DynamicArray(9) ' Allocate storage space.\n \n Erase NumArray ' Each element is reinitialized.\n Erase DynamicArray ' Free memory used by array.\n \n ' All values would be erased.\n msgbox(\"The value at Zeroth index of NumArray is \" & NumArray(0))\n msgbox(\"The value at First index of NumArray is \" & NumArray(1))\n msgbox(\"The value at Second index of NumArray is \" & NumArray(2))\n msgbox(\"The value at Third index of NumArray is \" & NumArray(3))\nEnd Sub" }, { "code": null, "e": 3113, "s": 3042, "text": "When you execute the above function, it produces the following output." }, { "code": null, "e": 3280, "s": 3113, "text": "The value at Zeroth index of NumArray is \nThe value at First index of NumArray is \nThe value at Second index of NumArray is \nThe value at Third index of NumArray is \n" }, { "code": null, "e": 3314, "s": 3280, "text": "\n 101 Lectures \n 6 hours \n" }, { "code": null, "e": 3329, "s": 3314, "text": " Pavan Lalwani" }, { "code": null, "e": 3362, "s": 3329, "text": "\n 41 Lectures \n 3 hours \n" }, { "code": null, "e": 3377, "s": 3362, "text": " Arnold Higuit" }, { "code": null, "e": 3412, "s": 3377, "text": "\n 80 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3430, "s": 3412, "text": " Prashant Panchal" }, { "code": null, "e": 3463, "s": 3430, "text": "\n 25 Lectures \n 2 hours \n" }, { "code": null, "e": 3481, "s": 3463, "text": " Prashant Panchal" }, { "code": null, "e": 3514, "s": 3481, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 3529, "s": 3514, "text": " Arnold Higuit" }, { "code": null, "e": 3565, "s": 3529, "text": "\n 92 Lectures \n 10.5 hours \n" }, { "code": null, "e": 3593, "s": 3565, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 3600, "s": 3593, "text": " Print" }, { "code": null, "e": 3611, "s": 3600, "text": " Add Notes" } ]
Why Git and Git-LFS is not enough to solve the Machine Learning Reproducibility crisis | by David Herron | Towards Data Science
Some claim the machine learning field is in a crisis due to software tooling that’s insufficient to ensure repeatable processes. The crisis is about difficulty in reproducing results such as machine learning models. The crisis could be solved with better software tools for machine learning practitioners. The reproducibility issue is so important that the annual NeurIPS conference plans to make this a major topic of discussion at NeurIPS 2019. The “Call for Papers” announcement has more information https://medium.com/@NeurIPSConf/call-for-papers-689294418f43 The so-called crisis is because of the difficulty in replicating the work of co-workers or fellow scientists, threatening their ability to build on each other’s work or to share it with clients or to deploy production services. Since machine learning, and other forms of artificial intelligence software, are so widely used across both academic and corporate research, replicability or reproducibility is a critical problem. We might think this can be solved with typical software engineering tools, since machine learning development is similar to regular software engineering. In both cases we generate some sort of compiled software asset for execution on computer hardware hoping to get accurate results. Why can’t we tap into the rich tradition of software tools, and best practices for software quality, to build repeatable processes for machine learning teams? Unfortunately traditional software engineering tools do not fit well with the needs of machine learning researchers. A key issue is the training data. Often this is a large amount of data, such as images, videos, or texts, that are fed into machine learning tools to train an ML model. Often the training data is not under any kind of source control mechanism, if only because systems like Git do not deal well with large data files, and source control management systems designed to generate delta’s for text files do not deal well with changes to large binary files. Any experienced software engineer will tell you that a team without source control will be in a state of barely managed chaos. Changes won’t always be recorded and team members might forget what was done. At the end of the day that means a model trained against the training data cannot be replicated because the training data set will have changed in unknown-able ways. If there is no software system to remember the state of the data set on any given day, then what mechanism is there to remember what happened when? The first response might be to simply use Git-LFS (Git Large File Storage) because it, as the name implies, deals with large files while building on Git. The pitch is that Git-LFS “replaces large files such as audio samples, videos, datasets, and graphics with text pointers inside Git, while storing the file contents on a remote server like GitHub.com or GitHub Enterprise.” One can just imagine a harried machine learning team saying “sounds great, let’s go for it”. It handles multi-gigabyte files, speeds up checkout from remote repositories, and uses the same comfortable workflow. That sure ticks a lot of boxes, doesn’t it? Not so fast, didn’t your manager instruct you to evaluate carefully before jumping in with both feet? Another life lesson to recall is to look both ways before crossing the street. The first thing your evaluation should turn up is that Git-LFS requires an LFS server, and that server is not available through every Git hosting service. The big three (Github, Gitlab and Atlassian) all support Git-LFS, but maybe you have a DIY bone in your body. Instead of using a 3rd party Git hosting service, you might prefer to host your own Git service. Gogs, for example, is a competent Git service you can easily run on your own hardware, but it does not have built-in support for Git-LFS. Depending on your data needs this next could be a killer: Git LFS lets you store files up to 2 GB in size. That is a Github limitation rather than Git-LFS limitation, however all Git-LFS implementations seem to come with various limitations. Gitlab and Atlassian both have their own lists of Git-LFS limitations. Consider this 2GB limit from Github: One of the use-cases in the Git-LFS pitch is storing video files, but isn’t it common for videos to be way beyond 2GB in size? Therefore GIt-LFS on Github is probably unsuitable for machine learning datasets. It’s not just the 2GB file size limit, but Github places such a tight limit on the free tier of Git-LFS use that one must purchase a data plan covering both data and bandwidth usage. An issue related to bandwidth is that when using a hosted Git-LFS solution, your training data is stored in a remote server and must be downloaded over the Internet. The time to download training data is a serious user experience problem. Another issue is the ease of placing data files on a cloud storage system (AWS, GCP, etc) as is often required when to run cloud-based AI software. This is not supported, since the main Git-LFS offerings from the big 3 Git services store your LFS files on their server. There is a DIY Git-LFS server that does store files on AWS S3 at https://github.com/meltingice/git-lfs-s3 But setting up a custom Git-LFS server of course requires additional work. And, what if you need the files to be on GCP instead of AWS infrastructure? Is there a Git-LFS server which stores data on the cloud storage platform of your choice? Is there a Git-LFS server that utilizes a simple SSH server? In other words, GIt-LFS limits your choices of where the data is stored. With Git-LFS your team has better control over the data, because it is now version controlled. Does that mean the problem is solved? Earlier we said the “key issue is the training data”, but that was a lie. Sort of. Yes keeping the data under version control is a big improvement. But is the lack of version control of the data files the entire problem? No. What determines the results of training a model or other activities? The determining factors include the following, and perhaps more: Training data — the image database or whatever data source is used in training the model The scripts used in training the model The libraries used by the training scripts The scripts used in processing data The libraries or other tools used in processing data The operating system and CPU/GPU hardware Production system code Libraries used by production system code Obviously the result of training a model depends on a variety of conditions. Since there are so many variables to this, it is hard to be precise, but the general problem is a lack of what’s now called Configuration Management. Software engineers have come to recognize the importance of being able to specify the precise system configuration used in deploying systems. Humans are an inventive lot, and there are many possible solutions to this “crisis”. Environments like R Studio or Jupyter Notebook offer a kind of interactive Markdown document which can be configured to execute data science or machine learning workflows. This is useful for documenting machine learning work, and specifying which scripts and libraries are used. But these systems do not offer a solution to managing data sets. Likewise, Makefiles and similar workflow scripting tools offer a method to repeatedly execute a series of commands. The executed commands are determined through file-system time stamps. These tools offer no solution for data management. At the other end of the scale are companies like Domino Data Labs or C3 IoT offering hosted platforms for data science and machine learning. Both package together an offering built upon a wide swath of data science tools. In some cases, like C3 IoT, users are coding in a proprietary language and storing their data in a proprietary data store. It can be enticing to use a one-stop-shopping service, but will it offer the needed flexibility? In the rest of this article we’ll discuss DVC. It was designed to closely match Git functionality, to leverage the familiarity most of us have with Git, but with features making it work well for both workflow and data management in the machine learning context. DVC (https://dvc.org) takes on and solves a larger slice of the machine learning reproducibility problem than does Git-LFS or several other potential solutions. It does this by managing the code (scripts and programs), alongside large data files, in a hybrid between DVC and a source code management (SCM) system like Git. In addition DVC manages the workflow required for processing files used in machine learning experiments. The data files and commands-to-execute are described in DVC files which we’ll learn about in the following sections. Finally, with DVC it is easy to store data on many storage systems from the local disk, to an SSH server, or to cloud systems (S3, GCP, etc). Data managed by DVC can be easily shared with others using this storage system. DVC uses a similar command structure to Git. As we see here, just like git push and git pull are used for sharing code and configuration with collaborators, dvc push and dvc pull is used for sharing data. All this is covered in more detail in the coming sections, or if you want to skip right to learning about DVC see the tutorial at https://dvc.org/doc/tutorial. At the core of DVC is a data store (the DVC cache) optimized for storing and versioning large files. The team chooses which files to store in the SCM (like Git) and which to store in DVC. Files managed by DVC are stored such that DVC can maintain multiple versions of each file, and to use file-system links to quickly change which version of each file is being used. Conceptually the SCM (like Git) and DVC both have repositories holding multiple versions of each file. One can check out “version N” and the corresponding files will appear in the working directory, then later check out “version N+1” and the files will change around to match. On the DVC side, this is handled in the DVC cache. Files stored in the cache are indexed by a checksum (MD5 hash) of the content. As the individual files managed by DVC change, their checksum will of course change, and corresponding cache entries are created. The cache holds all instances of each file. For efficiency, DVC uses several linking methods (depending on file system support) to insert files into the workspace without copying. This way DVC can quickly update the working directory when requested. DVC uses what are called “DVC files” to describe both the data files and the workflow steps. Each workspace will have multiple DVC files, with each describing one or more data files with the corresponding checksum, and each describing a command to execute in the workflow. cmd: python src/prepare.py data/data.xmldeps:- md5: b4801c88a83f3bf5024c19a942993a48 path: src/prepare.py- md5: a304afb96060aad90176268345e10355 path: data/data.xmlmd5: c3a73109be6c186b9d72e714bcedaddbouts:- cache: true md5: 6836f797f3924fb46fcfd6b9f6aa6416.dir metric: false path: data/preparedwdir: . This example DVC file comes from the DVC Getting Started example (https://github.com/iterative/example-get-started) and shows the initial step of a workflow. We’ll talk more about workflows in the next section. For now, note that this command has two dependencies, src/prepare.py and data/data.xml, and an output data directory named data/prepared. Everything has an MD5 hash, and as these files change the MD5 hash will change and a new instance of changed data files are stored in the DVC cache. DVC files are checked into the SCM managed (Git) repository. As commits are made to the SCM repository each DVC file is updated (if appropriate) with new checksums of each file. Therefore with DVC one can recreate exactly the data set present for each commit, and the team can exactly recreate each development step of the project. DVC files are roughly similar to the “pointer” files used in Git-LFS. The DVC team recommends using different SCM tags or branches for each experiment. Therefore accessing the data files, and code, and configuration, appropriate to that experiment is as simple as switching branches. The SCM will update the code and configuration files, and DVC will update the data files, automatically. This means there is no more scratching your head trying to remember which data files were used for what experiment. DVC tracks all that for you. The DVC files remember not only the files used in a particular execution stage, but the command that is executed in that stage. Reproducing a machine learning result requires not only using the precise same data files, but the same processing steps and the same code/configuration. Consider a typical step in creating a model, of preparing sample data to use in later steps. You might have a Python script, prepare.py, to perform that split, and you might have input data in an XML file named data/data.xml. $ dvc run -d data/data.xml -d code/prepare.py \ -o data/prepared \ python code/prepare.py This is how we use DVC to record that processing step. The DVC “run” command creates a DVC file based on the command-line options. The -d option defines dependencies, and in this case we see an input file in XML format, and a Python script. The -o option records output files, in this case there is an output data directory listed. Finally, the executed command is a Python script. Hence, we have input data, code and configuration, and output data, all dutifully recorded in the resulting DVC file, which corresponds to the DVC file shown in the previous section. If prepare.py is changed from one commit to the next, the SCM will automatically track the change. Likewise any change to data.xml results in a new instance in the DVC cache, which DVC will automatically track. The resulting data directory will also be tracked by DVC if they change. A DVC file can also simply refer to a file, like so: md5: 99775a801a1553aae41358eafc2759a9outs:- cache: true md5: ce68b98d82545628782c66192c96f2d2 metric: false path: data/Posts.xml.zip persist: falsewdir: .. This results from the “dvc add file” command, which is used when you simply have a data file, and it is not the result of another command. For example in https://dvc.org/doc/tutorial/define-ml-pipeline this is shown, which results in the immediately preceeding DVC file: $ wget -P data https://dvc.org/s3/so/100K/Posts.xml.zip$ dvc add data/Posts.xml.zip The file Posts.xml.zip is then the data source for a sequence of steps shown in the tutorial that derive information from this data. Take a step back and recognize these are individual steps in a larger workflow, or what DVC calls a pipeline. With “dvc add” and “dvc run” you can string together several Stages, each being created with a “dvc run” command, and each being described by a DVC file. For a complete working example, see https://github.com/iterative/example-get-started and https://dvc.org/doc/tutorial This means that each working directory will have several DVC files, one for each stage in the pipeline used in that project. DVC scans the DVC files to build up a Directed Acyclic Graph (DAG) of the commands required to reproduce the output(s) of the pipeline. Each stage is like a mini-Makefile in that DVC executes the command only if the dependencies have changed. It is also different because DVC does not consider only the file-system timestamps, like Make does, but whether the file content has changed, as determined by the checksum in the DVC file versus the current state of the file. Bottom line is that this means there is no more scratching your head trying to remember which version of what script was used for each experiment. DVC tracks all of that for you. A machine learning researcher is probably working with colleagues, and needs to share data and code and configuration. Or the researcher may need to deploy data to remote systems, for example to run software on a cloud computing system (AWS, GCP, etc), which often means uploading data to the corresponding cloud storage service (S3, GCP, etc). The code and configuration side of a DVC workspace is stored in the SCM (like Git). Using normal SCM commands (like “git clone”) one can easily share it with colleagues. But how about sharing the data with colleagues? DVC has the concept of remote storage. A DVC workspace can push data to, or pull data from, remote storage. The remote storage pool can exist on any of the cloud storage platforms (S3, GCP, etc) as well as an SSH server. Therefore to share code, configuration and data with a colleague, you first define a remote storage pool. The configuration file holding remote storage definitions is tracked by the SCM. You next push the SCM repository to a shared server, which carries with it the DVC configuration file. When your colleague clones the repository, they can immediately pull the data from the remote cache. This means your colleagues no longer have to scratch their head wondering how to run your code. They can easily replicate the exact steps, and the exact data, used to produce the results. The key to repeatable results is using good practices, to keep proper versioning of not only their data but the code and configuration files, and to automate processing steps. Successful projects sometimes requires collaboration with colleagues, which is made easier through cloud storage systems. Some jobs require AI software running on cloud computing platforms, requiring data files to be stored on cloud storage platforms. With DVC a machine learning research team can ensure their data, configuration and code are in sync with each other. It is an easy-to-use system which efficiently manages shared data repositories alongside an SCM system (like Git) to store the configuration and code. Back in 2014 Jason Brownlee wrote a checklist he claimed would encourage reproducible machine learning results, by default: https://machinelearningmastery.com/reproducible-machine-learning-results-by-default/ A Practical Taxonomy of Reproducibility for Machine Learning Research — A research paper by staff of Kaggle and the U of Washington http://www.rctatman.com/files/2018-7-14-MLReproducability.pdf A researcher at McGill Univ, Joelle Pineau, has another checklist for Machine Learning reproducibility https://www.cs.mcgill.ca/~jpineau/ReproducibilityChecklist.pdf She made a presentation at the NeurIPS 2018 conference: https://videoken.com/embed/jH0AgVcwIBc (start at about 6 minutes) The 12 Factor Application is a take on reproducibility or reliability of web services https://12factor.net/ A survey of scientists by the journal Nature noted over 50% of scientists agree there is a crisis in reproducing results https://www.nature.com/news/1-500-scientists-lift-the-lid-on-reproducibility-1.19970
[ { "code": null, "e": 353, "s": 47, "text": "Some claim the machine learning field is in a crisis due to software tooling that’s insufficient to ensure repeatable processes. The crisis is about difficulty in reproducing results such as machine learning models. The crisis could be solved with better software tools for machine learning practitioners." }, { "code": null, "e": 611, "s": 353, "text": "The reproducibility issue is so important that the annual NeurIPS conference plans to make this a major topic of discussion at NeurIPS 2019. The “Call for Papers” announcement has more information https://medium.com/@NeurIPSConf/call-for-papers-689294418f43" }, { "code": null, "e": 1036, "s": 611, "text": "The so-called crisis is because of the difficulty in replicating the work of co-workers or fellow scientists, threatening their ability to build on each other’s work or to share it with clients or to deploy production services. Since machine learning, and other forms of artificial intelligence software, are so widely used across both academic and corporate research, replicability or reproducibility is a critical problem." }, { "code": null, "e": 1479, "s": 1036, "text": "We might think this can be solved with typical software engineering tools, since machine learning development is similar to regular software engineering. In both cases we generate some sort of compiled software asset for execution on computer hardware hoping to get accurate results. Why can’t we tap into the rich tradition of software tools, and best practices for software quality, to build repeatable processes for machine learning teams?" }, { "code": null, "e": 1596, "s": 1479, "text": "Unfortunately traditional software engineering tools do not fit well with the needs of machine learning researchers." }, { "code": null, "e": 2253, "s": 1596, "text": "A key issue is the training data. Often this is a large amount of data, such as images, videos, or texts, that are fed into machine learning tools to train an ML model. Often the training data is not under any kind of source control mechanism, if only because systems like Git do not deal well with large data files, and source control management systems designed to generate delta’s for text files do not deal well with changes to large binary files. Any experienced software engineer will tell you that a team without source control will be in a state of barely managed chaos. Changes won’t always be recorded and team members might forget what was done." }, { "code": null, "e": 2567, "s": 2253, "text": "At the end of the day that means a model trained against the training data cannot be replicated because the training data set will have changed in unknown-able ways. If there is no software system to remember the state of the data set on any given day, then what mechanism is there to remember what happened when?" }, { "code": null, "e": 3199, "s": 2567, "text": "The first response might be to simply use Git-LFS (Git Large File Storage) because it, as the name implies, deals with large files while building on Git. The pitch is that Git-LFS “replaces large files such as audio samples, videos, datasets, and graphics with text pointers inside Git, while storing the file contents on a remote server like GitHub.com or GitHub Enterprise.” One can just imagine a harried machine learning team saying “sounds great, let’s go for it”. It handles multi-gigabyte files, speeds up checkout from remote repositories, and uses the same comfortable workflow. That sure ticks a lot of boxes, doesn’t it?" }, { "code": null, "e": 3380, "s": 3199, "text": "Not so fast, didn’t your manager instruct you to evaluate carefully before jumping in with both feet? Another life lesson to recall is to look both ways before crossing the street." }, { "code": null, "e": 3880, "s": 3380, "text": "The first thing your evaluation should turn up is that Git-LFS requires an LFS server, and that server is not available through every Git hosting service. The big three (Github, Gitlab and Atlassian) all support Git-LFS, but maybe you have a DIY bone in your body. Instead of using a 3rd party Git hosting service, you might prefer to host your own Git service. Gogs, for example, is a competent Git service you can easily run on your own hardware, but it does not have built-in support for Git-LFS." }, { "code": null, "e": 4439, "s": 3880, "text": "Depending on your data needs this next could be a killer: Git LFS lets you store files up to 2 GB in size. That is a Github limitation rather than Git-LFS limitation, however all Git-LFS implementations seem to come with various limitations. Gitlab and Atlassian both have their own lists of Git-LFS limitations. Consider this 2GB limit from Github: One of the use-cases in the Git-LFS pitch is storing video files, but isn’t it common for videos to be way beyond 2GB in size? Therefore GIt-LFS on Github is probably unsuitable for machine learning datasets." }, { "code": null, "e": 4622, "s": 4439, "text": "It’s not just the 2GB file size limit, but Github places such a tight limit on the free tier of Git-LFS use that one must purchase a data plan covering both data and bandwidth usage." }, { "code": null, "e": 4861, "s": 4622, "text": "An issue related to bandwidth is that when using a hosted Git-LFS solution, your training data is stored in a remote server and must be downloaded over the Internet. The time to download training data is a serious user experience problem." }, { "code": null, "e": 5612, "s": 4861, "text": "Another issue is the ease of placing data files on a cloud storage system (AWS, GCP, etc) as is often required when to run cloud-based AI software. This is not supported, since the main Git-LFS offerings from the big 3 Git services store your LFS files on their server. There is a DIY Git-LFS server that does store files on AWS S3 at https://github.com/meltingice/git-lfs-s3 But setting up a custom Git-LFS server of course requires additional work. And, what if you need the files to be on GCP instead of AWS infrastructure? Is there a Git-LFS server which stores data on the cloud storage platform of your choice? Is there a Git-LFS server that utilizes a simple SSH server? In other words, GIt-LFS limits your choices of where the data is stored." }, { "code": null, "e": 5745, "s": 5612, "text": "With Git-LFS your team has better control over the data, because it is now version controlled. Does that mean the problem is solved?" }, { "code": null, "e": 5970, "s": 5745, "text": "Earlier we said the “key issue is the training data”, but that was a lie. Sort of. Yes keeping the data under version control is a big improvement. But is the lack of version control of the data files the entire problem? No." }, { "code": null, "e": 6104, "s": 5970, "text": "What determines the results of training a model or other activities? The determining factors include the following, and perhaps more:" }, { "code": null, "e": 6193, "s": 6104, "text": "Training data — the image database or whatever data source is used in training the model" }, { "code": null, "e": 6232, "s": 6193, "text": "The scripts used in training the model" }, { "code": null, "e": 6275, "s": 6232, "text": "The libraries used by the training scripts" }, { "code": null, "e": 6311, "s": 6275, "text": "The scripts used in processing data" }, { "code": null, "e": 6364, "s": 6311, "text": "The libraries or other tools used in processing data" }, { "code": null, "e": 6406, "s": 6364, "text": "The operating system and CPU/GPU hardware" }, { "code": null, "e": 6429, "s": 6406, "text": "Production system code" }, { "code": null, "e": 6470, "s": 6429, "text": "Libraries used by production system code" }, { "code": null, "e": 6839, "s": 6470, "text": "Obviously the result of training a model depends on a variety of conditions. Since there are so many variables to this, it is hard to be precise, but the general problem is a lack of what’s now called Configuration Management. Software engineers have come to recognize the importance of being able to specify the precise system configuration used in deploying systems." }, { "code": null, "e": 6924, "s": 6839, "text": "Humans are an inventive lot, and there are many possible solutions to this “crisis”." }, { "code": null, "e": 7268, "s": 6924, "text": "Environments like R Studio or Jupyter Notebook offer a kind of interactive Markdown document which can be configured to execute data science or machine learning workflows. This is useful for documenting machine learning work, and specifying which scripts and libraries are used. But these systems do not offer a solution to managing data sets." }, { "code": null, "e": 7505, "s": 7268, "text": "Likewise, Makefiles and similar workflow scripting tools offer a method to repeatedly execute a series of commands. The executed commands are determined through file-system time stamps. These tools offer no solution for data management." }, { "code": null, "e": 7947, "s": 7505, "text": "At the other end of the scale are companies like Domino Data Labs or C3 IoT offering hosted platforms for data science and machine learning. Both package together an offering built upon a wide swath of data science tools. In some cases, like C3 IoT, users are coding in a proprietary language and storing their data in a proprietary data store. It can be enticing to use a one-stop-shopping service, but will it offer the needed flexibility?" }, { "code": null, "e": 8209, "s": 7947, "text": "In the rest of this article we’ll discuss DVC. It was designed to closely match Git functionality, to leverage the familiarity most of us have with Git, but with features making it work well for both workflow and data management in the machine learning context." }, { "code": null, "e": 8976, "s": 8209, "text": "DVC (https://dvc.org) takes on and solves a larger slice of the machine learning reproducibility problem than does Git-LFS or several other potential solutions. It does this by managing the code (scripts and programs), alongside large data files, in a hybrid between DVC and a source code management (SCM) system like Git. In addition DVC manages the workflow required for processing files used in machine learning experiments. The data files and commands-to-execute are described in DVC files which we’ll learn about in the following sections. Finally, with DVC it is easy to store data on many storage systems from the local disk, to an SSH server, or to cloud systems (S3, GCP, etc). Data managed by DVC can be easily shared with others using this storage system." }, { "code": null, "e": 9341, "s": 8976, "text": "DVC uses a similar command structure to Git. As we see here, just like git push and git pull are used for sharing code and configuration with collaborators, dvc push and dvc pull is used for sharing data. All this is covered in more detail in the coming sections, or if you want to skip right to learning about DVC see the tutorial at https://dvc.org/doc/tutorial." }, { "code": null, "e": 9709, "s": 9341, "text": "At the core of DVC is a data store (the DVC cache) optimized for storing and versioning large files. The team chooses which files to store in the SCM (like Git) and which to store in DVC. Files managed by DVC are stored such that DVC can maintain multiple versions of each file, and to use file-system links to quickly change which version of each file is being used." }, { "code": null, "e": 9986, "s": 9709, "text": "Conceptually the SCM (like Git) and DVC both have repositories holding multiple versions of each file. One can check out “version N” and the corresponding files will appear in the working directory, then later check out “version N+1” and the files will change around to match." }, { "code": null, "e": 10290, "s": 9986, "text": "On the DVC side, this is handled in the DVC cache. Files stored in the cache are indexed by a checksum (MD5 hash) of the content. As the individual files managed by DVC change, their checksum will of course change, and corresponding cache entries are created. The cache holds all instances of each file." }, { "code": null, "e": 10496, "s": 10290, "text": "For efficiency, DVC uses several linking methods (depending on file system support) to insert files into the workspace without copying. This way DVC can quickly update the working directory when requested." }, { "code": null, "e": 10769, "s": 10496, "text": "DVC uses what are called “DVC files” to describe both the data files and the workflow steps. Each workspace will have multiple DVC files, with each describing one or more data files with the corresponding checksum, and each describing a command to execute in the workflow." }, { "code": null, "e": 11077, "s": 10769, "text": "cmd: python src/prepare.py data/data.xmldeps:- md5: b4801c88a83f3bf5024c19a942993a48 path: src/prepare.py- md5: a304afb96060aad90176268345e10355 path: data/data.xmlmd5: c3a73109be6c186b9d72e714bcedaddbouts:- cache: true md5: 6836f797f3924fb46fcfd6b9f6aa6416.dir metric: false path: data/preparedwdir: ." }, { "code": null, "e": 11575, "s": 11077, "text": "This example DVC file comes from the DVC Getting Started example (https://github.com/iterative/example-get-started) and shows the initial step of a workflow. We’ll talk more about workflows in the next section. For now, note that this command has two dependencies, src/prepare.py and data/data.xml, and an output data directory named data/prepared. Everything has an MD5 hash, and as these files change the MD5 hash will change and a new instance of changed data files are stored in the DVC cache." }, { "code": null, "e": 11907, "s": 11575, "text": "DVC files are checked into the SCM managed (Git) repository. As commits are made to the SCM repository each DVC file is updated (if appropriate) with new checksums of each file. Therefore with DVC one can recreate exactly the data set present for each commit, and the team can exactly recreate each development step of the project." }, { "code": null, "e": 11977, "s": 11907, "text": "DVC files are roughly similar to the “pointer” files used in Git-LFS." }, { "code": null, "e": 12296, "s": 11977, "text": "The DVC team recommends using different SCM tags or branches for each experiment. Therefore accessing the data files, and code, and configuration, appropriate to that experiment is as simple as switching branches. The SCM will update the code and configuration files, and DVC will update the data files, automatically." }, { "code": null, "e": 12441, "s": 12296, "text": "This means there is no more scratching your head trying to remember which data files were used for what experiment. DVC tracks all that for you." }, { "code": null, "e": 12569, "s": 12441, "text": "The DVC files remember not only the files used in a particular execution stage, but the command that is executed in that stage." }, { "code": null, "e": 12949, "s": 12569, "text": "Reproducing a machine learning result requires not only using the precise same data files, but the same processing steps and the same code/configuration. Consider a typical step in creating a model, of preparing sample data to use in later steps. You might have a Python script, prepare.py, to perform that split, and you might have input data in an XML file named data/data.xml." }, { "code": null, "e": 13061, "s": 12949, "text": "$ dvc run -d data/data.xml -d code/prepare.py \\ -o data/prepared \\ python code/prepare.py" }, { "code": null, "e": 13192, "s": 13061, "text": "This is how we use DVC to record that processing step. The DVC “run” command creates a DVC file based on the command-line options." }, { "code": null, "e": 13626, "s": 13192, "text": "The -d option defines dependencies, and in this case we see an input file in XML format, and a Python script. The -o option records output files, in this case there is an output data directory listed. Finally, the executed command is a Python script. Hence, we have input data, code and configuration, and output data, all dutifully recorded in the resulting DVC file, which corresponds to the DVC file shown in the previous section." }, { "code": null, "e": 13910, "s": 13626, "text": "If prepare.py is changed from one commit to the next, the SCM will automatically track the change. Likewise any change to data.xml results in a new instance in the DVC cache, which DVC will automatically track. The resulting data directory will also be tracked by DVC if they change." }, { "code": null, "e": 13963, "s": 13910, "text": "A DVC file can also simply refer to a file, like so:" }, { "code": null, "e": 14123, "s": 13963, "text": "md5: 99775a801a1553aae41358eafc2759a9outs:- cache: true md5: ce68b98d82545628782c66192c96f2d2 metric: false path: data/Posts.xml.zip persist: falsewdir: .." }, { "code": null, "e": 14394, "s": 14123, "text": "This results from the “dvc add file” command, which is used when you simply have a data file, and it is not the result of another command. For example in https://dvc.org/doc/tutorial/define-ml-pipeline this is shown, which results in the immediately preceeding DVC file:" }, { "code": null, "e": 14478, "s": 14394, "text": "$ wget -P data https://dvc.org/s3/so/100K/Posts.xml.zip$ dvc add data/Posts.xml.zip" }, { "code": null, "e": 14611, "s": 14478, "text": "The file Posts.xml.zip is then the data source for a sequence of steps shown in the tutorial that derive information from this data." }, { "code": null, "e": 14993, "s": 14611, "text": "Take a step back and recognize these are individual steps in a larger workflow, or what DVC calls a pipeline. With “dvc add” and “dvc run” you can string together several Stages, each being created with a “dvc run” command, and each being described by a DVC file. For a complete working example, see https://github.com/iterative/example-get-started and https://dvc.org/doc/tutorial" }, { "code": null, "e": 15587, "s": 14993, "text": "This means that each working directory will have several DVC files, one for each stage in the pipeline used in that project. DVC scans the DVC files to build up a Directed Acyclic Graph (DAG) of the commands required to reproduce the output(s) of the pipeline. Each stage is like a mini-Makefile in that DVC executes the command only if the dependencies have changed. It is also different because DVC does not consider only the file-system timestamps, like Make does, but whether the file content has changed, as determined by the checksum in the DVC file versus the current state of the file." }, { "code": null, "e": 15766, "s": 15587, "text": "Bottom line is that this means there is no more scratching your head trying to remember which version of what script was used for each experiment. DVC tracks all of that for you." }, { "code": null, "e": 16111, "s": 15766, "text": "A machine learning researcher is probably working with colleagues, and needs to share data and code and configuration. Or the researcher may need to deploy data to remote systems, for example to run software on a cloud computing system (AWS, GCP, etc), which often means uploading data to the corresponding cloud storage service (S3, GCP, etc)." }, { "code": null, "e": 16329, "s": 16111, "text": "The code and configuration side of a DVC workspace is stored in the SCM (like Git). Using normal SCM commands (like “git clone”) one can easily share it with colleagues. But how about sharing the data with colleagues?" }, { "code": null, "e": 16550, "s": 16329, "text": "DVC has the concept of remote storage. A DVC workspace can push data to, or pull data from, remote storage. The remote storage pool can exist on any of the cloud storage platforms (S3, GCP, etc) as well as an SSH server." }, { "code": null, "e": 16941, "s": 16550, "text": "Therefore to share code, configuration and data with a colleague, you first define a remote storage pool. The configuration file holding remote storage definitions is tracked by the SCM. You next push the SCM repository to a shared server, which carries with it the DVC configuration file. When your colleague clones the repository, they can immediately pull the data from the remote cache." }, { "code": null, "e": 17129, "s": 16941, "text": "This means your colleagues no longer have to scratch their head wondering how to run your code. They can easily replicate the exact steps, and the exact data, used to produce the results." }, { "code": null, "e": 17557, "s": 17129, "text": "The key to repeatable results is using good practices, to keep proper versioning of not only their data but the code and configuration files, and to automate processing steps. Successful projects sometimes requires collaboration with colleagues, which is made easier through cloud storage systems. Some jobs require AI software running on cloud computing platforms, requiring data files to be stored on cloud storage platforms." }, { "code": null, "e": 17825, "s": 17557, "text": "With DVC a machine learning research team can ensure their data, configuration and code are in sync with each other. It is an easy-to-use system which efficiently manages shared data repositories alongside an SCM system (like Git) to store the configuration and code." }, { "code": null, "e": 18034, "s": 17825, "text": "Back in 2014 Jason Brownlee wrote a checklist he claimed would encourage reproducible machine learning results, by default: https://machinelearningmastery.com/reproducible-machine-learning-results-by-default/" }, { "code": null, "e": 18228, "s": 18034, "text": "A Practical Taxonomy of Reproducibility for Machine Learning Research — A research paper by staff of Kaggle and the U of Washington http://www.rctatman.com/files/2018-7-14-MLReproducability.pdf" }, { "code": null, "e": 18394, "s": 18228, "text": "A researcher at McGill Univ, Joelle Pineau, has another checklist for Machine Learning reproducibility https://www.cs.mcgill.ca/~jpineau/ReproducibilityChecklist.pdf" }, { "code": null, "e": 18516, "s": 18394, "text": "She made a presentation at the NeurIPS 2018 conference: https://videoken.com/embed/jH0AgVcwIBc (start at about 6 minutes)" }, { "code": null, "e": 18624, "s": 18516, "text": "The 12 Factor Application is a take on reproducibility or reliability of web services https://12factor.net/" } ]
Apache Solr - Quick Guide
Solr is an open-source search platform which is used to build search applications. It was built on top of Lucene (full text search engine). Solr is enterprise-ready, fast and highly scalable. The applications built using Solr are sophisticated and deliver high performance. It was Yonik Seely who created Solr in 2004 in order to add search capabilities to the company website of CNET Networks. In Jan 2006, it was made an open-source project under Apache Software Foundation. Its latest version, Solr 6.0, was released in 2016 with support for execution of parallel SQL queries. Solr can be used along with Hadoop. As Hadoop handles a large amount of data, Solr helps us in finding the required information from such a large source. Not only search, Solr can also be used for storage purpose. Like other NoSQL databases, it is a non-relational data storage and processing technology. In short, Solr is a scalable, ready to deploy, search/storage engine optimized to search large volumes of text-centric data. Solr is a wrap around Lucene’s Java API. Therefore, using Solr, you can leverage all the features of Lucene. Let us take a look at some of most prominent features of Solr − Restful APIs − To communicate with Solr, it is not mandatory to have Java programming skills. Instead you can use restful services to communicate with it. We enter documents in Solr in file formats like XML, JSON and .CSV and get results in the same file formats. Restful APIs − To communicate with Solr, it is not mandatory to have Java programming skills. Instead you can use restful services to communicate with it. We enter documents in Solr in file formats like XML, JSON and .CSV and get results in the same file formats. Full text search − Solr provides all the capabilities needed for a full text search such as tokens, phrases, spell check, wildcard, and auto-complete. Full text search − Solr provides all the capabilities needed for a full text search such as tokens, phrases, spell check, wildcard, and auto-complete. Enterprise ready − According to the need of the organization, Solr can be deployed in any kind of systems (big or small) such as standalone, distributed, cloud, etc. Enterprise ready − According to the need of the organization, Solr can be deployed in any kind of systems (big or small) such as standalone, distributed, cloud, etc. Flexible and Extensible − By extending the Java classes and configuring accordingly, we can customize the components of Solr easily. Flexible and Extensible − By extending the Java classes and configuring accordingly, we can customize the components of Solr easily. NoSQL database − Solr can also be used as big data scale NOSQL database where we can distribute the search tasks along a cluster. NoSQL database − Solr can also be used as big data scale NOSQL database where we can distribute the search tasks along a cluster. Admin Interface − Solr provides an easy-to-use, user friendly, feature powered, user interface, using which we can perform all the possible tasks such as manage logs, add, delete, update and search documents. Admin Interface − Solr provides an easy-to-use, user friendly, feature powered, user interface, using which we can perform all the possible tasks such as manage logs, add, delete, update and search documents. Highly Scalable − While using Solr with Hadoop, we can scale its capacity by adding replicas. Highly Scalable − While using Solr with Hadoop, we can scale its capacity by adding replicas. Text-Centric and Sorted by Relevance − Solr is mostly used to search text documents and the results are delivered according to the relevance with the user’s query in order. Text-Centric and Sorted by Relevance − Solr is mostly used to search text documents and the results are delivered according to the relevance with the user’s query in order. Unlike Lucene, you don’t need to have Java programming skills while working with Apache Solr. It provides a wonderful ready-to-deploy service to build a search box featuring autocomplete, which Lucene doesn’t provide. Using Solr, we can scale, distribute, and manage index, for large scale (Big Data) applications. Lucene is simple yet powerful Java-based search library. It can be used in any application to add search capability. Lucene is a scalable and high-performance library used to index and search virtually any kind of text. Lucene library provides the core operations which are required by any search application, such as Indexing and Searching. If we have a web portal with a huge volume of data, then we will most probably require a search engine in our portal to extract relevant information from the huge pool of data. Lucene works as the heart of any search application and provides the vital operations pertaining to indexing and searching. A Search Engine refers to a huge database of Internet resources such as webpages, newsgroups, programs, images, etc. It helps to locate information on the World Wide Web. Users can search for information by passing queries into the Search Engine in the form of keywords or phrases. The Search Engine then searches in its database and returns relevant links to the user. Generally, there are three basic components of a search engine as listed below − Web Crawler − Web crawlers are also known as spiders or bots. It is a software component that traverses the web to gather information. Web Crawler − Web crawlers are also known as spiders or bots. It is a software component that traverses the web to gather information. Database − All the information on the Web is stored in databases. They contain a huge volume of web resources. Database − All the information on the Web is stored in databases. They contain a huge volume of web resources. Search Interfaces − This component is an interface between the user and the database. It helps the user to search through the database. Search Interfaces − This component is an interface between the user and the database. It helps the user to search through the database. Any search application is required to perform some or all of the following operations. 1 Acquire Raw Content The very first step of any search application is to collect the target contents on which search is to be conducted. 2 Build the document The next step is to build the document(s) from the raw contents which the search application can understand and interpret easily. 3 Analyze the document Before indexing can start, the document is to be analyzed. 4 Indexing the document Once the documents are built and analyzed, the next step is to index them so that this document can be retrieved based on certain keys, instead of the whole contents of the document. Indexing is similar to the indexes that we have at the end of a book where common words are shown with their page numbers so that these words can be tracked quickly, instead of searching the complete book. 5 User Interface for Search Once a database of indexes is ready, then the application can perform search operations. To help the user make a search, the application must provide a user interface where the user can enter text and initiate the search process 6 Build Query Once the user makes a request to search a text, the application should prepare a query object using that text, which can then be used to inquire the index database to get relevant details. 7 Search Query Using the query object, the index database is checked to get the relevant details and the content documents. 8 Render Results Once the required result is received, the application should decide how to display the results to the user using its User Interface. Take a look at the following illustration. It shows an overall view of how Search Engines function. Apart from these basic operations, search applications can also provide administration-user interface to help the administrators control the level of search based on the user profiles. Analytics of search result is another important and advanced aspect of any search application. In this chapter, we will discuss how to set up Solr in Windows environment. To install Solr on your Windows system, you need to follow the steps given below − Visit the homepage of Apache Solr and click the download button. Visit the homepage of Apache Solr and click the download button. Select one of the mirrors to get an index of Apache Solr. From there download the file named Solr-6.2.0.zip. Select one of the mirrors to get an index of Apache Solr. From there download the file named Solr-6.2.0.zip. Move the file from the downloads folder to the required directory and unzip it. Move the file from the downloads folder to the required directory and unzip it. Suppose you downloaded the Solr fie and extracted it in onto the C drive. In such case, you can start Solr as shown in the following screenshot. To verify the installation, use the following URL in your browser. http://localhost:8983/ If the installation process is successful, then you will get to see the dashboard of the Apache Solr user interface as shown below. We can also communicate with Apache Solr using Java libraries; but before accessing Solr using Java API, you need to set the classpath for those libraries. Set the classpath to Solr libraries in the .bashrc file. Open .bashrc in any of the editors as shown below. $ gedit ~/.bashrc Set classpath for Solr libraries (lib folder in HBase) as shown below. export CLASSPATH = $CLASSPATH://home/hadoop/Solr/lib/* This is to prevent the “class not found” exception while accessing the HBase using Java API. Solr can be used along with Hadoop. As Hadoop handles a large amount of data, Solr helps us in finding the required information from such a large source. In this section, let us understand how you can install Hadoop on your system. Given below are the steps to be followed to download Hadoop onto your system. Step 1 − Go to the homepage of Hadoop. You can use the link − www.hadoop.apache.org/. Click the link Releases, as highlighted in the following screenshot. It will redirect you to the Apache Hadoop Releases page which contains links for mirrors of source and binary files of various versions of Hadoop as follows − Step 2 − Select the latest version of Hadoop (in our tutorial, it is 2.6.4) and click its binary link. It will take you to a page where mirrors for Hadoop binary are available. Click one of these mirrors to download Hadoop. Open Linux terminal and login as super-user. $ su password: Go to the directory where you need to install Hadoop, and save the file there using the link copied earlier, as shown in the following code block. # cd /usr/local # wget http://redrockdigimark.com/apachemirror/hadoop/common/hadoop- 2.6.4/hadoop-2.6.4.tar.gz After downloading Hadoop, extract it using the following commands. # tar zxvf hadoop-2.6.4.tar.gz # mkdir hadoop # mv hadoop-2.6.4/* to hadoop/ # exit Follow the steps given below to install Hadoop in pseudo-distributed mode. You can set the Hadoop environment variables by appending the following commands to ~/.bashrc file. export HADOOP_HOME = /usr/local/hadoop export HADOOP_MAPRED_HOME = $HADOOP_HOME export HADOOP_COMMON_HOME = $HADOOP_HOME export HADOOP_HDFS_HOME = $HADOOP_HOME export YARN_HOME = $HADOOP_HOME export HADOOP_COMMON_LIB_NATIVE_DIR = $HADOOP_HOME/lib/native export PATH = $PATH:$HADOOP_HOME/sbin:$HADOOP_HOME/bin export HADOOP_INSTALL = $HADOOP_HOME Next, apply all the changes into the current running system. $ source ~/.bashrc You can find all the Hadoop configuration files in the location “$HADOOP_HOME/etc/hadoop”. It is required to make changes in those configuration files according to your Hadoop infrastructure. $ cd $HADOOP_HOME/etc/hadoop In order to develop Hadoop programs in Java, you have to reset the Java environment variables in hadoop-env.sh file by replacing JAVA_HOME value with the location of Java in your system. export JAVA_HOME = /usr/local/jdk1.7.0_71 The following are the list of files that you have to edit to configure Hadoop − core-site.xml hdfs-site.xml yarn-site.xml mapred-site.xml core-site.xml The core-site.xml file contains information such as the port number used for Hadoop instance, memory allocated for the file system, memory limit for storing the data, and size of Read/Write buffers. Open the core-site.xml and add the following properties inside the <configuration>, </configuration> tags. <configuration> <property> <name>fs.default.name</name> <value>hdfs://localhost:9000</value> </property> </configuration> hdfs-site.xml The hdfs-site.xml file contains information such as the value of replication data, namenode path, and datanode paths of your local file systems. It means the place where you want to store the Hadoop infrastructure. Let us assume the following data. dfs.replication (data replication value) = 1 (In the below given path /hadoop/ is the user name. hadoopinfra/hdfs/namenode is the directory created by hdfs file system.) namenode path = //home/hadoop/hadoopinfra/hdfs/namenode (hadoopinfra/hdfs/datanode is the directory created by hdfs file system.) datanode path = //home/hadoop/hadoopinfra/hdfs/datanode Open this file and add the following properties inside the <configuration>, </configuration> tags. <configuration> <property> <name>dfs.replication</name> <value>1</value> </property> <property> <name>dfs.name.dir</name> <value>file:///home/hadoop/hadoopinfra/hdfs/namenode</value> </property> <property> <name>dfs.data.dir</name> <value>file:///home/hadoop/hadoopinfra/hdfs/datanode</value> </property> </configuration> Note − In the above file, all the property values are user-defined and you can make changes according to your Hadoop infrastructure. yarn-site.xml This file is used to configure yarn into Hadoop. Open the yarn-site.xml file and add the following properties in between the <configuration>, </configuration> tags in this file. <configuration> <property> <name>yarn.nodemanager.aux-services</name> <value>mapreduce_shuffle</value> </property> </configuration> mapred-site.xml This file is used to specify which MapReduce framework we are using. By default, Hadoop contains a template of yarn-site.xml. First of all, it is required to copy the file from mapred-site,xml.template to mapred-site.xml file using the following command. $ cp mapred-site.xml.template mapred-site.xml Open mapred-site.xml file and add the following properties inside the <configuration>, </configuration> tags. <configuration> <property> <name>mapreduce.framework.name</name> <value>yarn</value> </property> </configuration> The following steps are used to verify the Hadoop installation. Set up the namenode using the command "hdfs namenode –format" as follows. $ cd ~ $ hdfs namenode -format The expected result is as follows. 10/24/14 21:30:55 INFO namenode.NameNode: STARTUP_MSG: /************************************************************ STARTUP_MSG: Starting NameNode STARTUP_MSG: host = localhost/192.168.1.11 STARTUP_MSG: args = [-format] STARTUP_MSG: version = 2.6.4 ... ... 10/24/14 21:30:56 INFO common.Storage: Storage directory /home/hadoop/hadoopinfra/hdfs/namenode has been successfully formatted. 10/24/14 21:30:56 INFO namenode.NNStorageRetentionManager: Going to retain 1 images with txid >= 0 10/24/14 21:30:56 INFO util.ExitUtil: Exiting with status 0 10/24/14 21:30:56 INFO namenode.NameNode: SHUTDOWN_MSG: /************************************************************ SHUTDOWN_MSG: Shutting down NameNode at localhost/192.168.1.11 ************************************************************/ The following command is used to start the Hadoop dfs. Executing this command will start your Hadoop file system. $ start-dfs.sh The expected output is as follows − 10/24/14 21:37:56 Starting namenodes on [localhost] localhost: starting namenode, logging to /home/hadoop/hadoop-2.6.4/logs/hadoop- hadoop-namenode-localhost.out localhost: starting datanode, logging to /home/hadoop/hadoop-2.6.4/logs/hadoop- hadoop-datanode-localhost.out Starting secondary namenodes [0.0.0.0] The following command is used to start the Yarn script. Executing this command will start your Yarn demons. $ start-yarn.sh The expected output as follows − starting yarn daemons starting resourcemanager, logging to /home/hadoop/hadoop-2.6.4/logs/yarn- hadoop-resourcemanager-localhost.out localhost: starting nodemanager, logging to /home/hadoop/hadoop- 2.6.4/logs/yarn-hadoop-nodemanager-localhost.out The default port number to access Hadoop is 50070. Use the following URL to get Hadoop services on browser. http://localhost:50070/ Follow the steps given below to download and install Solr. Open the homepage of Apache Solr by clicking the following link − https://lucene.apache.org/solr/ Click the download button (highlighted in the above screenshot). On clicking, you will be redirected to the page where you have various mirrors of Apache Solr. Select a mirror and click on it, which will redirect you to a page where you can download the source and binary files of Apache Solr, as shown in the following screenshot. On clicking, a folder named Solr-6.2.0.tqz will be downloaded in the downloads folder of your system. Extract the contents of the downloaded folder. Create a folder named Solr in the Hadoop home directory and move the contents of the extracted folder to it, as shown below. $ mkdir Solr $ cd Downloads $ mv Solr-6.2.0 /home/Hadoop/ Browse through the bin folder of Solr Home directory and verify the installation using the version option, as shown in the following code block. $ cd bin/ $ ./Solr version 6.2.0 Open the .bashrc file using the following command − [Hadoop@localhost ~]$ source ~/.bashrc Now set the home and path directories for Apache Solr as follows − export SOLR_HOME = /home/Hadoop/Solr export PATH = $PATH:/$SOLR_HOME/bin/ Open the terminal and execute the following command − [Hadoop@localhost Solr]$ source ~/.bashrc Now, you can execute the commands of Solr from any directory. In this chapter, we will discuss the architecture of Apache Solr. The following illustration shows a block diagram of the architecture of Apache Solr. Following are the major building blocks (components) of Apache Solr − Request Handler − The requests we send to Apache Solr are processed by these request handlers. The requests might be query requests or index update requests. Based on our requirement, we need to select the request handler. To pass a request to Solr, we will generally map the handler to a certain URI end-point and the specified request will be served by it. Request Handler − The requests we send to Apache Solr are processed by these request handlers. The requests might be query requests or index update requests. Based on our requirement, we need to select the request handler. To pass a request to Solr, we will generally map the handler to a certain URI end-point and the specified request will be served by it. Search Component − A search component is a type (feature) of search provided in Apache Solr. It might be spell checking, query, faceting, hit highlighting, etc. These search components are registered as search handlers. Multiple components can be registered to a search handler. Search Component − A search component is a type (feature) of search provided in Apache Solr. It might be spell checking, query, faceting, hit highlighting, etc. These search components are registered as search handlers. Multiple components can be registered to a search handler. Query Parser − The Apache Solr query parser parses the queries that we pass to Solr and verifies the queries for syntactical errors. After parsing the queries, it translates them to a format which Lucene understands. Query Parser − The Apache Solr query parser parses the queries that we pass to Solr and verifies the queries for syntactical errors. After parsing the queries, it translates them to a format which Lucene understands. Response Writer − A response writer in Apache Solr is the component which generates the formatted output for the user queries. Solr supports response formats such as XML, JSON, CSV, etc. We have different response writers for each type of response. Response Writer − A response writer in Apache Solr is the component which generates the formatted output for the user queries. Solr supports response formats such as XML, JSON, CSV, etc. We have different response writers for each type of response. Analyzer/tokenizer − Lucene recognizes data in the form of tokens. Apache Solr analyzes the content, divides it into tokens, and passes these tokens to Lucene. An analyzer in Apache Solr examines the text of fields and generates a token stream. A tokenizer breaks the token stream prepared by the analyzer into tokens. Analyzer/tokenizer − Lucene recognizes data in the form of tokens. Apache Solr analyzes the content, divides it into tokens, and passes these tokens to Lucene. An analyzer in Apache Solr examines the text of fields and generates a token stream. A tokenizer breaks the token stream prepared by the analyzer into tokens. Update Request Processor − Whenever we send an update request to Apache Solr, the request is run through a set of plugins (signature, logging, indexing), collectively known as update request processor. This processor is responsible for modifications such as dropping a field, adding a field, etc. Update Request Processor − Whenever we send an update request to Apache Solr, the request is run through a set of plugins (signature, logging, indexing), collectively known as update request processor. This processor is responsible for modifications such as dropping a field, adding a field, etc. In this chapter, we will try to understand the real meaning of some of the terms that are frequently used while working on Solr. The following is a list of general terms that are used across all types of Solr setups − Instance − Just like a tomcat instance or a jetty instance, this term refers to the application server, which runs inside a JVM. The home directory of Solr provides reference to each of these Solr instances, in which one or more cores can be configured to run in each instance. Instance − Just like a tomcat instance or a jetty instance, this term refers to the application server, which runs inside a JVM. The home directory of Solr provides reference to each of these Solr instances, in which one or more cores can be configured to run in each instance. Core − While running multiple indexes in your application, you can have multiple cores in each instance, instead of multiple instances each having one core. Core − While running multiple indexes in your application, you can have multiple cores in each instance, instead of multiple instances each having one core. Home − The term $SOLR_HOME refers to the home directory which has all the information regarding the cores and their indexes, configurations, and dependencies. Home − The term $SOLR_HOME refers to the home directory which has all the information regarding the cores and their indexes, configurations, and dependencies. Shard − In distributed environments, the data is partitioned between multiple Solr instances, where each chunk of data can be called as a Shard. It contains a subset of the whole index. Shard − In distributed environments, the data is partitioned between multiple Solr instances, where each chunk of data can be called as a Shard. It contains a subset of the whole index. In an earlier chapter, we discussed how to install Apache Solr in standalone mode. Note that we can also install Solr in distributed mode (cloud environment) where Solr is installed in a master-slave pattern. In distributed mode, the index is created on the master server and it is replicated to one or more slave servers. The key terms associated with Solr Cloud are as follows − Node − In Solr cloud, each single instance of Solr is regarded as a node. Node − In Solr cloud, each single instance of Solr is regarded as a node. Cluster − All the nodes of the environment combined together make a cluster. Cluster − All the nodes of the environment combined together make a cluster. Collection − A cluster has a logical index that is known as a collection. Collection − A cluster has a logical index that is known as a collection. Shard − A shard is portion of the collection which has one or more replicas of the index. Shard − A shard is portion of the collection which has one or more replicas of the index. Replica − In Solr Core, a copy of shard that runs in a node is known as a replica. Replica − In Solr Core, a copy of shard that runs in a node is known as a replica. Leader − It is also a replica of shard, which distributes the requests of the Solr Cloud to the remaining replicas. Leader − It is also a replica of shard, which distributes the requests of the Solr Cloud to the remaining replicas. Zookeeper − It is an Apache project that Solr Cloud uses for centralized configuration and coordination, to manage the cluster and to elect a leader. Zookeeper − It is an Apache project that Solr Cloud uses for centralized configuration and coordination, to manage the cluster and to elect a leader. The main configuration files in Apache Solr are as follows − Solr.xml − It is the file in the $SOLR_HOME directory that contains Solr Cloud related information. To load the cores, Solr refers to this file, which helps in identifying them. Solr.xml − It is the file in the $SOLR_HOME directory that contains Solr Cloud related information. To load the cores, Solr refers to this file, which helps in identifying them. Solrconfig.xml − This file contains the definitions and core-specific configurations related to request handling and response formatting, along with indexing, configuring, managing memory and making commits. Solrconfig.xml − This file contains the definitions and core-specific configurations related to request handling and response formatting, along with indexing, configuring, managing memory and making commits. Schema.xml − This file contains the whole schema along with the fields and field types. Schema.xml − This file contains the whole schema along with the fields and field types. Core.properties − This file contains the configurations specific to the core. It is referred for core discovery, as it contains the name of the core and path of the data directory. It can be used in any directory, which will then be treated as the core directory. Core.properties − This file contains the configurations specific to the core. It is referred for core discovery, as it contains the name of the core and path of the data directory. It can be used in any directory, which will then be treated as the core directory. After installing Solr, browse to the bin folder in Solr home directory and start Solr using the following command. [Hadoop@localhost ~]$ cd [Hadoop@localhost ~]$ cd Solr/ [Hadoop@localhost Solr]$ cd bin/ [Hadoop@localhost bin]$ ./Solr start This command starts Solr in the background, listening on port 8983 by displaying the following message. Waiting up to 30 seconds to see Solr running on port 8983 [\] Started Solr server on port 8983 (pid = 6035). Happy searching! If you start Solr using the start command, then Solr will start in the background. Instead, you can start Solr in the foreground using the –f option. [Hadoop@localhost bin]$ ./Solr start –f 5823 INFO (coreLoadExecutor-6-thread-2) [ ] o.a.s.c.SolrResourceLoader Adding 'file:/home/Hadoop/Solr/contrib/extraction/lib/xmlbeans-2.6.0.jar' to classloader 5823 INFO (coreLoadExecutor-6-thread-2) [ ] o.a.s.c.SolrResourceLoader Adding 'file:/home/Hadoop/Solr/dist/Solr-cell-6.2.0.jar' to classloader 5823 INFO (coreLoadExecutor-6-thread-2) [ ] o.a.s.c.SolrResourceLoader Adding 'file:/home/Hadoop/Solr/contrib/clustering/lib/carrot2-guava-18.0.jar' to classloader 5823 INFO (coreLoadExecutor-6-thread-2) [ ] o.a.s.c.SolrResourceLoader Adding 'file:/home/Hadoop/Solr/contrib/clustering/lib/attributes-binder1.3.1.jar' to classloader 5823 INFO (coreLoadExecutor-6-thread-2) [ ] o.a.s.c.SolrResourceLoader Adding 'file:/home/Hadoop/Solr/contrib/clustering/lib/simple-xml-2.7.1.jar' to classloader ....................................................................................................................................................................................................................................... ............................................................................................................................................................................................................................ 12901 INFO (coreLoadExecutor-6-thread-1) [ x:Solr_sample] o.a.s.u.UpdateLog Took 24.0ms to seed version buckets with highest version 1546058939881226240 12902 INFO (coreLoadExecutor-6-thread-1) [ x:Solr_sample] o.a.s.c.CoreContainer registering core: Solr_sample 12904 INFO (coreLoadExecutor-6-thread-2) [ x:my_core] o.a.s.u.UpdateLog Took 16.0ms to seed version buckets with highest version 1546058939894857728 12904 INFO (coreLoadExecutor-6-thread-2) [ x:my_core] o.a.s.c.CoreContainer registering core: my_core Using –p option of the start command, we can start Solr in another port, as shown in the following code block. [Hadoop@localhost bin]$ ./Solr start -p 8984 Waiting up to 30 seconds to see Solr running on port 8984 [-] Started Solr server on port 8984 (pid = 10137). Happy searching! You can stop Solr using the stop command. $ ./Solr stop This command stops Solr, displaying a message as shown below. Sending stop command to Solr running on port 8983 ... waiting 5 seconds to allow Jetty process 6035 to stop gracefully. The restart command of Solr stops Solr for 5 seconds and starts it again. You can restart Solr using the following command − ./Solr restart This command restarts Solr, displaying the following message − Sending stop command to Solr running on port 8983 ... waiting 5 seconds to allow Jetty process 6671 to stop gracefully. Waiting up to 30 seconds to see Solr running on port 8983 [|] [/] Started Solr server on port 8983 (pid = 6906). Happy searching! The help command of Solr can be used to check the usage of the Solr prompt and its options. [Hadoop@localhost bin]$ ./Solr -help Usage: Solr COMMAND OPTIONS where COMMAND is one of: start, stop, restart, status, healthcheck, create, create_core, create_collection, delete, version, zk Standalone server example (start Solr running in the background on port 8984): ./Solr start -p 8984 SolrCloud example (start Solr running in SolrCloud mode using localhost:2181 to connect to Zookeeper, with 1g max heap size and remote Java debug options enabled): ./Solr start -c -m 1g -z localhost:2181 -a "-Xdebug - Xrunjdwp:transport = dt_socket,server = y,suspend = n,address = 1044" Pass -help after any COMMAND to see command-specific usage information, such as: ./Solr start -help or ./Solr stop -help This status command of Solr can be used to search and find out the running Solr instances on your computer. It can provide you information about a Solr instance such as its version, memory usage, etc. You can check the status of a Solr instance, using the status command as follows − [Hadoop@localhost bin]$ ./Solr status On executing, the above command displays the status of Solr as follows − Found 1 Solr nodes: Solr process 6906 running on port 8983 { "Solr_home":"/home/Hadoop/Solr/server/Solr", "version":"6.2.0 764d0f19151dbff6f5fcd9fc4b2682cf934590c5 - mike - 2016-08-20 05:41:37", "startTime":"2016-09-20T06:00:02.877Z", "uptime":"0 days, 0 hours, 5 minutes, 14 seconds", "memory":"30.6 MB (%6.2) of 490.7 MB" } After starting Apache Solr, you can visit the homepage of the Solr web interface by using the following URL. Localhost:8983/Solr/ The interface of Solr Admin appears as follows − A Solr Core is a running instance of a Lucene index that contains all the Solr configuration files required to use it. We need to create a Solr Core to perform operations like indexing and analyzing. A Solr application may contain one or multiple cores. If necessary, two cores in a Solr application can communicate with each other. After installing and starting Solr, you can connect to the client (web interface) of Solr. As highlighted in the following screenshot, initially there are no cores in Apache Solr. Now, we will see how to create a core in Solr. One way to create a core is to create a schema-less core using the create command, as shown below − [Hadoop@localhost bin]$ ./Solr create -c Solr_sample Here, we are trying to create a core named Solr_sample in Apache Solr. This command creates a core displaying the following message. Copying configuration to new core instance directory: /home/Hadoop/Solr/server/Solr/Solr_sample Creating new core 'Solr_sample' using command: http://localhost:8983/Solr/admin/cores?action=CREATE&name=Solr_sample&instanceD ir = Solr_sample { "responseHeader":{ "status":0, "QTime":11550 }, "core":"Solr_sample" } You can create multiple cores in Solr. On the left-hand side of the Solr Admin, you can see a core selector where you can select the newly created core, as shown in the following screenshot. Alternatively, you can create a core using the create_core command. This command has the following options − Let’s see how you can use the create_core command. Here, we will try to create a core named my_core. [Hadoop@localhost bin]$ ./Solr create_core -c my_core On executing, the above command creates a core displaying the following message − Copying configuration to new core instance directory: /home/Hadoop/Solr/server/Solr/my_core Creating new core 'my_core' using command: http://localhost:8983/Solr/admin/cores?action=CREATE&name=my_core&instanceD ir = my_core { "responseHeader":{ "status":0, "QTime":1346 }, "core":"my_core" } You can delete a core using the delete command of Apache Solr. Let’s suppose we have a core named my_core in Solr, as shown in the following screenshot. You can delete this core using the delete command by passing the name of the core to this command as follows − [Hadoop@localhost bin]$ ./Solr delete -c my_core On executing the above command, the specified core will be deleted displaying the following message. Deleting core 'my_core' using command: http://localhost:8983/Solr/admin/cores?action=UNLOAD&core = my_core&deleteIndex = true&deleteDataDir = true&deleteInstanceDir = true { "responseHeader" :{ "status":0, "QTime":170 } } You can open the web interface of Solr to verify whether the core has been deleted or not. In general, indexing is an arrangement of documents or (other entities) systematically. Indexing enables users to locate information in a document. Indexing collects, parses, and stores documents. Indexing collects, parses, and stores documents. Indexing is done to increase the speed and performance of a search query while finding a required document. Indexing is done to increase the speed and performance of a search query while finding a required document. In Apache Solr, we can index (add, delete, modify) various document formats such as xml, csv, pdf, etc. We can add data to Solr index in several ways. In this chapter, we are going to discuss indexing − Using the Solr Web Interface. Using any of the client APIs like Java, Python, etc. Using the post tool. In this chapter, we will discuss how to add data to the index of Apache Solr using various interfaces (command line, web interface, and Java client API) Solr has a post command in its bin/ directory. Using this command, you can index various formats of files such as JSON, XML, CSV in Apache Solr. Browse through the bin directory of Apache Solr and execute the –h option of the post command, as shown in the following code block. [Hadoop@localhost bin]$ cd $SOLR_HOME [Hadoop@localhost bin]$ ./post -h On executing the above command, you will get a list of options of the post command, as shown below. Usage: post -c <collection> [OPTIONS] <files|directories|urls|-d [".."]> or post –help collection name defaults to DEFAULT_SOLR_COLLECTION if not specified OPTIONS ======= Solr options: -url <base Solr update URL> (overrides collection, host, and port) -host <host> (default: localhost) -p or -port <port> (default: 8983) -commit yes|no (default: yes) Web crawl options: -recursive <depth> (default: 1) -delay <seconds> (default: 10) Directory crawl options: -delay <seconds> (default: 0) stdin/args options: -type <content/type> (default: application/xml) Other options: -filetypes <type>[,<type>,...] (default: xml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots, rtf,htm,html,txt,log) -params "<key> = <value>[&<key> = <value>...]" (values must be URL-encoded; these pass through to Solr update request) -out yes|no (default: no; yes outputs Solr response to console) -format Solr (sends application/json content as Solr commands to /update instead of /update/json/docs) Examples: * JSON file:./post -c wizbang events.json * XML files: ./post -c records article*.xml * CSV file: ./post -c signals LATEST-signals.csv * Directory of files: ./post -c myfiles ~/Documents * Web crawl: ./post -c gettingstarted http://lucene.apache.org/Solr -recursive 1 -delay 1 * Standard input (stdin): echo '{commit: {}}' | ./post -c my_collection - type application/json -out yes –d * Data as string: ./post -c signals -type text/csv -out yes -d $'id,value\n1,0.47' Suppose we have a file named sample.csv with the following content (in the bin directory). The above dataset contains personal details like Student id, first name, last name, phone, and city. The CSV file of the dataset is shown below. Here, you must note that you need to mention the schema, documenting its first line. id, first_name, last_name, phone_no, location 001, Pruthvi, Reddy, 9848022337, Hyderabad 002, kasyap, Sastry, 9848022338, Vishakapatnam 003, Rajesh, Khanna, 9848022339, Delhi 004, Preethi, Agarwal, 9848022330, Pune 005, Trupthi, Mohanty, 9848022336, Bhubaneshwar 006, Archana, Mishra, 9848022335, Chennai You can index this data under the core named sample_Solr using the post command as follows − [Hadoop@localhost bin]$ ./post -c Solr_sample sample.csv On executing the above command, the given document is indexed under the specified core, generating the following output. /home/Hadoop/java/bin/java -classpath /home/Hadoop/Solr/dist/Solr-core 6.2.0.jar -Dauto = yes -Dc = Solr_sample -Ddata = files org.apache.Solr.util.SimplePostTool sample.csv SimplePostTool version 5.0.0 Posting files to [base] url http://localhost:8983/Solr/Solr_sample/update... Entering auto mode. File endings considered are xml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots,rtf, htm,html,txt,log POSTing file sample.csv (text/csv) to [base] 1 files indexed. COMMITting Solr index changes to http://localhost:8983/Solr/Solr_sample/update... Time spent: 0:00:00.228 Visit the homepage of Solr Web UI using the following URL − http://localhost:8983/ Select the core Solr_sample. By default, the request handler is /select and the query is “:”. Without doing any modifications, click the ExecuteQuery button at the bottom of the page. On executing the query, you can observe the contents of the indexed CSV document in JSON format (default), as shown in the following screenshot. Note − In the same way, you can index other file formats such as JSON, XML, CSV, etc. You can also index documents using the web interface provided by Solr. Let us see how to index the following JSON document. [ { "id" : "001", "name" : "Ram", "age" : 53, "Designation" : "Manager", "Location" : "Hyderabad", }, { "id" : "002", "name" : "Robert", "age" : 43, "Designation" : "SR.Programmer", "Location" : "Chennai", }, { "id" : "003", "name" : "Rahim", "age" : 25, "Designation" : "JR.Programmer", "Location" : "Delhi", } ] Open Solr web interface using the following URL − http://localhost:8983/ Step 2 Select the core Solr_sample. By default, the values of the fields Request Handler, Common Within, Overwrite, and Boost are /update, 1000, true, and 1.0 respectively, as shown in the following screenshot. Now, choose the document format you want from JSON, CSV, XML, etc. Type the document to be indexed in the text area and click the Submit Document button, as shown in the following screenshot. Following is the Java program to add documents to Apache Solr index. Save this code in a file with the name AddingDocument.java. import java.io.IOException; import org.apache.Solr.client.Solrj.SolrClient; import org.apache.Solr.client.Solrj.SolrServerException; import org.apache.Solr.client.Solrj.impl.HttpSolrClient; import org.apache.Solr.common.SolrInputDocument; public class AddingDocument { public static void main(String args[]) throws Exception { //Preparing the Solr client String urlString = "http://localhost:8983/Solr/my_core"; SolrClient Solr = new HttpSolrClient.Builder(urlString).build(); //Preparing the Solr document SolrInputDocument doc = new SolrInputDocument(); //Adding fields to the document doc.addField("id", "003"); doc.addField("name", "Rajaman"); doc.addField("age","34"); doc.addField("addr","vishakapatnam"); //Adding the document to Solr Solr.add(doc); //Saving the changes Solr.commit(); System.out.println("Documents added"); } } Compile the above code by executing the following commands in the terminal − [Hadoop@localhost bin]$ javac AddingDocument [Hadoop@localhost bin]$ java AddingDocument On executing the above command, you will get the following output. Documents added In the previous chapter, we explained how to add data into Solr which is in JSON and .CSV file formats. In this chapter, we will demonstrate how to add data in Apache Solr index using XML document format. Suppose we need to add the following data to Solr index using the XML file format. To add the above data into Solr index, we need to prepare an XML document, as shown below. Save this document in a file with the name sample.xml. <add> <doc> <field name = "id">001</field> <field name = "first name">Rajiv</field> <field name = "last name">Reddy</field> <field name = "phone">9848022337</field> <field name = "city">Hyderabad</field> </doc> <doc> <field name = "id">002</field> <field name = "first name">Siddarth</field> <field name = "last name">Battacharya</field> <field name = "phone">9848022338</field> <field name = "city">Kolkata</field> </doc> <doc> <field name = "id">003</field> <field name = "first name">Rajesh</field> <field name = "last name">Khanna</field> <field name = "phone">9848022339</field> <field name = "city">Delhi</field> </doc> <doc> <field name = "id">004</field> <field name = "first name">Preethi</field> <field name = "last name">Agarwal</field> <field name = "phone">9848022330</field> <field name = "city">Pune</field> </doc> <doc> <field name = "id">005</field> <field name = "first name">Trupthi</field> <field name = "last name">Mohanthy</field> <field name = "phone">9848022336</field> <field name = "city">Bhuwaeshwar</field> </doc> <doc> <field name = "id">006</field> <field name = "first name">Archana</field> <field name = "last name">Mishra</field> <field name = "phone">9848022335</field> <field name = "city">Chennai</field> </doc> </add> As you can observe, the XML file written to add data to index contains three important tags namely, <add> </add>, <doc></doc>, and < field >< /field >. add − This is the root tag for adding documents to the index. It contains one or more documents that are to be added. add − This is the root tag for adding documents to the index. It contains one or more documents that are to be added. doc − The documents we add should be wrapped within the <doc></doc> tags. This document contains the data in the form of fields. doc − The documents we add should be wrapped within the <doc></doc> tags. This document contains the data in the form of fields. field − The field tag holds the name and value of the fields of the document. field − The field tag holds the name and value of the fields of the document. After preparing the document, you can add this document to the index using any of the means discussed in the previous chapter. Suppose the XML file exists in the bin directory of Solr and it is to be indexed in the core named my_core, then you can add it to Solr index using the post tool as follows − [Hadoop@localhost bin]$ ./post -c my_core sample.xml On executing the above command, you will get the following output. /home/Hadoop/java/bin/java -classpath /home/Hadoop/Solr/dist/Solr- core6.2.0.jar -Dauto = yes -Dc = my_core -Ddata = files org.apache.Solr.util.SimplePostTool sample.xml SimplePostTool version 5.0.0 Posting files to [base] url http://localhost:8983/Solr/my_core/update... Entering auto mode. File endings considered are xml,json,jsonl,csv,pdf,doc,docx,ppt,pptx, xls,xlsx,odt,odp,ods,ott,otp,ots,rtf,htm,html,txt,log POSTing file sample.xml (application/xml) to [base] 1 files indexed. COMMITting Solr index changes to http://localhost:8983/Solr/my_core/update... Time spent: 0:00:00.201 Visit the homepage of Apache Solr web interface and select the core my_core. Try to retrieve all the documents by passing the query “:” in the text area q and execute the query. On executing, you can observe that the desired data is added to the Solr index. Following is the XML file used to update a field in the existing document. Save this in a file with the name update.xml. <add> <doc> <field name = "id">001</field> <field name = "first name" update = "set">Raj</field> <field name = "last name" update = "add">Malhotra</field> <field name = "phone" update = "add">9000000000</field> <field name = "city" update = "add">Delhi</field> </doc> </add> As you can observe, the XML file written to update data is just like the one which we use to add documents. But the only difference is we use the update attribute of the field. In our example, we will use the above document and try to update the fields of the document with the id 001. Suppose the XML document exists in the bin directory of Solr. Since we are updating the index which exists in the core named my_core, you can update using the post tool as follows − [Hadoop@localhost bin]$ ./post -c my_core update.xml On executing the above command, you will get the following output. /home/Hadoop/java/bin/java -classpath /home/Hadoop/Solr/dist/Solr-core 6.2.0.jar -Dauto = yes -Dc = my_core -Ddata = files org.apache.Solr.util.SimplePostTool update.xml SimplePostTool version 5.0.0 Posting files to [base] url http://localhost:8983/Solr/my_core/update... Entering auto mode. File endings considered are xml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots,rtf, htm,html,txt,log POSTing file update.xml (application/xml) to [base] 1 files indexed. COMMITting Solr index changes to http://localhost:8983/Solr/my_core/update... Time spent: 0:00:00.159 Visit the homepage of Apache Solr web interface and select the core as my_core. Try to retrieve all the documents by passing the query “:” in the text area q and execute the query. On executing, you can observe that the document is updated. Following is the Java program to add documents to Apache Solr index. Save this code in a file with the name UpdatingDocument.java. import java.io.IOException; import org.apache.Solr.client.Solrj.SolrClient; import org.apache.Solr.client.Solrj.SolrServerException; import org.apache.Solr.client.Solrj.impl.HttpSolrClient; import org.apache.Solr.client.Solrj.request.UpdateRequest; import org.apache.Solr.client.Solrj.response.UpdateResponse; import org.apache.Solr.common.SolrInputDocument; public class UpdatingDocument { public static void main(String args[]) throws SolrServerException, IOException { //Preparing the Solr client String urlString = "http://localhost:8983/Solr/my_core"; SolrClient Solr = new HttpSolrClient.Builder(urlString).build(); //Preparing the Solr document SolrInputDocument doc = new SolrInputDocument(); UpdateRequest updateRequest = new UpdateRequest(); updateRequest.setAction( UpdateRequest.ACTION.COMMIT, false, false); SolrInputDocument myDocumentInstantlycommited = new SolrInputDocument(); myDocumentInstantlycommited.addField("id", "002"); myDocumentInstantlycommited.addField("name", "Rahman"); myDocumentInstantlycommited.addField("age","27"); myDocumentInstantlycommited.addField("addr","hyderabad"); updateRequest.add( myDocumentInstantlycommited); UpdateResponse rsp = updateRequest.process(Solr); System.out.println("Documents Updated"); } } Compile the above code by executing the following commands in the terminal − [Hadoop@localhost bin]$ javac UpdatingDocument [Hadoop@localhost bin]$ java UpdatingDocument On executing the above command, you will get the following output. Documents updated To delete documents from the index of Apache Solr, we need to specify the ID’s of the documents to be deleted between the <delete></delete> tags. <delete> <id>003</id> <id>005</id> <id>004</id> <id>002</id> </delete> Here, this XML code is used to delete the documents with ID’s 003 and 005. Save this code in a file with the name delete.xml. If you want to delete the documents from the index which belongs to the core named my_core, then you can post the delete.xml file using the post tool, as shown below. [Hadoop@localhost bin]$ ./post -c my_core delete.xml On executing the above command, you will get the following output. /home/Hadoop/java/bin/java -classpath /home/Hadoop/Solr/dist/Solr-core 6.2.0.jar -Dauto = yes -Dc = my_core -Ddata = files org.apache.Solr.util.SimplePostTool delete.xml SimplePostTool version 5.0.0 Posting files to [base] url http://localhost:8983/Solr/my_core/update... Entering auto mode. File endings considered are xml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots, rtf,htm,html,txt,log POSTing file delete.xml (application/xml) to [base] 1 files indexed. COMMITting Solr index changes to http://localhost:8983/Solr/my_core/update... Time spent: 0:00:00.179 Visit the homepage of the of Apache Solr web interface and select the core as my_core. Try to retrieve all the documents by passing the query “:” in the text area q and execute the query. On executing, you can observe that the specified documents are deleted. Sometimes we need to delete documents based on fields other than ID. For example, we may have to delete the documents where the city is Chennai. In such cases, you need to specify the name and value of the field within the <query></query> tag pair. <delete> <query>city:Chennai</query> </delete> Save it as delete_field.xml and perform the delete operation on the core named my_core using the post tool of Solr. [Hadoop@localhost bin]$ ./post -c my_core delete_field.xml On executing the above command, it produces the following output. /home/Hadoop/java/bin/java -classpath /home/Hadoop/Solr/dist/Solr-core 6.2.0.jar -Dauto = yes -Dc = my_core -Ddata = files org.apache.Solr.util.SimplePostTool delete_field.xml SimplePostTool version 5.0.0 Posting files to [base] url http://localhost:8983/Solr/my_core/update... Entering auto mode. File endings considered are xml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots, rtf,htm,html,txt,log POSTing file delete_field.xml (application/xml) to [base] 1 files indexed. COMMITting Solr index changes to http://localhost:8983/Solr/my_core/update... Time spent: 0:00:00.084 Visit the homepage of the of Apache Solr web interface and select the core as my_core. Try to retrieve all the documents by passing the query “:” in the text area q and execute the query. On executing, you can observe that the documents containing the specified field value pair are deleted. Just like deleting a specific field, if you want to delete all the documents from an index, you just need to pass the symbol “:” between the tags <query></ query>, as shown below. <delete> <query>*:*</query> </delete> Save it as delete_all.xml and perform the delete operation on the core named my_core using the post tool of Solr. [Hadoop@localhost bin]$ ./post -c my_core delete_all.xml On executing the above command, it produces the following output. /home/Hadoop/java/bin/java -classpath /home/Hadoop/Solr/dist/Solr-core 6.2.0.jar -Dauto = yes -Dc = my_core -Ddata = files org.apache.Solr.util.SimplePostTool deleteAll.xml SimplePostTool version 5.0.0 Posting files to [base] url http://localhost:8983/Solr/my_core/update... Entering auto mode. File endings considered are xml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots,rtf, htm,html,txt,log POSTing file deleteAll.xml (application/xml) to [base] 1 files indexed. COMMITting Solr index changes to http://localhost:8983/Solr/my_core/update... Time spent: 0:00:00.138 Visit the homepage of Apache Solr web interface and select the core as my_core. Try to retrieve all the documents by passing the query “:” in the text area q and execute the query. On executing, you can observe that the documents containing the specified field value pair are deleted. Following is the Java program to add documents to Apache Solr index. Save this code in a file with the name UpdatingDocument.java. import java.io.IOException; import org.apache.Solr.client.Solrj.SolrClient; import org.apache.Solr.client.Solrj.SolrServerException; import org.apache.Solr.client.Solrj.impl.HttpSolrClient; import org.apache.Solr.common.SolrInputDocument; public class DeletingAllDocuments { public static void main(String args[]) throws SolrServerException, IOException { //Preparing the Solr client String urlString = "http://localhost:8983/Solr/my_core"; SolrClient Solr = new HttpSolrClient.Builder(urlString).build(); //Preparing the Solr document SolrInputDocument doc = new SolrInputDocument(); //Deleting the documents from Solr Solr.deleteByQuery("*"); //Saving the document Solr.commit(); System.out.println("Documents deleted"); } } Compile the above code by executing the following commands in the terminal − [Hadoop@localhost bin]$ javac DeletingAllDocuments [Hadoop@localhost bin]$ java DeletingAllDocuments On executing the above command, you will get the following output. Documents deleted In this chapter, we will discuss how to retrieve data using Java Client API. Suppose we have a .csv document named sample.csv with the following content. 001,9848022337,Hyderabad,Rajiv,Reddy 002,9848022338,Kolkata,Siddarth,Battacharya 003,9848022339,Delhi,Rajesh,Khanna You can index this data under the core named sample_Solr using the post command. [Hadoop@localhost bin]$ ./post -c Solr_sample sample.csv Following is the Java program to add documents to Apache Solr index. Save this code in a file with named RetrievingData.java. import java.io.IOException; import org.apache.Solr.client.Solrj.SolrClient; import org.apache.Solr.client.Solrj.SolrQuery; import org.apache.Solr.client.Solrj.SolrServerException; import org.apache.Solr.client.Solrj.impl.HttpSolrClient; import org.apache.Solr.client.Solrj.response.QueryResponse; import org.apache.Solr.common.SolrDocumentList; public class RetrievingData { public static void main(String args[]) throws SolrServerException, IOException { //Preparing the Solr client String urlString = "http://localhost:8983/Solr/my_core"; SolrClient Solr = new HttpSolrClient.Builder(urlString).build(); //Preparing Solr query SolrQuery query = new SolrQuery(); query.setQuery("*:*"); //Adding the field to be retrieved query.addField("*"); //Executing the query QueryResponse queryResponse = Solr.query(query); //Storing the results of the query SolrDocumentList docs = queryResponse.getResults(); System.out.println(docs); System.out.println(docs.get(0)); System.out.println(docs.get(1)); System.out.println(docs.get(2)); //Saving the operations Solr.commit(); } } Compile the above code by executing the following commands in the terminal − [Hadoop@localhost bin]$ javac RetrievingData [Hadoop@localhost bin]$ java RetrievingData On executing the above command, you will get the following output. {numFound = 3,start = 0,docs = [SolrDocument{id=001, phone = [9848022337], city = [Hyderabad], first_name = [Rajiv], last_name = [Reddy], _version_ = 1547262806014820352}, SolrDocument{id = 002, phone = [9848022338], city = [Kolkata], first_name = [Siddarth], last_name = [Battacharya], _version_ = 1547262806026354688}, SolrDocument{id = 003, phone = [9848022339], city = [Delhi], first_name = [Rajesh], last_name = [Khanna], _version_ = 1547262806029500416}]} SolrDocument{id = 001, phone = [9848022337], city = [Hyderabad], first_name = [Rajiv], last_name = [Reddy], _version_ = 1547262806014820352} SolrDocument{id = 002, phone = [9848022338], city = [Kolkata], first_name = [Siddarth], last_name = [Battacharya], _version_ = 1547262806026354688} SolrDocument{id = 003, phone = [9848022339], city = [Delhi], first_name = [Rajesh], last_name = [Khanna], _version_ = 1547262806029500416} In addition to storing data, Apache Solr also provides the facility of querying it back as and when required. Solr provides certain parameters using which we can query the data stored in it. In the following table, we have listed down the various query parameters available in Apache Solr. You can see all these parameters as options to query Apache Solr. Visit the homepage of Apache Solr. On the left-hand side of the page, click on the option Query. Here, you can see the fields for the parameters of a query. Assume we have 3 records in the core named my_core. To retrieve a particular record from the selected core, you need to pass the name and value pairs of the fields of a particular document. For example, if you want to retrieve the record with the value of the field id, you need to pass the name-value pair of the field as − Id:001 as value for the parameter q and execute the query. In the same way, you can retrieve all the records from an index by passing *:* as a value to the parameter q, as shown in the following screenshot. We can retrieve the records from the second record by passing 2 as a value to the parameter start, as shown in the following screenshot. You can restrict the number of records by specifying a value in the rows parameter. For example, we can restrict the total number of records in the result of the query to 2 by passing the value 2 into the parameter rows, as shown in the following screenshot. You can get the response in required document type by selecting one from the provided values of the parameter wt. In the above instance, we have chosen the .csv format to get the response. If we want to have particular fields in the resulted documents, we need to pass the list of the required fields, separated by commas, as a value to the property fl. In the following example, we are trying to retrieve the fields − id, phone, and first_name. Faceting in Apache Solr refers to the classification of the search results into various categories. In this chapter, we will discuss the types of faceting available in Apache Solr − Query faceting − It returns the number of documents in the current search results that also match the given query. Query faceting − It returns the number of documents in the current search results that also match the given query. Date faceting − It returns the number of documents that fall within certain date ranges. Date faceting − It returns the number of documents that fall within certain date ranges. Faceting commands are added to any normal Solr query request, and the faceting counts come back in the same query response. Using the field faceting, we can retrieve the counts for all terms, or just the top terms in any given field. As an example, let us consider the following books.csv file that contains data about various books. id,cat,name,price,inStock,author,series_t,sequence_i,genre_s 0553573403,book,A Game of Thrones,5.99,true,George R.R. Martin,"A Song of Ice and Fire",1,fantasy 0553579908,book,A Clash of Kings,10.99,true,George R.R. Martin,"A Song of Ice and Fire",2,fantasy 055357342X,book,A Storm of Swords,7.99,true,George R.R. Martin,"A Song of Ice and Fire",3,fantasy 0553293354,book,Foundation,7.99,true,Isaac Asimov,Foundation Novels,1,scifi 0812521390,book,The Black Company,4.99,false,Glen Cook,The Chronicles of The Black Company,1,fantasy 0812550706,book,Ender's Game,6.99,true,Orson Scott Card,Ender,1,scifi 0441385532,book,Jhereg,7.95,false,Steven Brust,Vlad Taltos,1,fantasy 0380014300,book,Nine Princes In Amber,6.99,true,Roger Zelazny,the Chronicles of Amber,1,fantasy 0805080481,book,The Book of Three,5.99,true,Lloyd Alexander,The Chronicles of Prydain,1,fantasy 080508049X,book,The Black Cauldron,5.99,true,Lloyd Alexander,The Chronicles of Prydain,2,fantasy Let us post this file into Apache Solr using the post tool. [Hadoop@localhost bin]$ ./post -c Solr_sample sample.csv On executing the above command, all the documents mentioned in the given .csv file will be uploaded into Apache Solr. Now let us execute a faceted query on the field author with 0 rows on the collection/core my_core. Open the web UI of Apache Solr and on the left-hand side of the page, check the checkbox facet, as shown in the following screenshot. On checking the checkbox, you will have three more text fields in order to pass the parameters of the facet search. Now, as parameters of the query, pass the following values. q = *:*, rows = 0, facet.field = author Finally, execute the query by clicking the Execute Query button. On executing, it will produce the following result. It categorizes the documents in the index based on author and specifies the number of books contributed by each author. Following is the Java program to add documents to Apache Solr index. Save this code in a file with the name HitHighlighting.java. import java.io.IOException; import java.util.List; import org.apache.Solr.client.Solrj.SolrClient; import org.apache.Solr.client.Solrj.SolrQuery; import org.apache.Solr.client.Solrj.SolrServerException; import org.apache.Solr.client.Solrj.impl.HttpSolrClient; import org.apache.Solr.client.Solrj.request.QueryRequest; import org.apache.Solr.client.Solrj.response.FacetField; import org.apache.Solr.client.Solrj.response.FacetField.Count; import org.apache.Solr.client.Solrj.response.QueryResponse; import org.apache.Solr.common.SolrInputDocument; public class HitHighlighting { public static void main(String args[]) throws SolrServerException, IOException { //Preparing the Solr client String urlString = "http://localhost:8983/Solr/my_core"; SolrClient Solr = new HttpSolrClient.Builder(urlString).build(); //Preparing the Solr document SolrInputDocument doc = new SolrInputDocument(); //String query = request.query; SolrQuery query = new SolrQuery(); //Setting the query string query.setQuery("*:*"); //Setting the no.of rows query.setRows(0); //Adding the facet field query.addFacetField("author"); //Creating the query request QueryRequest qryReq = new QueryRequest(query); //Creating the query response QueryResponse resp = qryReq.process(Solr); //Retrieving the response fields System.out.println(resp.getFacetFields()); List<FacetField> facetFields = resp.getFacetFields(); for (int i = 0; i > facetFields.size(); i++) { FacetField facetField = facetFields.get(i); List<Count> facetInfo = facetField.getValues(); for (FacetField.Count facetInstance : facetInfo) { System.out.println(facetInstance.getName() + " : " + facetInstance.getCount() + " [drilldown qry:" + facetInstance.getAsFilterQuery()); } System.out.println("Hello"); } } } Compile the above code by executing the following commands in the terminal − [Hadoop@localhost bin]$ javac HitHighlighting [Hadoop@localhost bin]$ java HitHighlighting On executing the above command, you will get the following output. [author:[George R.R. Martin (3), Lloyd Alexander (2), Glen Cook (1), Isaac Asimov (1), Orson Scott Card (1), Roger Zelazny (1), Steven Brust (1)]] 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2298, "s": 2024, "text": "Solr is an open-source search platform which is used to build search applications. It was built on top of Lucene (full text search engine). Solr is enterprise-ready, fast and highly scalable. The applications built using Solr are sophisticated and deliver high performance." }, { "code": null, "e": 2604, "s": 2298, "text": "It was Yonik Seely who created Solr in 2004 in order to add search capabilities to the company website of CNET Networks. In Jan 2006, it was made an open-source project under Apache Software Foundation. Its latest version, Solr 6.0, was released in 2016 with support for execution of parallel SQL queries." }, { "code": null, "e": 2909, "s": 2604, "text": "Solr can be used along with Hadoop. As Hadoop handles a large amount of data, Solr helps us in finding the required information from such a large source. Not only search, Solr can also be used for storage purpose. Like other NoSQL databases, it is a non-relational data storage and processing technology." }, { "code": null, "e": 3034, "s": 2909, "text": "In short, Solr is a scalable, ready to deploy, search/storage engine optimized to search large volumes of text-centric data." }, { "code": null, "e": 3207, "s": 3034, "text": "Solr is a wrap around Lucene’s Java API. Therefore, using Solr, you can leverage all the features of Lucene. Let us take a look at some of most prominent features of Solr −" }, { "code": null, "e": 3471, "s": 3207, "text": "Restful APIs − To communicate with Solr, it is not mandatory to have Java programming skills. Instead you can use restful services to communicate with it. We enter documents in Solr in file formats like XML, JSON and .CSV and get results in the same file formats." }, { "code": null, "e": 3735, "s": 3471, "text": "Restful APIs − To communicate with Solr, it is not mandatory to have Java programming skills. Instead you can use restful services to communicate with it. We enter documents in Solr in file formats like XML, JSON and .CSV and get results in the same file formats." }, { "code": null, "e": 3886, "s": 3735, "text": "Full text search − Solr provides all the capabilities needed for a full text search such as tokens, phrases, spell check, wildcard, and auto-complete." }, { "code": null, "e": 4037, "s": 3886, "text": "Full text search − Solr provides all the capabilities needed for a full text search such as tokens, phrases, spell check, wildcard, and auto-complete." }, { "code": null, "e": 4203, "s": 4037, "text": "Enterprise ready − According to the need of the organization, Solr can be deployed in any kind of systems (big or small) such as standalone, distributed, cloud, etc." }, { "code": null, "e": 4369, "s": 4203, "text": "Enterprise ready − According to the need of the organization, Solr can be deployed in any kind of systems (big or small) such as standalone, distributed, cloud, etc." }, { "code": null, "e": 4502, "s": 4369, "text": "Flexible and Extensible − By extending the Java classes and configuring accordingly, we can customize the components of Solr easily." }, { "code": null, "e": 4635, "s": 4502, "text": "Flexible and Extensible − By extending the Java classes and configuring accordingly, we can customize the components of Solr easily." }, { "code": null, "e": 4765, "s": 4635, "text": "NoSQL database − Solr can also be used as big data scale NOSQL database where we can distribute the search tasks along a cluster." }, { "code": null, "e": 4895, "s": 4765, "text": "NoSQL database − Solr can also be used as big data scale NOSQL database where we can distribute the search tasks along a cluster." }, { "code": null, "e": 5104, "s": 4895, "text": "Admin Interface − Solr provides an easy-to-use, user friendly, feature powered, user interface, using which we can perform all the possible tasks such as manage logs, add, delete, update and search documents." }, { "code": null, "e": 5313, "s": 5104, "text": "Admin Interface − Solr provides an easy-to-use, user friendly, feature powered, user interface, using which we can perform all the possible tasks such as manage logs, add, delete, update and search documents." }, { "code": null, "e": 5407, "s": 5313, "text": "Highly Scalable − While using Solr with Hadoop, we can scale its capacity by adding replicas." }, { "code": null, "e": 5501, "s": 5407, "text": "Highly Scalable − While using Solr with Hadoop, we can scale its capacity by adding replicas." }, { "code": null, "e": 5674, "s": 5501, "text": "Text-Centric and Sorted by Relevance − Solr is mostly used to search text documents and the results are delivered according to the relevance with the user’s query in order." }, { "code": null, "e": 5847, "s": 5674, "text": "Text-Centric and Sorted by Relevance − Solr is mostly used to search text documents and the results are delivered according to the relevance with the user’s query in order." }, { "code": null, "e": 6162, "s": 5847, "text": "Unlike Lucene, you don’t need to have Java programming skills while working with Apache Solr. It provides a wonderful ready-to-deploy service to build a search box featuring autocomplete, which Lucene doesn’t provide. Using Solr, we can scale, distribute, and manage index, for large scale (Big Data) applications." }, { "code": null, "e": 6504, "s": 6162, "text": "Lucene is simple yet powerful Java-based search library. It can be used in any application to add search capability. Lucene is a scalable and high-performance library used to index and search virtually any kind of text. Lucene library provides the core operations which are required by any search application, such as Indexing and Searching." }, { "code": null, "e": 6805, "s": 6504, "text": "If we have a web portal with a huge volume of data, then we will most probably require a search engine in our portal to extract relevant information from the huge pool of data. Lucene works as the heart of any search application and provides the vital operations pertaining to indexing and searching." }, { "code": null, "e": 6976, "s": 6805, "text": "A Search Engine refers to a huge database of Internet resources such as webpages, newsgroups, programs, images, etc. It helps to locate information on the World Wide Web." }, { "code": null, "e": 7175, "s": 6976, "text": "Users can search for information by passing queries into the Search Engine in the form of keywords or phrases. The Search Engine then searches in its database and returns relevant links to the user." }, { "code": null, "e": 7256, "s": 7175, "text": "Generally, there are three basic components of a search engine as listed below −" }, { "code": null, "e": 7391, "s": 7256, "text": "Web Crawler − Web crawlers are also known as spiders or bots. It is a software component that traverses the web to gather information." }, { "code": null, "e": 7526, "s": 7391, "text": "Web Crawler − Web crawlers are also known as spiders or bots. It is a software component that traverses the web to gather information." }, { "code": null, "e": 7637, "s": 7526, "text": "Database − All the information on the Web is stored in databases. They contain a huge volume of web resources." }, { "code": null, "e": 7748, "s": 7637, "text": "Database − All the information on the Web is stored in databases. They contain a huge volume of web resources." }, { "code": null, "e": 7884, "s": 7748, "text": "Search Interfaces − This component is an interface between the user and the database. It helps the user to search through the database." }, { "code": null, "e": 8020, "s": 7884, "text": "Search Interfaces − This component is an interface between the user and the database. It helps the user to search through the database." }, { "code": null, "e": 8107, "s": 8020, "text": "Any search application is required to perform some or all of the following operations." }, { "code": null, "e": 8109, "s": 8107, "text": "1" }, { "code": null, "e": 8129, "s": 8109, "text": "Acquire Raw Content" }, { "code": null, "e": 8245, "s": 8129, "text": "The very first step of any search application is to collect the target contents on which search is to be conducted." }, { "code": null, "e": 8247, "s": 8245, "text": "2" }, { "code": null, "e": 8266, "s": 8247, "text": "Build the document" }, { "code": null, "e": 8396, "s": 8266, "text": "The next step is to build the document(s) from the raw contents which the search application can understand and interpret easily." }, { "code": null, "e": 8398, "s": 8396, "text": "3" }, { "code": null, "e": 8419, "s": 8398, "text": "Analyze the document" }, { "code": null, "e": 8478, "s": 8419, "text": "Before indexing can start, the document is to be analyzed." }, { "code": null, "e": 8480, "s": 8478, "text": "4" }, { "code": null, "e": 8502, "s": 8480, "text": "Indexing the document" }, { "code": null, "e": 8685, "s": 8502, "text": "Once the documents are built and analyzed, the next step is to index them so that this document can be retrieved based on certain keys, instead of the whole contents of the document." }, { "code": null, "e": 8891, "s": 8685, "text": "Indexing is similar to the indexes that we have at the end of a book where common words are shown with their page numbers so that these words can be tracked quickly, instead of searching the complete book." }, { "code": null, "e": 8893, "s": 8891, "text": "5" }, { "code": null, "e": 8919, "s": 8893, "text": "User Interface for Search" }, { "code": null, "e": 9148, "s": 8919, "text": "Once a database of indexes is ready, then the application can perform search operations. To help the user make a search, the application must provide a user interface where the user can enter text and initiate the search process" }, { "code": null, "e": 9150, "s": 9148, "text": "6" }, { "code": null, "e": 9162, "s": 9150, "text": "Build Query" }, { "code": null, "e": 9351, "s": 9162, "text": "Once the user makes a request to search a text, the application should prepare a query object using that text, which can then be used to inquire the index database to get relevant details." }, { "code": null, "e": 9353, "s": 9351, "text": "7" }, { "code": null, "e": 9366, "s": 9353, "text": "Search Query" }, { "code": null, "e": 9475, "s": 9366, "text": "Using the query object, the index database is checked to get the relevant details and the content documents." }, { "code": null, "e": 9477, "s": 9475, "text": "8" }, { "code": null, "e": 9492, "s": 9477, "text": "Render Results" }, { "code": null, "e": 9625, "s": 9492, "text": "Once the required result is received, the application should decide how to display the results to the user using its User Interface." }, { "code": null, "e": 9725, "s": 9625, "text": "Take a look at the following illustration. It shows an overall view of how Search Engines function." }, { "code": null, "e": 10005, "s": 9725, "text": "Apart from these basic operations, search applications can also provide administration-user interface to help the administrators control the level of search based on the user profiles. Analytics of search result is another important and advanced aspect of any search application." }, { "code": null, "e": 10164, "s": 10005, "text": "In this chapter, we will discuss how to set up Solr in Windows environment. To install Solr on your Windows system, you need to follow the steps given below −" }, { "code": null, "e": 10229, "s": 10164, "text": "Visit the homepage of Apache Solr and click the download button." }, { "code": null, "e": 10294, "s": 10229, "text": "Visit the homepage of Apache Solr and click the download button." }, { "code": null, "e": 10403, "s": 10294, "text": "Select one of the mirrors to get an index of Apache Solr. From there download the file named Solr-6.2.0.zip." }, { "code": null, "e": 10512, "s": 10403, "text": "Select one of the mirrors to get an index of Apache Solr. From there download the file named Solr-6.2.0.zip." }, { "code": null, "e": 10592, "s": 10512, "text": "Move the file from the downloads folder to the required directory and unzip it." }, { "code": null, "e": 10672, "s": 10592, "text": "Move the file from the downloads folder to the required directory and unzip it." }, { "code": null, "e": 10817, "s": 10672, "text": "Suppose you downloaded the Solr fie and extracted it in onto the C drive. In such case, you can start Solr as shown in the following screenshot." }, { "code": null, "e": 10884, "s": 10817, "text": "To verify the installation, use the following URL in your browser." }, { "code": null, "e": 10907, "s": 10884, "text": "http://localhost:8983/" }, { "code": null, "e": 11039, "s": 10907, "text": "If the installation process is successful, then you will get to see the dashboard of the Apache Solr user interface as shown below." }, { "code": null, "e": 11195, "s": 11039, "text": "We can also communicate with Apache Solr using Java libraries; but before accessing Solr using Java API, you need to set the classpath for those libraries." }, { "code": null, "e": 11303, "s": 11195, "text": "Set the classpath to Solr libraries in the .bashrc file. Open .bashrc in any of the editors as shown below." }, { "code": null, "e": 11322, "s": 11303, "text": "$ gedit ~/.bashrc\n" }, { "code": null, "e": 11393, "s": 11322, "text": "Set classpath for Solr libraries (lib folder in HBase) as shown below." }, { "code": null, "e": 11449, "s": 11393, "text": "export CLASSPATH = $CLASSPATH://home/hadoop/Solr/lib/*\n" }, { "code": null, "e": 11542, "s": 11449, "text": "This is to prevent the “class not found” exception while accessing the HBase using Java API." }, { "code": null, "e": 11774, "s": 11542, "text": "Solr can be used along with Hadoop. As Hadoop handles a large amount of data, Solr helps us in finding the required information from such a large source. In this section, let us understand how you can install Hadoop on your system." }, { "code": null, "e": 11852, "s": 11774, "text": "Given below are the steps to be followed to download Hadoop onto your system." }, { "code": null, "e": 12007, "s": 11852, "text": "Step 1 − Go to the homepage of Hadoop. You can use the link − www.hadoop.apache.org/. Click the link Releases, as highlighted in the following screenshot." }, { "code": null, "e": 12166, "s": 12007, "text": "It will redirect you to the Apache Hadoop Releases page which contains links for mirrors of source and binary files of various versions of Hadoop as follows −" }, { "code": null, "e": 12390, "s": 12166, "text": "Step 2 − Select the latest version of Hadoop (in our tutorial, it is 2.6.4) and click its binary link. It will take you to a page where mirrors for Hadoop binary are available. Click one of these mirrors to download Hadoop." }, { "code": null, "e": 12435, "s": 12390, "text": "Open Linux terminal and login as super-user." }, { "code": null, "e": 12453, "s": 12435, "text": "$ su \npassword: \n" }, { "code": null, "e": 12600, "s": 12453, "text": "Go to the directory where you need to install Hadoop, and save the file there using the link copied earlier, as shown in the following code block." }, { "code": null, "e": 12713, "s": 12600, "text": "# cd /usr/local \n# wget http://redrockdigimark.com/apachemirror/hadoop/common/hadoop-\n2.6.4/hadoop-2.6.4.tar.gz\n" }, { "code": null, "e": 12780, "s": 12713, "text": "After downloading Hadoop, extract it using the following commands." }, { "code": null, "e": 12870, "s": 12780, "text": "# tar zxvf hadoop-2.6.4.tar.gz \n# mkdir hadoop \n# mv hadoop-2.6.4/* to hadoop/ \n# exit \n" }, { "code": null, "e": 12945, "s": 12870, "text": "Follow the steps given below to install Hadoop in pseudo-distributed mode." }, { "code": null, "e": 13045, "s": 12945, "text": "You can set the Hadoop environment variables by appending the following commands to ~/.bashrc file." }, { "code": null, "e": 13397, "s": 13045, "text": "export HADOOP_HOME = /usr/local/hadoop export\nHADOOP_MAPRED_HOME = $HADOOP_HOME export\nHADOOP_COMMON_HOME = $HADOOP_HOME export \nHADOOP_HDFS_HOME = $HADOOP_HOME export \nYARN_HOME = $HADOOP_HOME \nexport HADOOP_COMMON_LIB_NATIVE_DIR = $HADOOP_HOME/lib/native \nexport PATH = $PATH:$HADOOP_HOME/sbin:$HADOOP_HOME/bin \nexport HADOOP_INSTALL = $HADOOP_HOME\n" }, { "code": null, "e": 13458, "s": 13397, "text": "Next, apply all the changes into the current running system." }, { "code": null, "e": 13478, "s": 13458, "text": "$ source ~/.bashrc\n" }, { "code": null, "e": 13670, "s": 13478, "text": "You can find all the Hadoop configuration files in the location “$HADOOP_HOME/etc/hadoop”. It is required to make changes in those configuration files according to your Hadoop infrastructure." }, { "code": null, "e": 13700, "s": 13670, "text": "$ cd $HADOOP_HOME/etc/hadoop\n" }, { "code": null, "e": 13887, "s": 13700, "text": "In order to develop Hadoop programs in Java, you have to reset the Java environment variables in hadoop-env.sh file by replacing JAVA_HOME value with the location of Java in your system." }, { "code": null, "e": 13930, "s": 13887, "text": "export JAVA_HOME = /usr/local/jdk1.7.0_71\n" }, { "code": null, "e": 14010, "s": 13930, "text": "The following are the list of files that you have to edit to configure Hadoop −" }, { "code": null, "e": 14024, "s": 14010, "text": "core-site.xml" }, { "code": null, "e": 14038, "s": 14024, "text": "hdfs-site.xml" }, { "code": null, "e": 14052, "s": 14038, "text": "yarn-site.xml" }, { "code": null, "e": 14068, "s": 14052, "text": "mapred-site.xml" }, { "code": null, "e": 14082, "s": 14068, "text": "core-site.xml" }, { "code": null, "e": 14281, "s": 14082, "text": "The core-site.xml file contains information such as the port number used for Hadoop instance, memory allocated for the file system, memory limit for storing the data, and size of Read/Write buffers." }, { "code": null, "e": 14388, "s": 14281, "text": "Open the core-site.xml and add the following properties inside the <configuration>, </configuration> tags." }, { "code": null, "e": 14544, "s": 14388, "text": "<configuration> \n <property> \n <name>fs.default.name</name> \n <value>hdfs://localhost:9000</value> \n </property> \n</configuration> " }, { "code": null, "e": 14558, "s": 14544, "text": "hdfs-site.xml" }, { "code": null, "e": 14773, "s": 14558, "text": "The hdfs-site.xml file contains information such as the value of replication data, namenode path, and datanode paths of your local file systems. It means the place where you want to store the Hadoop infrastructure." }, { "code": null, "e": 14807, "s": 14773, "text": "Let us assume the following data." }, { "code": null, "e": 15173, "s": 14807, "text": "dfs.replication (data replication value) = 1 \n\n(In the below given path /hadoop/ is the user name. \nhadoopinfra/hdfs/namenode is the directory created by hdfs file system.) \nnamenode path = //home/hadoop/hadoopinfra/hdfs/namenode \n\n(hadoopinfra/hdfs/datanode is the directory created by hdfs file system.) \ndatanode path = //home/hadoop/hadoopinfra/hdfs/datanode\n" }, { "code": null, "e": 15272, "s": 15173, "text": "Open this file and add the following properties inside the <configuration>, </configuration> tags." }, { "code": null, "e": 15702, "s": 15272, "text": "<configuration> \n <property> \n <name>dfs.replication</name> \n <value>1</value> \n </property> \n \n <property> \n <name>dfs.name.dir</name> \n <value>file:///home/hadoop/hadoopinfra/hdfs/namenode</value> \n </property> \n \n <property> \n <name>dfs.data.dir</name> \n <value>file:///home/hadoop/hadoopinfra/hdfs/datanode</value> \n </property> \n</configuration> " }, { "code": null, "e": 15835, "s": 15702, "text": "Note − In the above file, all the property values are user-defined and you can make changes according to your Hadoop infrastructure." }, { "code": null, "e": 15849, "s": 15835, "text": "yarn-site.xml" }, { "code": null, "e": 16027, "s": 15849, "text": "This file is used to configure yarn into Hadoop. Open the yarn-site.xml file and add the following properties in between the <configuration>, </configuration> tags in this file." }, { "code": null, "e": 16193, "s": 16027, "text": "<configuration> \n <property> \n <name>yarn.nodemanager.aux-services</name> \n <value>mapreduce_shuffle</value> \n </property> \n</configuration> " }, { "code": null, "e": 16209, "s": 16193, "text": "mapred-site.xml" }, { "code": null, "e": 16464, "s": 16209, "text": "This file is used to specify which MapReduce framework we are using. By default, Hadoop contains a template of yarn-site.xml. First of all, it is required to copy the file from mapred-site,xml.template to mapred-site.xml file using the following command." }, { "code": null, "e": 16511, "s": 16464, "text": "$ cp mapred-site.xml.template mapred-site.xml\n" }, { "code": null, "e": 16621, "s": 16511, "text": "Open mapred-site.xml file and add the following properties inside the <configuration>, </configuration> tags." }, { "code": null, "e": 16769, "s": 16621, "text": "<configuration> \n <property> \n <name>mapreduce.framework.name</name> \n <value>yarn</value> \n </property> \n</configuration> " }, { "code": null, "e": 16833, "s": 16769, "text": "The following steps are used to verify the Hadoop installation." }, { "code": null, "e": 16907, "s": 16833, "text": "Set up the namenode using the command \"hdfs namenode –format\" as follows." }, { "code": null, "e": 16941, "s": 16907, "text": "$ cd ~ \n$ hdfs namenode -format \n" }, { "code": null, "e": 16976, "s": 16941, "text": "The expected result is as follows." }, { "code": null, "e": 17788, "s": 16976, "text": "10/24/14 21:30:55 INFO namenode.NameNode: STARTUP_MSG: \n/************************************************************ \nSTARTUP_MSG: Starting NameNode \nSTARTUP_MSG: host = localhost/192.168.1.11 \nSTARTUP_MSG: args = [-format] STARTUP_MSG: version = 2.6.4 \n... \n... \n10/24/14 21:30:56 INFO common.Storage: Storage directory \n/home/hadoop/hadoopinfra/hdfs/namenode has been successfully formatted. \n10/24/14 21:30:56 INFO namenode.NNStorageRetentionManager: Going to retain 1 \nimages with txid >= 0 \n10/24/14 21:30:56 INFO util.ExitUtil: Exiting with status 0 \n10/24/14 21:30:56 INFO namenode.NameNode: SHUTDOWN_MSG: \n/************************************************************ \nSHUTDOWN_MSG: Shutting down NameNode at localhost/192.168.1.11 \n************************************************************/ \n" }, { "code": null, "e": 17902, "s": 17788, "text": "The following command is used to start the Hadoop dfs. Executing this command will start your Hadoop file system." }, { "code": null, "e": 17919, "s": 17902, "text": "$ start-dfs.sh \n" }, { "code": null, "e": 17955, "s": 17919, "text": "The expected output is as follows −" }, { "code": null, "e": 18272, "s": 17955, "text": "10/24/14 21:37:56 \nStarting namenodes on [localhost] \nlocalhost: starting namenode, logging to /home/hadoop/hadoop-2.6.4/logs/hadoop-\nhadoop-namenode-localhost.out \nlocalhost: starting datanode, logging to /home/hadoop/hadoop-2.6.4/logs/hadoop-\nhadoop-datanode-localhost.out \nStarting secondary namenodes [0.0.0.0] \n" }, { "code": null, "e": 18380, "s": 18272, "text": "The following command is used to start the Yarn script. Executing this command will start your Yarn demons." }, { "code": null, "e": 18398, "s": 18380, "text": "$ start-yarn.sh \n" }, { "code": null, "e": 18431, "s": 18398, "text": "The expected output as follows −" }, { "code": null, "e": 18682, "s": 18431, "text": "starting yarn daemons \nstarting resourcemanager, logging to /home/hadoop/hadoop-2.6.4/logs/yarn-\nhadoop-resourcemanager-localhost.out \nlocalhost: starting nodemanager, logging to /home/hadoop/hadoop-\n2.6.4/logs/yarn-hadoop-nodemanager-localhost.out \n" }, { "code": null, "e": 18790, "s": 18682, "text": "The default port number to access Hadoop is 50070. Use the following URL to get Hadoop services on browser." }, { "code": null, "e": 18814, "s": 18790, "text": "http://localhost:50070/" }, { "code": null, "e": 18873, "s": 18814, "text": "Follow the steps given below to download and install Solr." }, { "code": null, "e": 18971, "s": 18873, "text": "Open the homepage of Apache Solr by clicking the following link − https://lucene.apache.org/solr/" }, { "code": null, "e": 19303, "s": 18971, "text": "Click the download button (highlighted in the above screenshot). On clicking, you will be redirected to the page where you have various mirrors of Apache Solr. Select a mirror and click on it, which will redirect you to a page where you can download the source and binary files of Apache Solr, as shown in the following screenshot." }, { "code": null, "e": 19452, "s": 19303, "text": "On clicking, a folder named Solr-6.2.0.tqz will be downloaded in the downloads folder of your system. Extract the contents of the downloaded folder." }, { "code": null, "e": 19577, "s": 19452, "text": "Create a folder named Solr in the Hadoop home directory and move the contents of the extracted folder to it, as shown below." }, { "code": null, "e": 19639, "s": 19577, "text": "$ mkdir Solr \n$ cd Downloads \n$ mv Solr-6.2.0 /home/Hadoop/ \n" }, { "code": null, "e": 19784, "s": 19639, "text": "Browse through the bin folder of Solr Home directory and verify the installation using the version option, as shown in the following code block." }, { "code": null, "e": 19821, "s": 19784, "text": "$ cd bin/ \n$ ./Solr version \n6.2.0 \n" }, { "code": null, "e": 19873, "s": 19821, "text": "Open the .bashrc file using the following command −" }, { "code": null, "e": 19914, "s": 19873, "text": "[Hadoop@localhost ~]$ source ~/.bashrc \n" }, { "code": null, "e": 19981, "s": 19914, "text": "Now set the home and path directories for Apache Solr as follows −" }, { "code": null, "e": 20058, "s": 19981, "text": "export SOLR_HOME = /home/Hadoop/Solr \nexport PATH = $PATH:/$SOLR_HOME/bin/\n" }, { "code": null, "e": 20112, "s": 20058, "text": "Open the terminal and execute the following command −" }, { "code": null, "e": 20155, "s": 20112, "text": "[Hadoop@localhost Solr]$ source ~/.bashrc\n" }, { "code": null, "e": 20217, "s": 20155, "text": "Now, you can execute the commands of Solr from any directory." }, { "code": null, "e": 20368, "s": 20217, "text": "In this chapter, we will discuss the architecture of Apache Solr. The following illustration shows a block diagram of the architecture of Apache Solr." }, { "code": null, "e": 20438, "s": 20368, "text": "Following are the major building blocks (components) of Apache Solr −" }, { "code": null, "e": 20797, "s": 20438, "text": "Request Handler − The requests we send to Apache Solr are processed by these request handlers. The requests might be query requests or index update requests. Based on our requirement, we need to select the request handler. To pass a request to Solr, we will generally map the handler to a certain URI end-point and the specified request will be served by it." }, { "code": null, "e": 21156, "s": 20797, "text": "Request Handler − The requests we send to Apache Solr are processed by these request handlers. The requests might be query requests or index update requests. Based on our requirement, we need to select the request handler. To pass a request to Solr, we will generally map the handler to a certain URI end-point and the specified request will be served by it." }, { "code": null, "e": 21435, "s": 21156, "text": "Search Component − A search component is a type (feature) of search provided in Apache Solr. It might be spell checking, query, faceting, hit highlighting, etc. These search components are registered as search handlers. Multiple components can be registered to a search handler." }, { "code": null, "e": 21714, "s": 21435, "text": "Search Component − A search component is a type (feature) of search provided in Apache Solr. It might be spell checking, query, faceting, hit highlighting, etc. These search components are registered as search handlers. Multiple components can be registered to a search handler." }, { "code": null, "e": 21931, "s": 21714, "text": "Query Parser − The Apache Solr query parser parses the queries that we pass to Solr and verifies the queries for syntactical errors. After parsing the queries, it translates them to a format which Lucene understands." }, { "code": null, "e": 22148, "s": 21931, "text": "Query Parser − The Apache Solr query parser parses the queries that we pass to Solr and verifies the queries for syntactical errors. After parsing the queries, it translates them to a format which Lucene understands." }, { "code": null, "e": 22397, "s": 22148, "text": "Response Writer − A response writer in Apache Solr is the component which generates the formatted output for the user queries. Solr supports response formats such as XML, JSON, CSV, etc. We have different response writers for each type of response." }, { "code": null, "e": 22646, "s": 22397, "text": "Response Writer − A response writer in Apache Solr is the component which generates the formatted output for the user queries. Solr supports response formats such as XML, JSON, CSV, etc. We have different response writers for each type of response." }, { "code": null, "e": 22965, "s": 22646, "text": "Analyzer/tokenizer − Lucene recognizes data in the form of tokens. Apache Solr analyzes the content, divides it into tokens, and passes these tokens to Lucene. An analyzer in Apache Solr examines the text of fields and generates a token stream. A tokenizer breaks the token stream prepared by the analyzer into tokens." }, { "code": null, "e": 23284, "s": 22965, "text": "Analyzer/tokenizer − Lucene recognizes data in the form of tokens. Apache Solr analyzes the content, divides it into tokens, and passes these tokens to Lucene. An analyzer in Apache Solr examines the text of fields and generates a token stream. A tokenizer breaks the token stream prepared by the analyzer into tokens." }, { "code": null, "e": 23581, "s": 23284, "text": "Update Request Processor − Whenever we send an update request to Apache Solr, the request is run through a set of plugins (signature, logging, indexing), collectively known as update request processor. This processor is responsible for modifications such as dropping a field, adding a field, etc." }, { "code": null, "e": 23878, "s": 23581, "text": "Update Request Processor − Whenever we send an update request to Apache Solr, the request is run through a set of plugins (signature, logging, indexing), collectively known as update request processor. This processor is responsible for modifications such as dropping a field, adding a field, etc." }, { "code": null, "e": 24007, "s": 23878, "text": "In this chapter, we will try to understand the real meaning of some of the terms that are frequently used while working on Solr." }, { "code": null, "e": 24096, "s": 24007, "text": "The following is a list of general terms that are used across all types of Solr setups −" }, { "code": null, "e": 24374, "s": 24096, "text": "Instance − Just like a tomcat instance or a jetty instance, this term refers to the application server, which runs inside a JVM. The home directory of Solr provides reference to each of these Solr instances, in which one or more cores can be configured to run in each instance." }, { "code": null, "e": 24652, "s": 24374, "text": "Instance − Just like a tomcat instance or a jetty instance, this term refers to the application server, which runs inside a JVM. The home directory of Solr provides reference to each of these Solr instances, in which one or more cores can be configured to run in each instance." }, { "code": null, "e": 24809, "s": 24652, "text": "Core − While running multiple indexes in your application, you can have multiple cores in each instance, instead of multiple instances each having one core." }, { "code": null, "e": 24966, "s": 24809, "text": "Core − While running multiple indexes in your application, you can have multiple cores in each instance, instead of multiple instances each having one core." }, { "code": null, "e": 25125, "s": 24966, "text": "Home − The term $SOLR_HOME refers to the home directory which has all the information regarding the cores and their indexes, configurations, and dependencies." }, { "code": null, "e": 25284, "s": 25125, "text": "Home − The term $SOLR_HOME refers to the home directory which has all the information regarding the cores and their indexes, configurations, and dependencies." }, { "code": null, "e": 25470, "s": 25284, "text": "Shard − In distributed environments, the data is partitioned between multiple Solr instances, where each chunk of data can be called as a Shard. It contains a subset of the whole index." }, { "code": null, "e": 25656, "s": 25470, "text": "Shard − In distributed environments, the data is partitioned between multiple Solr instances, where each chunk of data can be called as a Shard. It contains a subset of the whole index." }, { "code": null, "e": 25979, "s": 25656, "text": "In an earlier chapter, we discussed how to install Apache Solr in standalone mode. Note that we can also install Solr in distributed mode (cloud environment) where Solr is installed in a master-slave pattern. In distributed mode, the index is created on the master server and it is replicated to one or more slave servers." }, { "code": null, "e": 26037, "s": 25979, "text": "The key terms associated with Solr Cloud are as follows −" }, { "code": null, "e": 26111, "s": 26037, "text": "Node − In Solr cloud, each single instance of Solr is regarded as a node." }, { "code": null, "e": 26185, "s": 26111, "text": "Node − In Solr cloud, each single instance of Solr is regarded as a node." }, { "code": null, "e": 26262, "s": 26185, "text": "Cluster − All the nodes of the environment combined together make a cluster." }, { "code": null, "e": 26339, "s": 26262, "text": "Cluster − All the nodes of the environment combined together make a cluster." }, { "code": null, "e": 26413, "s": 26339, "text": "Collection − A cluster has a logical index that is known as a collection." }, { "code": null, "e": 26487, "s": 26413, "text": "Collection − A cluster has a logical index that is known as a collection." }, { "code": null, "e": 26577, "s": 26487, "text": "Shard − A shard is portion of the collection which has one or more replicas of the index." }, { "code": null, "e": 26667, "s": 26577, "text": "Shard − A shard is portion of the collection which has one or more replicas of the index." }, { "code": null, "e": 26750, "s": 26667, "text": "Replica − In Solr Core, a copy of shard that runs in a node is known as a replica." }, { "code": null, "e": 26833, "s": 26750, "text": "Replica − In Solr Core, a copy of shard that runs in a node is known as a replica." }, { "code": null, "e": 26949, "s": 26833, "text": "Leader − It is also a replica of shard, which distributes the requests of the Solr Cloud to the remaining replicas." }, { "code": null, "e": 27065, "s": 26949, "text": "Leader − It is also a replica of shard, which distributes the requests of the Solr Cloud to the remaining replicas." }, { "code": null, "e": 27215, "s": 27065, "text": "Zookeeper − It is an Apache project that Solr Cloud uses for centralized configuration and coordination, to manage the cluster and to elect a leader." }, { "code": null, "e": 27365, "s": 27215, "text": "Zookeeper − It is an Apache project that Solr Cloud uses for centralized configuration and coordination, to manage the cluster and to elect a leader." }, { "code": null, "e": 27426, "s": 27365, "text": "The main configuration files in Apache Solr are as follows −" }, { "code": null, "e": 27604, "s": 27426, "text": "Solr.xml − It is the file in the $SOLR_HOME directory that contains Solr Cloud related information. To load the cores, Solr refers to this file, which helps in identifying them." }, { "code": null, "e": 27782, "s": 27604, "text": "Solr.xml − It is the file in the $SOLR_HOME directory that contains Solr Cloud related information. To load the cores, Solr refers to this file, which helps in identifying them." }, { "code": null, "e": 27990, "s": 27782, "text": "Solrconfig.xml − This file contains the definitions and core-specific configurations related to request handling and response formatting, along with indexing, configuring, managing memory and making commits." }, { "code": null, "e": 28198, "s": 27990, "text": "Solrconfig.xml − This file contains the definitions and core-specific configurations related to request handling and response formatting, along with indexing, configuring, managing memory and making commits." }, { "code": null, "e": 28286, "s": 28198, "text": "Schema.xml − This file contains the whole schema along with the fields and field types." }, { "code": null, "e": 28374, "s": 28286, "text": "Schema.xml − This file contains the whole schema along with the fields and field types." }, { "code": null, "e": 28638, "s": 28374, "text": "Core.properties − This file contains the configurations specific to the core. It is referred for core discovery, as it contains the name of the core and path of the data directory. It can be used in any directory, which will then be treated as the core directory." }, { "code": null, "e": 28902, "s": 28638, "text": "Core.properties − This file contains the configurations specific to the core. It is referred for core discovery, as it contains the name of the core and path of the data directory. It can be used in any directory, which will then be treated as the core directory." }, { "code": null, "e": 29017, "s": 28902, "text": "After installing Solr, browse to the bin folder in Solr home directory and start Solr using the following command." }, { "code": null, "e": 29149, "s": 29017, "text": "[Hadoop@localhost ~]$ cd \n[Hadoop@localhost ~]$ cd Solr/ \n[Hadoop@localhost Solr]$ cd bin/ \n[Hadoop@localhost bin]$ ./Solr start\n" }, { "code": null, "e": 29253, "s": 29149, "text": "This command starts Solr in the background, listening on port 8983 by displaying the following message." }, { "code": null, "e": 29383, "s": 29253, "text": "Waiting up to 30 seconds to see Solr running on port 8983 [\\] \nStarted Solr server on port 8983 (pid = 6035). Happy searching!\n" }, { "code": null, "e": 29533, "s": 29383, "text": "If you start Solr using the start command, then Solr will start in the background. Instead, you can start Solr in the foreground using the –f option." }, { "code": null, "e": 31392, "s": 29533, "text": "[Hadoop@localhost bin]$ ./Solr start –f \n\n5823 INFO (coreLoadExecutor-6-thread-2) [ ] o.a.s.c.SolrResourceLoader \nAdding 'file:/home/Hadoop/Solr/contrib/extraction/lib/xmlbeans-2.6.0.jar' to \nclassloader \n5823 INFO (coreLoadExecutor-6-thread-2) [ ] o.a.s.c.SolrResourceLoader \nAdding 'file:/home/Hadoop/Solr/dist/Solr-cell-6.2.0.jar' to classloader \n5823 INFO (coreLoadExecutor-6-thread-2) [ ] o.a.s.c.SolrResourceLoader \nAdding 'file:/home/Hadoop/Solr/contrib/clustering/lib/carrot2-guava-18.0.jar' \nto classloader \n5823 INFO (coreLoadExecutor-6-thread-2) [ ] o.a.s.c.SolrResourceLoader \nAdding 'file:/home/Hadoop/Solr/contrib/clustering/lib/attributes-binder1.3.1.jar' \nto classloader \n5823 INFO (coreLoadExecutor-6-thread-2) [ ] o.a.s.c.SolrResourceLoader \nAdding 'file:/home/Hadoop/Solr/contrib/clustering/lib/simple-xml-2.7.1.jar' \nto classloader \n....................................................................................................................................................................................................................................... \n............................................................................................................................................................................................................................ \n12901 INFO (coreLoadExecutor-6-thread-1) [ x:Solr_sample] o.a.s.u.UpdateLog \nTook 24.0ms to seed version buckets with highest version 1546058939881226240 12902 \nINFO (coreLoadExecutor-6-thread-1) [ x:Solr_sample] \no.a.s.c.CoreContainer registering core: Solr_sample \n12904 INFO (coreLoadExecutor-6-thread-2) [ x:my_core] o.a.s.u.UpdateLog Took \n16.0ms to seed version buckets with highest version 1546058939894857728 \n12904 INFO (coreLoadExecutor-6-thread-2) [ x:my_core] o.a.s.c.CoreContainer \nregistering core: my_core \n" }, { "code": null, "e": 31503, "s": 31392, "text": "Using –p option of the start command, we can start Solr in another port, as shown in the following code block." }, { "code": null, "e": 31682, "s": 31503, "text": "[Hadoop@localhost bin]$ ./Solr start -p 8984 \n\nWaiting up to 30 seconds to see Solr running on port 8984 [-] \nStarted Solr server on port 8984 (pid = 10137). Happy searching!\n" }, { "code": null, "e": 31724, "s": 31682, "text": "You can stop Solr using the stop command." }, { "code": null, "e": 31739, "s": 31724, "text": "$ ./Solr stop\n" }, { "code": null, "e": 31801, "s": 31739, "text": "This command stops Solr, displaying a message as shown below." }, { "code": null, "e": 31923, "s": 31801, "text": "Sending stop command to Solr running on port 8983 ... waiting 5 seconds to \nallow Jetty process 6035 to stop gracefully.\n" }, { "code": null, "e": 32048, "s": 31923, "text": "The restart command of Solr stops Solr for 5 seconds and starts it again. You can restart Solr using the following command −" }, { "code": null, "e": 32065, "s": 32048, "text": "./Solr restart \n" }, { "code": null, "e": 32128, "s": 32065, "text": "This command restarts Solr, displaying the following message −" }, { "code": null, "e": 32385, "s": 32128, "text": "Sending stop command to Solr running on port 8983 ... waiting 5 seconds to \nallow Jetty process 6671 to stop gracefully. \nWaiting up to 30 seconds to see Solr running on port 8983 [|] [/] \nStarted Solr server on port 8983 (pid = 6906). Happy searching!\n" }, { "code": null, "e": 32477, "s": 32385, "text": "The help command of Solr can be used to check the usage of the Solr prompt and its options." }, { "code": null, "e": 33219, "s": 32477, "text": "[Hadoop@localhost bin]$ ./Solr -help \n\nUsage: Solr COMMAND OPTIONS \n where COMMAND is one of: start, stop, restart, status, healthcheck, \ncreate, create_core, create_collection, delete, version, zk \nStandalone server example (start Solr running in the background on port 8984): \n ./Solr start -p 8984 \nSolrCloud example (start Solr running in SolrCloud mode using localhost:2181 \nto connect to Zookeeper, with 1g max heap size and remote Java debug options enabled): \n ./Solr start -c -m 1g -z localhost:2181 -a \"-Xdebug -\n Xrunjdwp:transport = dt_socket,server = y,suspend = n,address = 1044\" \nPass -help after any COMMAND to see command-specific usage information, \nsuch as: ./Solr start -help or ./Solr stop -help \n" }, { "code": null, "e": 33420, "s": 33219, "text": "This status command of Solr can be used to search and find out the running Solr instances on your computer. It can provide you information about a Solr instance such as its version, memory usage, etc." }, { "code": null, "e": 33503, "s": 33420, "text": "You can check the status of a Solr instance, using the status command as follows −" }, { "code": null, "e": 33543, "s": 33503, "text": "[Hadoop@localhost bin]$ ./Solr status \n" }, { "code": null, "e": 33616, "s": 33543, "text": "On executing, the above command displays the status of Solr as follows −" }, { "code": null, "e": 33982, "s": 33616, "text": "Found 1 Solr nodes: \n\nSolr process 6906 running on port 8983 { \n \"Solr_home\":\"/home/Hadoop/Solr/server/Solr\", \n \"version\":\"6.2.0 764d0f19151dbff6f5fcd9fc4b2682cf934590c5 - \n mike - 2016-08-20 05:41:37\", \n \"startTime\":\"2016-09-20T06:00:02.877Z\", \n \"uptime\":\"0 days, 0 hours, 5 minutes, 14 seconds\", \n \"memory\":\"30.6 MB (%6.2) of 490.7 MB\"\n} \n" }, { "code": null, "e": 34091, "s": 33982, "text": "After starting Apache Solr, you can visit the homepage of the Solr web interface by using the following URL." }, { "code": null, "e": 34113, "s": 34091, "text": "Localhost:8983/Solr/\n" }, { "code": null, "e": 34162, "s": 34113, "text": "The interface of Solr Admin appears as follows −" }, { "code": null, "e": 34362, "s": 34162, "text": "A Solr Core is a running instance of a Lucene index that contains all the Solr configuration files required to use it. We need to create a Solr Core to perform operations like indexing and analyzing." }, { "code": null, "e": 34495, "s": 34362, "text": "A Solr application may contain one or multiple cores. If necessary, two cores in a Solr application can communicate with each other." }, { "code": null, "e": 34586, "s": 34495, "text": "After installing and starting Solr, you can connect to the client (web interface) of Solr." }, { "code": null, "e": 34722, "s": 34586, "text": "As highlighted in the following screenshot, initially there are no cores in Apache Solr. Now, we will see how to create a core in Solr." }, { "code": null, "e": 34822, "s": 34722, "text": "One way to create a core is to create a schema-less core using the create command, as shown below −" }, { "code": null, "e": 34877, "s": 34822, "text": "[Hadoop@localhost bin]$ ./Solr create -c Solr_sample \n" }, { "code": null, "e": 35010, "s": 34877, "text": "Here, we are trying to create a core named Solr_sample in Apache Solr. This command creates a core displaying the following message." }, { "code": null, "e": 35363, "s": 35010, "text": "Copying configuration to new core instance directory:\n/home/Hadoop/Solr/server/Solr/Solr_sample \n\nCreating new core 'Solr_sample' using command: \nhttp://localhost:8983/Solr/admin/cores?action=CREATE&name=Solr_sample&instanceD \nir = Solr_sample { \n \"responseHeader\":{ \n \"status\":0, \n \"QTime\":11550\n }, \n \"core\":\"Solr_sample\" \n} \n" }, { "code": null, "e": 35554, "s": 35363, "text": "You can create multiple cores in Solr. On the left-hand side of the Solr Admin, you can see a core selector where you can select the newly created core, as shown in the following screenshot." }, { "code": null, "e": 35663, "s": 35554, "text": "Alternatively, you can create a core using the create_core command. This command has the following options −" }, { "code": null, "e": 35764, "s": 35663, "text": "Let’s see how you can use the create_core command. Here, we will try to create a core named my_core." }, { "code": null, "e": 35820, "s": 35764, "text": "[Hadoop@localhost bin]$ ./Solr create_core -c my_core \n" }, { "code": null, "e": 35902, "s": 35820, "text": "On executing, the above command creates a core displaying the following message −" }, { "code": null, "e": 36230, "s": 35902, "text": "Copying configuration to new core instance directory: \n/home/Hadoop/Solr/server/Solr/my_core \n\nCreating new core 'my_core' using command: \nhttp://localhost:8983/Solr/admin/cores?action=CREATE&name=my_core&instanceD\nir = my_core { \n \"responseHeader\":{ \n \"status\":0, \n \"QTime\":1346\n }, \n \"core\":\"my_core\" \n}\n" }, { "code": null, "e": 36383, "s": 36230, "text": "You can delete a core using the delete command of Apache Solr. Let’s suppose we have a core named my_core in Solr, as shown in the following screenshot." }, { "code": null, "e": 36494, "s": 36383, "text": "You can delete this core using the delete command by passing the name of the core to this command as follows −" }, { "code": null, "e": 36545, "s": 36494, "text": "[Hadoop@localhost bin]$ ./Solr delete -c my_core \n" }, { "code": null, "e": 36646, "s": 36545, "text": "On executing the above command, the specified core will be deleted displaying the following message." }, { "code": null, "e": 36905, "s": 36646, "text": "Deleting core 'my_core' using command: \nhttp://localhost:8983/Solr/admin/cores?action=UNLOAD&core = my_core&deleteIndex\n = true&deleteDataDir = true&deleteInstanceDir = true {\n \n \"responseHeader\" :{ \n \"status\":0, \n \"QTime\":170\n }\n} \n" }, { "code": null, "e": 36996, "s": 36905, "text": "You can open the web interface of Solr to verify whether the core has been deleted or not." }, { "code": null, "e": 37144, "s": 36996, "text": "In general, indexing is an arrangement of documents or (other entities) systematically. Indexing enables users to locate information in a document." }, { "code": null, "e": 37193, "s": 37144, "text": "Indexing collects, parses, and stores documents." }, { "code": null, "e": 37242, "s": 37193, "text": "Indexing collects, parses, and stores documents." }, { "code": null, "e": 37350, "s": 37242, "text": "Indexing is done to increase the speed and performance of a search query while finding a required document." }, { "code": null, "e": 37458, "s": 37350, "text": "Indexing is done to increase the speed and performance of a search query while finding a required document." }, { "code": null, "e": 37609, "s": 37458, "text": "In Apache Solr, we can index (add, delete, modify) various document formats such as xml, csv, pdf, etc. We can add data to Solr index in several ways." }, { "code": null, "e": 37661, "s": 37609, "text": "In this chapter, we are going to discuss indexing −" }, { "code": null, "e": 37691, "s": 37661, "text": "Using the Solr Web Interface." }, { "code": null, "e": 37744, "s": 37691, "text": "Using any of the client APIs like Java, Python, etc." }, { "code": null, "e": 37765, "s": 37744, "text": "Using the post tool." }, { "code": null, "e": 37918, "s": 37765, "text": "In this chapter, we will discuss how to add data to the index of Apache Solr using various interfaces (command line, web interface, and Java client API)" }, { "code": null, "e": 38063, "s": 37918, "text": "Solr has a post command in its bin/ directory. Using this command, you can index various formats of files such as JSON, XML, CSV in Apache Solr." }, { "code": null, "e": 38196, "s": 38063, "text": "Browse through the bin directory of Apache Solr and execute the –h option of the post command, as shown in the following code block." }, { "code": null, "e": 38270, "s": 38196, "text": "[Hadoop@localhost bin]$ cd $SOLR_HOME \n[Hadoop@localhost bin]$ ./post -h\n" }, { "code": null, "e": 38370, "s": 38270, "text": "On executing the above command, you will get a list of options of the post command, as shown below." }, { "code": null, "e": 39943, "s": 38370, "text": "Usage: post -c <collection> [OPTIONS] <files|directories|urls|-d [\"..\"]> \nor post –help \n collection name defaults to DEFAULT_SOLR_COLLECTION if not specified \nOPTIONS \n======= \nSolr options: \n -url <base Solr update URL> (overrides collection, host, and port) \n -host <host> (default: localhost) \n -p or -port <port> (default: 8983) \n -commit yes|no (default: yes) \n\nWeb crawl options: \n -recursive <depth> (default: 1) \n -delay <seconds> (default: 10) \n\nDirectory crawl options: \n -delay <seconds> (default: 0) \n\nstdin/args options: \n -type <content/type> (default: application/xml) \n\nOther options: \n -filetypes <type>[,<type>,...] (default: \n xml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots,\n rtf,htm,html,txt,log) \n -params \"<key> = <value>[&<key> = <value>...]\" (values must be \n URL-encoded; these pass through to Solr update request) \n -out yes|no (default: no; yes outputs Solr response to console) \n -format Solr (sends application/json content as Solr commands \n to /update instead of /update/json/docs) \n\nExamples: \n* JSON file:./post -c wizbang events.json \n* XML files: ./post -c records article*.xml \n* CSV file: ./post -c signals LATEST-signals.csv \n* Directory of files: ./post -c myfiles ~/Documents \n* Web crawl: ./post -c gettingstarted http://lucene.apache.org/Solr -recursive 1 -delay 1 \n* Standard input (stdin): echo '{commit: {}}' | ./post -c my_collection -\ntype application/json -out yes –d \n* Data as string: ./post -c signals -type text/csv -out yes -d $'id,value\\n1,0.47'\n" }, { "code": null, "e": 40034, "s": 39943, "text": "Suppose we have a file named sample.csv with the following content (in the bin directory)." }, { "code": null, "e": 40264, "s": 40034, "text": "The above dataset contains personal details like Student id, first name, last name, phone, and city. The CSV file of the dataset is shown below. Here, you must note that you need to mention the schema, documenting its first line." }, { "code": null, "e": 40679, "s": 40264, "text": "id, first_name, last_name, phone_no, location \n001, Pruthvi, Reddy, 9848022337, Hyderabad \n002, kasyap, Sastry, 9848022338, Vishakapatnam \n003, Rajesh, Khanna, 9848022339, Delhi \n004, Preethi, Agarwal, 9848022330, Pune \n005, Trupthi, Mohanty, 9848022336, Bhubaneshwar \n006, Archana, Mishra, 9848022335, Chennai\n" }, { "code": null, "e": 40772, "s": 40679, "text": "You can index this data under the core named sample_Solr using the post command as follows −" }, { "code": null, "e": 40831, "s": 40772, "text": "[Hadoop@localhost bin]$ ./post -c Solr_sample sample.csv \n" }, { "code": null, "e": 40952, "s": 40831, "text": "On executing the above command, the given document is indexed under the specified core, generating the following output." }, { "code": null, "e": 41555, "s": 40952, "text": "/home/Hadoop/java/bin/java -classpath /home/Hadoop/Solr/dist/Solr-core\n6.2.0.jar -Dauto = yes -Dc = Solr_sample -Ddata = files \norg.apache.Solr.util.SimplePostTool sample.csv \nSimplePostTool version 5.0.0 \nPosting files to [base] url http://localhost:8983/Solr/Solr_sample/update... \nEntering auto mode. File endings considered are \nxml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots,rtf,\nhtm,html,txt,log \nPOSTing file sample.csv (text/csv) to [base] \n1 files indexed. \nCOMMITting Solr index changes to \nhttp://localhost:8983/Solr/Solr_sample/update... \nTime spent: 0:00:00.228\n" }, { "code": null, "e": 41615, "s": 41555, "text": "Visit the homepage of Solr Web UI using the following URL −" }, { "code": null, "e": 41638, "s": 41615, "text": "http://localhost:8983/" }, { "code": null, "e": 41822, "s": 41638, "text": "Select the core Solr_sample. By default, the request handler is /select and the query is “:”. Without doing any modifications, click the ExecuteQuery button at the bottom of the page." }, { "code": null, "e": 41967, "s": 41822, "text": "On executing the query, you can observe the contents of the indexed CSV document in JSON format (default), as shown in the following screenshot." }, { "code": null, "e": 42053, "s": 41967, "text": "Note − In the same way, you can index other file formats such as JSON, XML, CSV, etc." }, { "code": null, "e": 42177, "s": 42053, "text": "You can also index documents using the web interface provided by Solr. Let us see how to index the following JSON document." }, { "code": null, "e": 42622, "s": 42177, "text": "[ \n { \n \"id\" : \"001\", \n \"name\" : \"Ram\", \n \"age\" : 53, \n \"Designation\" : \"Manager\", \n \"Location\" : \"Hyderabad\", \n }, \n { \n \"id\" : \"002\", \n \"name\" : \"Robert\", \n \"age\" : 43, \n \"Designation\" : \"SR.Programmer\", \n \"Location\" : \"Chennai\", \n }, \n { \n \"id\" : \"003\", \n \"name\" : \"Rahim\", \n \"age\" : 25, \n \"Designation\" : \"JR.Programmer\", \n \"Location\" : \"Delhi\", \n } \n] " }, { "code": null, "e": 42672, "s": 42622, "text": "Open Solr web interface using the following URL −" }, { "code": null, "e": 42695, "s": 42672, "text": "http://localhost:8983/" }, { "code": null, "e": 42702, "s": 42695, "text": "Step 2" }, { "code": null, "e": 42906, "s": 42702, "text": "Select the core Solr_sample. By default, the values of the fields Request Handler, Common Within, Overwrite, and Boost are /update, 1000, true, and 1.0 respectively, as shown in the following screenshot." }, { "code": null, "e": 43098, "s": 42906, "text": "Now, choose the document format you want from JSON, CSV, XML, etc. Type the document to be indexed in the text area and click the Submit Document button, as shown in the following screenshot." }, { "code": null, "e": 43227, "s": 43098, "text": "Following is the Java program to add documents to Apache Solr index. Save this code in a file with the name AddingDocument.java." }, { "code": null, "e": 44226, "s": 43227, "text": "import java.io.IOException; \n\nimport org.apache.Solr.client.Solrj.SolrClient; \nimport org.apache.Solr.client.Solrj.SolrServerException; \nimport org.apache.Solr.client.Solrj.impl.HttpSolrClient; \nimport org.apache.Solr.common.SolrInputDocument; \n\npublic class AddingDocument { \n public static void main(String args[]) throws Exception { \n //Preparing the Solr client \n String urlString = \"http://localhost:8983/Solr/my_core\"; \n SolrClient Solr = new HttpSolrClient.Builder(urlString).build(); \n \n //Preparing the Solr document \n SolrInputDocument doc = new SolrInputDocument(); \n \n //Adding fields to the document \n doc.addField(\"id\", \"003\"); \n doc.addField(\"name\", \"Rajaman\"); \n doc.addField(\"age\",\"34\"); \n doc.addField(\"addr\",\"vishakapatnam\"); \n \n //Adding the document to Solr \n Solr.add(doc); \n \n //Saving the changes \n Solr.commit(); \n System.out.println(\"Documents added\"); \n } \n}" }, { "code": null, "e": 44303, "s": 44226, "text": "Compile the above code by executing the following commands in the terminal −" }, { "code": null, "e": 44395, "s": 44303, "text": "[Hadoop@localhost bin]$ javac AddingDocument \n[Hadoop@localhost bin]$ java AddingDocument \n" }, { "code": null, "e": 44462, "s": 44395, "text": "On executing the above command, you will get the following output." }, { "code": null, "e": 44479, "s": 44462, "text": "Documents added\n" }, { "code": null, "e": 44684, "s": 44479, "text": "In the previous chapter, we explained how to add data into Solr which is in JSON and .CSV file formats. In this chapter, we will demonstrate how to add data in Apache Solr index using XML document format." }, { "code": null, "e": 44767, "s": 44684, "text": "Suppose we need to add the following data to Solr index using the XML file format." }, { "code": null, "e": 44913, "s": 44767, "text": "To add the above data into Solr index, we need to prepare an XML document, as shown below. Save this document in a file with the name sample.xml." }, { "code": null, "e": 46431, "s": 44913, "text": "<add> \n <doc> \n <field name = \"id\">001</field> \n <field name = \"first name\">Rajiv</field> \n <field name = \"last name\">Reddy</field> \n <field name = \"phone\">9848022337</field> \n <field name = \"city\">Hyderabad</field> \n </doc> \n <doc> \n <field name = \"id\">002</field> \n <field name = \"first name\">Siddarth</field> \n <field name = \"last name\">Battacharya</field> \n <field name = \"phone\">9848022338</field> \n <field name = \"city\">Kolkata</field> \n </doc> \n <doc> \n <field name = \"id\">003</field> \n <field name = \"first name\">Rajesh</field> \n <field name = \"last name\">Khanna</field> \n <field name = \"phone\">9848022339</field> \n <field name = \"city\">Delhi</field> \n </doc> \n <doc> \n <field name = \"id\">004</field> \n <field name = \"first name\">Preethi</field> \n <field name = \"last name\">Agarwal</field> \n <field name = \"phone\">9848022330</field> \n <field name = \"city\">Pune</field> \n </doc> \n <doc> \n <field name = \"id\">005</field> \n <field name = \"first name\">Trupthi</field> \n <field name = \"last name\">Mohanthy</field> \n <field name = \"phone\">9848022336</field> \n <field name = \"city\">Bhuwaeshwar</field> \n </doc> \n <doc> \n <field name = \"id\">006</field> \n <field name = \"first name\">Archana</field> \n <field name = \"last name\">Mishra</field> \n <field name = \"phone\">9848022335</field> \n <field name = \"city\">Chennai</field> \n </doc> \n</add>" }, { "code": null, "e": 46583, "s": 46431, "text": "As you can observe, the XML file written to add data to index contains three important tags namely, <add> </add>, <doc></doc>, and < field >< /field >." }, { "code": null, "e": 46701, "s": 46583, "text": "add − This is the root tag for adding documents to the index. It contains one or more documents that are to be added." }, { "code": null, "e": 46819, "s": 46701, "text": "add − This is the root tag for adding documents to the index. It contains one or more documents that are to be added." }, { "code": null, "e": 46948, "s": 46819, "text": "doc − The documents we add should be wrapped within the <doc></doc> tags. This document contains the data in the form of fields." }, { "code": null, "e": 47077, "s": 46948, "text": "doc − The documents we add should be wrapped within the <doc></doc> tags. This document contains the data in the form of fields." }, { "code": null, "e": 47155, "s": 47077, "text": "field − The field tag holds the name and value of the fields of the document." }, { "code": null, "e": 47233, "s": 47155, "text": "field − The field tag holds the name and value of the fields of the document." }, { "code": null, "e": 47360, "s": 47233, "text": "After preparing the document, you can add this document to the index using any of the means discussed in the previous chapter." }, { "code": null, "e": 47535, "s": 47360, "text": "Suppose the XML file exists in the bin directory of Solr and it is to be indexed in the core named my_core, then you can add it to Solr index using the post tool as follows −" }, { "code": null, "e": 47589, "s": 47535, "text": "[Hadoop@localhost bin]$ ./post -c my_core sample.xml\n" }, { "code": null, "e": 47656, "s": 47589, "text": "On executing the above command, you will get the following output." }, { "code": null, "e": 48252, "s": 47656, "text": "/home/Hadoop/java/bin/java -classpath /home/Hadoop/Solr/dist/Solr-\ncore6.2.0.jar -Dauto = yes -Dc = my_core -Ddata = files \norg.apache.Solr.util.SimplePostTool sample.xml \nSimplePostTool version 5.0.0 \nPosting files to [base] url http://localhost:8983/Solr/my_core/update... \nEntering auto mode. File endings considered are xml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,\nxls,xlsx,odt,odp,ods,ott,otp,ots,rtf,htm,html,txt,log \nPOSTing file sample.xml (application/xml) to [base] \n1 files indexed. \nCOMMITting Solr index changes to http://localhost:8983/Solr/my_core/update... \nTime spent: 0:00:00.201\n" }, { "code": null, "e": 48510, "s": 48252, "text": "Visit the homepage of Apache Solr web interface and select the core my_core. Try to retrieve all the documents by passing the query “:” in the text area q and execute the query. On executing, you can observe that the desired data is added to the Solr index." }, { "code": null, "e": 48631, "s": 48510, "text": "Following is the XML file used to update a field in the existing document. Save this in a file with the name update.xml." }, { "code": null, "e": 48973, "s": 48631, "text": "<add> \n <doc> \n <field name = \"id\">001</field> \n <field name = \"first name\" update = \"set\">Raj</field> \n <field name = \"last name\" update = \"add\">Malhotra</field> \n <field name = \"phone\" update = \"add\">9000000000</field> \n <field name = \"city\" update = \"add\">Delhi</field> \n </doc> \n</add>" }, { "code": null, "e": 49150, "s": 48973, "text": "As you can observe, the XML file written to update data is just like the one which we use to add documents. But the only difference is we use the update attribute of the field." }, { "code": null, "e": 49259, "s": 49150, "text": "In our example, we will use the above document and try to update the fields of the document with the id 001." }, { "code": null, "e": 49441, "s": 49259, "text": "Suppose the XML document exists in the bin directory of Solr. Since we are updating the index which exists in the core named my_core, you can update using the post tool as follows −" }, { "code": null, "e": 49496, "s": 49441, "text": "[Hadoop@localhost bin]$ ./post -c my_core update.xml \n" }, { "code": null, "e": 49563, "s": 49496, "text": "On executing the above command, you will get the following output." }, { "code": null, "e": 50161, "s": 49563, "text": "/home/Hadoop/java/bin/java -classpath /home/Hadoop/Solr/dist/Solr-core\n6.2.0.jar -Dauto = yes -Dc = my_core -Ddata = files \norg.apache.Solr.util.SimplePostTool update.xml \nSimplePostTool version 5.0.0 \nPosting files to [base] url http://localhost:8983/Solr/my_core/update... \nEntering auto mode. File endings considered are \nxml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots,rtf,\nhtm,html,txt,log \nPOSTing file update.xml (application/xml) to [base] \n1 files indexed. \nCOMMITting Solr index changes to http://localhost:8983/Solr/my_core/update... \nTime spent: 0:00:00.159 \n" }, { "code": null, "e": 50402, "s": 50161, "text": "Visit the homepage of Apache Solr web interface and select the core as my_core. Try to retrieve all the documents by passing the query “:” in the text area q and execute the query. On executing, you can observe that the document is updated." }, { "code": null, "e": 50533, "s": 50402, "text": "Following is the Java program to add documents to Apache Solr index. Save this code in a file with the name UpdatingDocument.java." }, { "code": null, "e": 51943, "s": 50533, "text": "import java.io.IOException; \n\nimport org.apache.Solr.client.Solrj.SolrClient; \nimport org.apache.Solr.client.Solrj.SolrServerException; \nimport org.apache.Solr.client.Solrj.impl.HttpSolrClient; \nimport org.apache.Solr.client.Solrj.request.UpdateRequest; \nimport org.apache.Solr.client.Solrj.response.UpdateResponse;\nimport org.apache.Solr.common.SolrInputDocument; \n\npublic class UpdatingDocument { \n public static void main(String args[]) throws SolrServerException, IOException { \n //Preparing the Solr client \n String urlString = \"http://localhost:8983/Solr/my_core\"; \n SolrClient Solr = new HttpSolrClient.Builder(urlString).build(); \n \n //Preparing the Solr document \n SolrInputDocument doc = new SolrInputDocument(); \n \n UpdateRequest updateRequest = new UpdateRequest(); \n updateRequest.setAction( UpdateRequest.ACTION.COMMIT, false, false); \n SolrInputDocument myDocumentInstantlycommited = new SolrInputDocument(); \n \n myDocumentInstantlycommited.addField(\"id\", \"002\"); \n myDocumentInstantlycommited.addField(\"name\", \"Rahman\"); \n myDocumentInstantlycommited.addField(\"age\",\"27\"); \n myDocumentInstantlycommited.addField(\"addr\",\"hyderabad\"); \n \n updateRequest.add( myDocumentInstantlycommited); \n UpdateResponse rsp = updateRequest.process(Solr); \n System.out.println(\"Documents Updated\"); \n } \n}" }, { "code": null, "e": 52020, "s": 51943, "text": "Compile the above code by executing the following commands in the terminal −" }, { "code": null, "e": 52116, "s": 52020, "text": "[Hadoop@localhost bin]$ javac UpdatingDocument \n[Hadoop@localhost bin]$ java UpdatingDocument \n" }, { "code": null, "e": 52183, "s": 52116, "text": "On executing the above command, you will get the following output." }, { "code": null, "e": 52203, "s": 52183, "text": "Documents updated \n" }, { "code": null, "e": 52349, "s": 52203, "text": "To delete documents from the index of Apache Solr, we need to specify the ID’s of the documents to be deleted between the <delete></delete> tags." }, { "code": null, "e": 52442, "s": 52349, "text": "<delete> \n <id>003</id> \n <id>005</id> \n <id>004</id> \n <id>002</id> \n</delete> " }, { "code": null, "e": 52568, "s": 52442, "text": "Here, this XML code is used to delete the documents with ID’s 003 and 005. Save this code in a file with the name delete.xml." }, { "code": null, "e": 52735, "s": 52568, "text": "If you want to delete the documents from the index which belongs to the core named my_core, then you can post the delete.xml file using the post tool, as shown below." }, { "code": null, "e": 52790, "s": 52735, "text": "[Hadoop@localhost bin]$ ./post -c my_core delete.xml \n" }, { "code": null, "e": 52857, "s": 52790, "text": "On executing the above command, you will get the following output." }, { "code": null, "e": 53455, "s": 52857, "text": "/home/Hadoop/java/bin/java -classpath /home/Hadoop/Solr/dist/Solr-core\n6.2.0.jar -Dauto = yes -Dc = my_core -Ddata = files \norg.apache.Solr.util.SimplePostTool delete.xml \nSimplePostTool version 5.0.0 \nPosting files to [base] url http://localhost:8983/Solr/my_core/update... \nEntering auto mode. File endings considered are \nxml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots,\nrtf,htm,html,txt,log \nPOSTing file delete.xml (application/xml) to [base] \n1 files indexed. \nCOMMITting Solr index changes to http://localhost:8983/Solr/my_core/update... \nTime spent: 0:00:00.179 \n" }, { "code": null, "e": 53715, "s": 53455, "text": "Visit the homepage of the of Apache Solr web interface and select the core as my_core. Try to retrieve all the documents by passing the query “:” in the text area q and execute the query. On executing, you can observe that the specified documents are deleted." }, { "code": null, "e": 53860, "s": 53715, "text": "Sometimes we need to delete documents based on fields other than ID. For example, we may have to delete the documents where the city is Chennai." }, { "code": null, "e": 53964, "s": 53860, "text": "In such cases, you need to specify the name and value of the field within the <query></query> tag pair." }, { "code": null, "e": 54017, "s": 53964, "text": "<delete> \n <query>city:Chennai</query> \n</delete>\n" }, { "code": null, "e": 54133, "s": 54017, "text": "Save it as delete_field.xml and perform the delete operation on the core named my_core using the post tool of Solr." }, { "code": null, "e": 54194, "s": 54133, "text": "[Hadoop@localhost bin]$ ./post -c my_core delete_field.xml \n" }, { "code": null, "e": 54260, "s": 54194, "text": "On executing the above command, it produces the following output." }, { "code": null, "e": 54870, "s": 54260, "text": "/home/Hadoop/java/bin/java -classpath /home/Hadoop/Solr/dist/Solr-core\n6.2.0.jar -Dauto = yes -Dc = my_core -Ddata = files \norg.apache.Solr.util.SimplePostTool delete_field.xml \nSimplePostTool version 5.0.0 \nPosting files to [base] url http://localhost:8983/Solr/my_core/update... \nEntering auto mode. File endings considered are \nxml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots,\nrtf,htm,html,txt,log \nPOSTing file delete_field.xml (application/xml) to [base] \n1 files indexed. \nCOMMITting Solr index changes to http://localhost:8983/Solr/my_core/update... \nTime spent: 0:00:00.084 \n" }, { "code": null, "e": 55162, "s": 54870, "text": "Visit the homepage of the of Apache Solr web interface and select the core as my_core. Try to retrieve all the documents by passing the query “:” in the text area q and execute the query. On executing, you can observe that the documents containing the specified field value pair are deleted." }, { "code": null, "e": 55342, "s": 55162, "text": "Just like deleting a specific field, if you want to delete all the documents from an index, you just need to pass the symbol “:” between the tags <query></ query>, as shown below." }, { "code": null, "e": 55386, "s": 55342, "text": "<delete> \n <query>*:*</query> \n</delete>\n" }, { "code": null, "e": 55500, "s": 55386, "text": "Save it as delete_all.xml and perform the delete operation on the core named my_core using the post tool of Solr." }, { "code": null, "e": 55558, "s": 55500, "text": "[Hadoop@localhost bin]$ ./post -c my_core delete_all.xml\n" }, { "code": null, "e": 55624, "s": 55558, "text": "On executing the above command, it produces the following output." }, { "code": null, "e": 56227, "s": 55624, "text": "/home/Hadoop/java/bin/java -classpath /home/Hadoop/Solr/dist/Solr-core\n6.2.0.jar -Dauto = yes -Dc = my_core -Ddata = files \norg.apache.Solr.util.SimplePostTool deleteAll.xml \nSimplePostTool version 5.0.0 \nPosting files to [base] url http://localhost:8983/Solr/my_core/update... \nEntering auto mode. File endings considered are \nxml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots,rtf,\nhtm,html,txt,log \nPOSTing file deleteAll.xml (application/xml) to [base] \n1 files indexed. \nCOMMITting Solr index changes to http://localhost:8983/Solr/my_core/update... \nTime spent: 0:00:00.138\n" }, { "code": null, "e": 56512, "s": 56227, "text": "Visit the homepage of Apache Solr web interface and select the core as my_core. Try to retrieve all the documents by passing the query “:” in the text area q and execute the query. On executing, you can observe that the documents containing the specified field value pair are deleted." }, { "code": null, "e": 56643, "s": 56512, "text": "Following is the Java program to add documents to Apache Solr index. Save this code in a file with the name UpdatingDocument.java." }, { "code": null, "e": 57496, "s": 56643, "text": "import java.io.IOException; \n\nimport org.apache.Solr.client.Solrj.SolrClient; \nimport org.apache.Solr.client.Solrj.SolrServerException; \nimport org.apache.Solr.client.Solrj.impl.HttpSolrClient; \nimport org.apache.Solr.common.SolrInputDocument; \n\npublic class DeletingAllDocuments { \n public static void main(String args[]) throws SolrServerException, IOException {\n //Preparing the Solr client \n String urlString = \"http://localhost:8983/Solr/my_core\"; \n SolrClient Solr = new HttpSolrClient.Builder(urlString).build(); \n \n //Preparing the Solr document \n SolrInputDocument doc = new SolrInputDocument(); \n \n //Deleting the documents from Solr \n Solr.deleteByQuery(\"*\"); \n \n //Saving the document \n Solr.commit(); \n System.out.println(\"Documents deleted\"); \n } \n}" }, { "code": null, "e": 57573, "s": 57496, "text": "Compile the above code by executing the following commands in the terminal −" }, { "code": null, "e": 57676, "s": 57573, "text": "[Hadoop@localhost bin]$ javac DeletingAllDocuments \n[Hadoop@localhost bin]$ java DeletingAllDocuments\n" }, { "code": null, "e": 57743, "s": 57676, "text": "On executing the above command, you will get the following output." }, { "code": null, "e": 57762, "s": 57743, "text": "Documents deleted\n" }, { "code": null, "e": 57916, "s": 57762, "text": "In this chapter, we will discuss how to retrieve data using Java Client API. Suppose we have a .csv document named sample.csv with the following content." }, { "code": null, "e": 58036, "s": 57916, "text": "001,9848022337,Hyderabad,Rajiv,Reddy \n002,9848022338,Kolkata,Siddarth,Battacharya \n003,9848022339,Delhi,Rajesh,Khanna\n" }, { "code": null, "e": 58117, "s": 58036, "text": "You can index this data under the core named sample_Solr using the post command." }, { "code": null, "e": 58175, "s": 58117, "text": "[Hadoop@localhost bin]$ ./post -c Solr_sample sample.csv\n" }, { "code": null, "e": 58301, "s": 58175, "text": "Following is the Java program to add documents to Apache Solr index. Save this code in a file with named RetrievingData.java." }, { "code": null, "e": 59564, "s": 58301, "text": "import java.io.IOException; \n\nimport org.apache.Solr.client.Solrj.SolrClient; \nimport org.apache.Solr.client.Solrj.SolrQuery; \nimport org.apache.Solr.client.Solrj.SolrServerException; \nimport org.apache.Solr.client.Solrj.impl.HttpSolrClient; \nimport org.apache.Solr.client.Solrj.response.QueryResponse; \nimport org.apache.Solr.common.SolrDocumentList; \n\npublic class RetrievingData { \n public static void main(String args[]) throws SolrServerException, IOException { \n //Preparing the Solr client \n String urlString = \"http://localhost:8983/Solr/my_core\"; \n SolrClient Solr = new HttpSolrClient.Builder(urlString).build(); \n \n //Preparing Solr query \n SolrQuery query = new SolrQuery(); \n query.setQuery(\"*:*\"); \n \n //Adding the field to be retrieved \n query.addField(\"*\"); \n \n //Executing the query \n QueryResponse queryResponse = Solr.query(query); \n \n //Storing the results of the query \n SolrDocumentList docs = queryResponse.getResults(); \n System.out.println(docs); \n System.out.println(docs.get(0)); \n System.out.println(docs.get(1)); \n System.out.println(docs.get(2)); \n \n //Saving the operations \n Solr.commit(); \n } \n}" }, { "code": null, "e": 59641, "s": 59564, "text": "Compile the above code by executing the following commands in the terminal −" }, { "code": null, "e": 59732, "s": 59641, "text": "[Hadoop@localhost bin]$ javac RetrievingData \n[Hadoop@localhost bin]$ java RetrievingData\n" }, { "code": null, "e": 59799, "s": 59732, "text": "On executing the above command, you will get the following output." }, { "code": null, "e": 60707, "s": 59799, "text": "{numFound = 3,start = 0,docs = [SolrDocument{id=001, phone = [9848022337], \ncity = [Hyderabad], first_name = [Rajiv], last_name = [Reddy], \n_version_ = 1547262806014820352}, SolrDocument{id = 002, phone = [9848022338], \ncity = [Kolkata], first_name = [Siddarth], last_name = [Battacharya], \n\n_version_ = 1547262806026354688}, SolrDocument{id = 003, phone = [9848022339], \ncity = [Delhi], first_name = [Rajesh], last_name = [Khanna], \n\n_version_ = 1547262806029500416}]} \n\nSolrDocument{id = 001, phone = [9848022337], city = [Hyderabad], first_name = [Rajiv], \nlast_name = [Reddy], _version_ = 1547262806014820352} \n\nSolrDocument{id = 002, phone = [9848022338], city = [Kolkata], first_name = [Siddarth], \nlast_name = [Battacharya], _version_ = 1547262806026354688} \n\nSolrDocument{id = 003, phone = [9848022339], city = [Delhi], first_name = [Rajesh], \nlast_name = [Khanna], _version_ = 1547262806029500416}\n" }, { "code": null, "e": 60898, "s": 60707, "text": "In addition to storing data, Apache Solr also provides the facility of querying it back as and when required. Solr provides certain parameters using which we can query the data stored in it." }, { "code": null, "e": 60997, "s": 60898, "text": "In the following table, we have listed down the various query parameters available in Apache Solr." }, { "code": null, "e": 61220, "s": 60997, "text": "You can see all these parameters as options to query Apache Solr. Visit the homepage of Apache Solr. On the left-hand side of the page, click on the option Query. Here, you can see the fields for the parameters of a query." }, { "code": null, "e": 61604, "s": 61220, "text": "Assume we have 3 records in the core named my_core. To retrieve a particular record from the selected core, you need to pass the name and value pairs of the fields of a particular document. For example, if you want to retrieve the record with the value of the field id, you need to pass the name-value pair of the field as − Id:001 as value for the parameter q and execute the query." }, { "code": null, "e": 61752, "s": 61604, "text": "In the same way, you can retrieve all the records from an index by passing *:* as a value to the parameter q, as shown in the following screenshot." }, { "code": null, "e": 61889, "s": 61752, "text": "We can retrieve the records from the second record by passing 2 as a value to the parameter start, as shown in the following screenshot." }, { "code": null, "e": 62148, "s": 61889, "text": "You can restrict the number of records by specifying a value in the rows parameter. For example, we can restrict the total number of records in the result of the query to 2 by passing the value 2 into the parameter rows, as shown in the following screenshot." }, { "code": null, "e": 62262, "s": 62148, "text": "You can get the response in required document type by selecting one from the provided values of the parameter wt." }, { "code": null, "e": 62337, "s": 62262, "text": "In the above instance, we have chosen the .csv format to get the response." }, { "code": null, "e": 62502, "s": 62337, "text": "If we want to have particular fields in the resulted documents, we need to pass the list of the required fields, separated by commas, as a value to the property fl." }, { "code": null, "e": 62594, "s": 62502, "text": "In the following example, we are trying to retrieve the fields − id, phone, and first_name." }, { "code": null, "e": 62776, "s": 62594, "text": "Faceting in Apache Solr refers to the classification of the search results into various categories. In this chapter, we will discuss the types of faceting available in Apache Solr −" }, { "code": null, "e": 62891, "s": 62776, "text": "Query faceting − It returns the number of documents in the current search results that also match the given query." }, { "code": null, "e": 63006, "s": 62891, "text": "Query faceting − It returns the number of documents in the current search results that also match the given query." }, { "code": null, "e": 63095, "s": 63006, "text": "Date faceting − It returns the number of documents that fall within certain date ranges." }, { "code": null, "e": 63184, "s": 63095, "text": "Date faceting − It returns the number of documents that fall within certain date ranges." }, { "code": null, "e": 63308, "s": 63184, "text": "Faceting commands are added to any normal Solr query request, and the faceting counts come back in the same query response." }, { "code": null, "e": 63418, "s": 63308, "text": "Using the field faceting, we can retrieve the counts for all terms, or just the top terms in any given field." }, { "code": null, "e": 63518, "s": 63418, "text": "As an example, let us consider the following books.csv file that contains data about various books." }, { "code": null, "e": 64502, "s": 63518, "text": "id,cat,name,price,inStock,author,series_t,sequence_i,genre_s \n0553573403,book,A Game of Thrones,5.99,true,George R.R. Martin,\"A Song of Ice \nand Fire\",1,fantasy \n\n0553579908,book,A Clash of Kings,10.99,true,George R.R. Martin,\"A Song of Ice \nand Fire\",2,fantasy \n\n055357342X,book,A Storm of Swords,7.99,true,George R.R. Martin,\"A Song of Ice \nand Fire\",3,fantasy \n\n0553293354,book,Foundation,7.99,true,Isaac Asimov,Foundation Novels,1,scifi \n0812521390,book,The Black Company,4.99,false,Glen Cook,The Chronicles of The \nBlack Company,1,fantasy \n\n0812550706,book,Ender's Game,6.99,true,Orson Scott Card,Ender,1,scifi \n0441385532,book,Jhereg,7.95,false,Steven Brust,Vlad Taltos,1,fantasy \n0380014300,book,Nine Princes In Amber,6.99,true,Roger Zelazny,the Chronicles of \nAmber,1,fantasy \n\n0805080481,book,The Book of Three,5.99,true,Lloyd Alexander,The Chronicles of \nPrydain,1,fantasy \n\n080508049X,book,The Black Cauldron,5.99,true,Lloyd Alexander,The Chronicles of \nPrydain,2,fantasy\n" }, { "code": null, "e": 64562, "s": 64502, "text": "Let us post this file into Apache Solr using the post tool." }, { "code": null, "e": 64620, "s": 64562, "text": "[Hadoop@localhost bin]$ ./post -c Solr_sample sample.csv\n" }, { "code": null, "e": 64738, "s": 64620, "text": "On executing the above command, all the documents mentioned in the given .csv file will be uploaded into Apache Solr." }, { "code": null, "e": 64837, "s": 64738, "text": "Now let us execute a faceted query on the field author with 0 rows on the collection/core my_core." }, { "code": null, "e": 64971, "s": 64837, "text": "Open the web UI of Apache Solr and on the left-hand side of the page, check the checkbox facet, as shown in the following screenshot." }, { "code": null, "e": 65147, "s": 64971, "text": "On checking the checkbox, you will have three more text fields in order to pass the parameters of the facet search. Now, as parameters of the query, pass the following values." }, { "code": null, "e": 65189, "s": 65147, "text": "q = *:*, rows = 0, facet.field = author \n" }, { "code": null, "e": 65254, "s": 65189, "text": "Finally, execute the query by clicking the Execute Query button." }, { "code": null, "e": 65306, "s": 65254, "text": "On executing, it will produce the following result." }, { "code": null, "e": 65426, "s": 65306, "text": "It categorizes the documents in the index based on author and specifies the number of books contributed by each author." }, { "code": null, "e": 65556, "s": 65426, "text": "Following is the Java program to add documents to Apache Solr index. Save this code in a file with the name HitHighlighting.java." }, { "code": null, "e": 67669, "s": 65556, "text": "import java.io.IOException; \nimport java.util.List; \n\nimport org.apache.Solr.client.Solrj.SolrClient; \nimport org.apache.Solr.client.Solrj.SolrQuery; \nimport org.apache.Solr.client.Solrj.SolrServerException; \nimport org.apache.Solr.client.Solrj.impl.HttpSolrClient; \nimport org.apache.Solr.client.Solrj.request.QueryRequest; \nimport org.apache.Solr.client.Solrj.response.FacetField; \nimport org.apache.Solr.client.Solrj.response.FacetField.Count;\nimport org.apache.Solr.client.Solrj.response.QueryResponse; \nimport org.apache.Solr.common.SolrInputDocument; \n\npublic class HitHighlighting { \n public static void main(String args[]) throws SolrServerException, IOException { \n //Preparing the Solr client \n String urlString = \"http://localhost:8983/Solr/my_core\"; \n SolrClient Solr = new HttpSolrClient.Builder(urlString).build(); \n \n //Preparing the Solr document \n SolrInputDocument doc = new SolrInputDocument(); \n \n //String query = request.query; \n SolrQuery query = new SolrQuery(); \n \n //Setting the query string \n query.setQuery(\"*:*\"); \n \n //Setting the no.of rows \n query.setRows(0); \n \n //Adding the facet field \n query.addFacetField(\"author\"); \n \n //Creating the query request \n QueryRequest qryReq = new QueryRequest(query); \n \n //Creating the query response \n QueryResponse resp = qryReq.process(Solr); \n \n //Retrieving the response fields \n System.out.println(resp.getFacetFields()); \n \n List<FacetField> facetFields = resp.getFacetFields(); \n for (int i = 0; i > facetFields.size(); i++) { \n FacetField facetField = facetFields.get(i); \n List<Count> facetInfo = facetField.getValues(); \n \n for (FacetField.Count facetInstance : facetInfo) { \n System.out.println(facetInstance.getName() + \" : \" + \n facetInstance.getCount() + \" [drilldown qry:\" + \n facetInstance.getAsFilterQuery()); \n } \n System.out.println(\"Hello\"); \n } \n } \n}" }, { "code": null, "e": 67746, "s": 67669, "text": "Compile the above code by executing the following commands in the terminal −" }, { "code": null, "e": 67840, "s": 67746, "text": "[Hadoop@localhost bin]$ javac HitHighlighting \n[Hadoop@localhost bin]$ java HitHighlighting \n" }, { "code": null, "e": 67907, "s": 67840, "text": "On executing the above command, you will get the following output." }, { "code": null, "e": 68056, "s": 67907, "text": "[author:[George R.R. Martin (3), Lloyd Alexander (2), Glen Cook (1), Isaac \nAsimov (1), Orson Scott Card (1), Roger Zelazny (1), Steven Brust (1)]]\n" }, { "code": null, "e": 68091, "s": 68056, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 68110, "s": 68091, "text": " Arnab Chakraborty" }, { "code": null, "e": 68145, "s": 68110, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 68166, "s": 68145, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 68199, "s": 68166, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 68212, "s": 68199, "text": " Nilay Mehta" }, { "code": null, "e": 68247, "s": 68212, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 68265, "s": 68247, "text": " Bigdata Engineer" }, { "code": null, "e": 68298, "s": 68265, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 68316, "s": 68298, "text": " Bigdata Engineer" }, { "code": null, "e": 68349, "s": 68316, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 68367, "s": 68349, "text": " Bigdata Engineer" }, { "code": null, "e": 68374, "s": 68367, "text": " Print" }, { "code": null, "e": 68385, "s": 68374, "text": " Add Notes" } ]
About Panel in ElectronJS - GeeksforGeeks
11 Jun, 2020 ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. In traditional web applications, The About page is one of the most frequently visited and important pages on the website. It is an opportunity for visitors to get to know the website. The About Page provides a bit of background, introduction about the website and the people behind it. It is just a single click away from the homepage and it should make a quick impression. Electron also provides us with a way by which we can include the About Panel in desktop applications using the instance methods of the app module. This tutorial will demonstrate how to include the About Panel in Electron. We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system. Project Structure: Example: Follow the Steps given in Custom Notifications in ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to setup the Electron application remain the same. package.json: { "name": "electron-panel", "version": "1.0.0", "description": "About Panel in Electron", "main": "main.js", "scripts": { "start": "electron ." }, "keywords": [ "electron" ], "author": "Radhesh Khanna", "license": "ISC", "dependencies": { "electron": "^8.3.0" } } Create the assets folder according to the project structure. Copy any image file of your choosing into the assets folder and name it as image.png. In this tutorial, we will be using the Electron logo as the image.png file. Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following result. About Panel in Electron: The app module is used to control the applications event life-cycle. This module is part of the Main Process. To import and use app module in the Renderer Process, we will be using Electron remote module. index.html: Add the following snippet in that file. html <h3>About Panel in Electron</h3> <button id="about"> About Panel in Electron </button> index.js: Add the following snippet in that file. javascript const electron = require('electron')const path = require('path') // Importing the app module using Electron remoteconst app = electron.remote.app var about = document.getElementById('about');about.addEventListener('click', (event) => { app.setAboutPanelOptions({ applicationName: 'About Panel in Electron', applicationVersion: '1.0.0', copyright: 'GeeksForGeeks', credits: 'GeeksForGeeks', authors: ['Radhesh Khanna'], website: 'https://www.geeksforgeeks.org/', iconPath: path.join(__dirname, '../assets/image.png'), }); app.showAboutPanel();}); A detailed Explanation of all the Instance Methods of the app module used in the code are given below: app.setAboutPanelOptions(options) This Instance method is used to set the options for the About Panel. On Linux, the options must be passed in order to be shown in the About panel. It does not support any defaults. This method does not have any Return type. It takes in the following parameters. For more detailed Information, Refer this link.options: Object It takes in the following parameters:applicationName: String (Optional) Sets the application Name to be displayed in the About Panel.applicationVersion; String (Optional) Sets the application Version to be displayed in the About Panel.copyright: String (Optional) Sets the applications Copyright Information to be displayed in the About Panel.version: String (Optional) This parameter is supported in macOS only. It sets the applications Build Version number to be displayed in the About Panel.credits: String (Optional) This parameter is supported in Windows and Linux only. It sets the applications Credit Information to be displayed in the About Panel.authors: String[] (Optional) This parameter is supported in Linux only. This parameter takes in a String array. It sets the List of authors for the application.website: String (Optional) This parameter is supported in Linux only. It sets the applications website information.iconPath: String (Optional) This parameter is supported in Windows and Linux only. It takes in the path to the applications Icon. On Linux, the Icon will be shown as 64×64 pixels image while retaining the aspect ratio. In our code, we have used the image.png file as our applications icon. options: Object It takes in the following parameters:applicationName: String (Optional) Sets the application Name to be displayed in the About Panel.applicationVersion; String (Optional) Sets the application Version to be displayed in the About Panel.copyright: String (Optional) Sets the applications Copyright Information to be displayed in the About Panel.version: String (Optional) This parameter is supported in macOS only. It sets the applications Build Version number to be displayed in the About Panel.credits: String (Optional) This parameter is supported in Windows and Linux only. It sets the applications Credit Information to be displayed in the About Panel.authors: String[] (Optional) This parameter is supported in Linux only. This parameter takes in a String array. It sets the List of authors for the application.website: String (Optional) This parameter is supported in Linux only. It sets the applications website information.iconPath: String (Optional) This parameter is supported in Windows and Linux only. It takes in the path to the applications Icon. On Linux, the Icon will be shown as 64×64 pixels image while retaining the aspect ratio. In our code, we have used the image.png file as our applications icon. applicationName: String (Optional) Sets the application Name to be displayed in the About Panel. applicationVersion; String (Optional) Sets the application Version to be displayed in the About Panel. copyright: String (Optional) Sets the applications Copyright Information to be displayed in the About Panel. version: String (Optional) This parameter is supported in macOS only. It sets the applications Build Version number to be displayed in the About Panel. credits: String (Optional) This parameter is supported in Windows and Linux only. It sets the applications Credit Information to be displayed in the About Panel. authors: String[] (Optional) This parameter is supported in Linux only. This parameter takes in a String array. It sets the List of authors for the application. website: String (Optional) This parameter is supported in Linux only. It sets the applications website information. iconPath: String (Optional) This parameter is supported in Windows and Linux only. It takes in the path to the applications Icon. On Linux, the Icon will be shown as 64×64 pixels image while retaining the aspect ratio. In our code, we have used the image.png file as our applications icon. app.showAboutPanel() This Instance method simply shows the applications About Panel with the options set using the app.setAboutPanelOptions() method. If no options are provided, it resorts to default values on Windows and macOS. Linux does not support any default values for the About Panel. On Windows, it simply shows the Electron version currently running in the application as its default options. Output: Removing the iconPath property from the app.setAboutPanelOptions(options) method. Passing an Empty options object in the app.setAboutPanelOptions(options) method in Windows. ElectronJS CSS HTML JavaScript Node.js Web Technologies 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 Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using 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": 25269, "s": 25241, "text": "\n11 Jun, 2020" }, { "code": null, "e": 25569, "s": 25269, "text": "ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime." }, { "code": null, "e": 26165, "s": 25569, "text": "In traditional web applications, The About page is one of the most frequently visited and important pages on the website. It is an opportunity for visitors to get to know the website. The About Page provides a bit of background, introduction about the website and the people behind it. It is just a single click away from the homepage and it should make a quick impression. Electron also provides us with a way by which we can include the About Panel in desktop applications using the instance methods of the app module. This tutorial will demonstrate how to include the About Panel in Electron." }, { "code": null, "e": 26335, "s": 26165, "text": "We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system." }, { "code": null, "e": 26355, "s": 26335, "text": "Project Structure: " }, { "code": null, "e": 26817, "s": 26355, "text": "Example: Follow the Steps given in Custom Notifications in ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to setup the Electron application remain the same. " }, { "code": null, "e": 26832, "s": 26817, "text": "package.json: " }, { "code": null, "e": 27133, "s": 26832, "text": "{\n \"name\": \"electron-panel\",\n \"version\": \"1.0.0\",\n \"description\": \"About Panel in Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.3.0\"\n }\n}\n" }, { "code": null, "e": 27490, "s": 27133, "text": "Create the assets folder according to the project structure. Copy any image file of your choosing into the assets folder and name it as image.png. In this tutorial, we will be using the Electron logo as the image.png file. Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following result. " }, { "code": null, "e": 27721, "s": 27490, "text": " About Panel in Electron: The app module is used to control the applications event life-cycle. This module is part of the Main Process. To import and use app module in the Renderer Process, we will be using Electron remote module." }, { "code": null, "e": 27774, "s": 27721, "text": "index.html: Add the following snippet in that file. " }, { "code": null, "e": 27779, "s": 27774, "text": "html" }, { "code": "<h3>About Panel in Electron</h3> <button id=\"about\"> About Panel in Electron </button>", "e": 27871, "s": 27779, "text": null }, { "code": null, "e": 27922, "s": 27871, "text": "index.js: Add the following snippet in that file. " }, { "code": null, "e": 27933, "s": 27922, "text": "javascript" }, { "code": "const electron = require('electron')const path = require('path') // Importing the app module using Electron remoteconst app = electron.remote.app var about = document.getElementById('about');about.addEventListener('click', (event) => { app.setAboutPanelOptions({ applicationName: 'About Panel in Electron', applicationVersion: '1.0.0', copyright: 'GeeksForGeeks', credits: 'GeeksForGeeks', authors: ['Radhesh Khanna'], website: 'https://www.geeksforgeeks.org/', iconPath: path.join(__dirname, '../assets/image.png'), }); app.showAboutPanel();});", "e": 28543, "s": 27933, "text": null }, { "code": null, "e": 28647, "s": 28543, "text": "A detailed Explanation of all the Instance Methods of the app module used in the code are given below: " }, { "code": null, "e": 30226, "s": 28647, "text": "app.setAboutPanelOptions(options) This Instance method is used to set the options for the About Panel. On Linux, the options must be passed in order to be shown in the About panel. It does not support any defaults. This method does not have any Return type. It takes in the following parameters. For more detailed Information, Refer this link.options: Object It takes in the following parameters:applicationName: String (Optional) Sets the application Name to be displayed in the About Panel.applicationVersion; String (Optional) Sets the application Version to be displayed in the About Panel.copyright: String (Optional) Sets the applications Copyright Information to be displayed in the About Panel.version: String (Optional) This parameter is supported in macOS only. It sets the applications Build Version number to be displayed in the About Panel.credits: String (Optional) This parameter is supported in Windows and Linux only. It sets the applications Credit Information to be displayed in the About Panel.authors: String[] (Optional) This parameter is supported in Linux only. This parameter takes in a String array. It sets the List of authors for the application.website: String (Optional) This parameter is supported in Linux only. It sets the applications website information.iconPath: String (Optional) This parameter is supported in Windows and Linux only. It takes in the path to the applications Icon. On Linux, the Icon will be shown as 64×64 pixels image while retaining the aspect ratio. In our code, we have used the image.png file as our applications icon." }, { "code": null, "e": 31462, "s": 30226, "text": "options: Object It takes in the following parameters:applicationName: String (Optional) Sets the application Name to be displayed in the About Panel.applicationVersion; String (Optional) Sets the application Version to be displayed in the About Panel.copyright: String (Optional) Sets the applications Copyright Information to be displayed in the About Panel.version: String (Optional) This parameter is supported in macOS only. It sets the applications Build Version number to be displayed in the About Panel.credits: String (Optional) This parameter is supported in Windows and Linux only. It sets the applications Credit Information to be displayed in the About Panel.authors: String[] (Optional) This parameter is supported in Linux only. This parameter takes in a String array. It sets the List of authors for the application.website: String (Optional) This parameter is supported in Linux only. It sets the applications website information.iconPath: String (Optional) This parameter is supported in Windows and Linux only. It takes in the path to the applications Icon. On Linux, the Icon will be shown as 64×64 pixels image while retaining the aspect ratio. In our code, we have used the image.png file as our applications icon." }, { "code": null, "e": 31559, "s": 31462, "text": "applicationName: String (Optional) Sets the application Name to be displayed in the About Panel." }, { "code": null, "e": 31662, "s": 31559, "text": "applicationVersion; String (Optional) Sets the application Version to be displayed in the About Panel." }, { "code": null, "e": 31771, "s": 31662, "text": "copyright: String (Optional) Sets the applications Copyright Information to be displayed in the About Panel." }, { "code": null, "e": 31923, "s": 31771, "text": "version: String (Optional) This parameter is supported in macOS only. It sets the applications Build Version number to be displayed in the About Panel." }, { "code": null, "e": 32085, "s": 31923, "text": "credits: String (Optional) This parameter is supported in Windows and Linux only. It sets the applications Credit Information to be displayed in the About Panel." }, { "code": null, "e": 32246, "s": 32085, "text": "authors: String[] (Optional) This parameter is supported in Linux only. This parameter takes in a String array. It sets the List of authors for the application." }, { "code": null, "e": 32362, "s": 32246, "text": "website: String (Optional) This parameter is supported in Linux only. It sets the applications website information." }, { "code": null, "e": 32652, "s": 32362, "text": "iconPath: String (Optional) This parameter is supported in Windows and Linux only. It takes in the path to the applications Icon. On Linux, the Icon will be shown as 64×64 pixels image while retaining the aspect ratio. In our code, we have used the image.png file as our applications icon." }, { "code": null, "e": 33054, "s": 32652, "text": "app.showAboutPanel() This Instance method simply shows the applications About Panel with the options set using the app.setAboutPanelOptions() method. If no options are provided, it resorts to default values on Windows and macOS. Linux does not support any default values for the About Panel. On Windows, it simply shows the Electron version currently running in the application as its default options." }, { "code": null, "e": 33063, "s": 33054, "text": "Output: " }, { "code": null, "e": 33146, "s": 33063, "text": "Removing the iconPath property from the app.setAboutPanelOptions(options) method. " }, { "code": null, "e": 33239, "s": 33146, "text": "Passing an Empty options object in the app.setAboutPanelOptions(options) method in Windows. " }, { "code": null, "e": 33250, "s": 33239, "text": "ElectronJS" }, { "code": null, "e": 33254, "s": 33250, "text": "CSS" }, { "code": null, "e": 33259, "s": 33254, "text": "HTML" }, { "code": null, "e": 33270, "s": 33259, "text": "JavaScript" }, { "code": null, "e": 33278, "s": 33270, "text": "Node.js" }, { "code": null, "e": 33295, "s": 33278, "text": "Web Technologies" }, { "code": null, "e": 33300, "s": 33295, "text": "HTML" }, { "code": null, "e": 33398, "s": 33300, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33407, "s": 33398, "text": "Comments" }, { "code": null, "e": 33420, "s": 33407, "text": "Old Comments" }, { "code": null, "e": 33457, "s": 33420, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 33486, "s": 33457, "text": "Form validation using jQuery" }, { "code": null, "e": 33525, "s": 33486, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 33567, "s": 33525, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 33602, "s": 33567, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 33662, "s": 33602, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 33723, "s": 33662, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 33776, "s": 33723, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 33826, "s": 33776, "text": "How to Insert Form Data into Database using PHP ?" } ]
k smallest elements in same order using O(1) extra space - GeeksforGeeks
14 Apr, 2021 You are given an array of n-elements you have to find k smallest elements from the array but they must be in the same order as they are in given array and we are allowed to use only O(1) extra space.Examples: Input : arr[] = {4, 2, 6, 1, 5}, k = 3 Output : 4 2 1 Explanation : 1, 2 and 4 are three smallest numbers and 4 2 1 is their order in given array Input : arr[] = {4, 12, 16, 21, 25}, k = 3 Output : 4 12 16 Explanation : 4, 12 and 16 are 3 smallest numbers and 4 12 16 is their order in given array We have discussed efficient solution to find n smallest elements of above problem with using extra space of O(n). To solve it without using any extra space we will use concept of insertion sort.The idea is to move k minimum elements to beginning in same order. To do this, we start from (k+1)-th element and move till end. For every array element, we replace the largest element of first k elements with the current element if current element is smaller than the largest. To keep the order, we use insertion sort idea. C++ Java Python3 C# PHP Javascript // CPP for printing smallest k numbers in order#include <algorithm>#include <iostream>using namespace std; // Function to print smallest k numbers// in arr[0..n-1]void printSmall(int arr[], int n, int k){ // For each arr[i] find whether // it is a part of n-smallest // with insertion sort concept for (int i = k; i < n; ++i) { // find largest from first k-elements int max_var = arr[k-1]; int pos = k-1; for (int j=k-2; j>=0; j--) { if (arr[j] > max_var) { max_var = arr[j]; pos = j; } } // if largest is greater than arr[i] // shift all element one place left if (max_var > arr[i]) { int j = pos; while (j < k-1) { arr[j] = arr[j+1]; j++; } // make arr[k-1] = arr[i] arr[k-1] = arr[i]; } } // print result for (int i=0; i<k; i++) cout << arr[i] <<" "; } // Driver programint main(){ int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 5; printSmall(arr, n, k); return 0;} // Java for printing smallest k numbers in orderimport java.util.*;import java.lang.*; public class GfG { // Function to print smallest k numbers // in arr[0..n-1] public static void printSmall(int arr[], int n, int k) { // For each arr[i] find whether // it is a part of n-smallest // with insertion sort concept for (int i = k; i < n; ++i) { // Find largest from top n-element int max_var = arr[k - 1]; int pos = k - 1; for (int j = k - 2; j >= 0; j--) { if (arr[j] > max_var) { max_var = arr[j]; pos = j; } } // If largest is greater than arr[i] // shift all element one place left if (max_var > arr[i]) { int j = pos; while (j < k - 1) { arr[j] = arr[j + 1]; j++; } // make arr[k-1] = arr[i] arr[k - 1] = arr[i]; } } // print result for (int i = 0; i < k; i++) System.out.print(arr[i] + " "); } // Driver function public static void main(String argc[]) { int[] arr = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = 10; int k = 5; printSmall(arr, n, k); } }/* This code is contributed by Sagar Shukla */ # Python 3 for printing smallest# k numbers in order # Function to print smallest k# numbers in arr[0..n-1]def printSmall(arr, n, k): # For each arr[i] find whether # it is a part of n-smallest # with insertion sort concept for i in range(k, n): # find largest from first k-elements max_var = arr[k - 1] pos = k - 1 for j in range(k - 2, -1, -1): if (arr[j] > max_var): max_var = arr[j] pos = j # if largest is greater than arr[i] # shift all element one place left if (max_var > arr[i]): j = pos while (j < k - 1): arr[j] = arr[j + 1] j += 1 # make arr[k-1] = arr[i] arr[k - 1] = arr[i] # print result for i in range(0, k): print(arr[i], end = " ") # Driver programarr = [1, 5, 8, 9, 6, 7, 3, 4, 2, 0]n = len(arr)k = 5printSmall(arr, n, k) # This code is contributed by# Smitha Dinesh Semwal // C# for printing smallest k numbers in orderusing System; public class GfG { // Function to print smallest k numbers // in arr[0..n-1] public static void printSmall(int []arr, int n, int k) { // For each arr[i] find whether // it is a part of n-smallest // with insertion sort concept for (int i = k; i < n; ++i) { // Find largest from top n-element int max_var = arr[k - 1]; int pos = k - 1; for (int j = k - 2; j >= 0; j--) { if (arr[j] > max_var) { max_var = arr[j]; pos = j; } } // If largest is greater than arr[i] // shift all element one place left if (max_var > arr[i]) { int j = pos; while (j < k - 1) { arr[j] = arr[j + 1]; j++; } // make arr[k-1] = arr[i] arr[k - 1] = arr[i]; } } // print result for (int i = 0; i < k; i++) Console.Write(arr[i] + " "); } // Driver function public static void Main() { int[] arr = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = 10; int k = 5; printSmall(arr, n, k); }} /* This code is contributed by Vt_m */ <?php// PHP for printing smallest// k numbers in order // Function to print smallest k// numbers in arr[0..n-1]function printSmall($arr, $n, $k){ // For each arr[i] find whether // it is a part of n-smallest // with insertion sort concept for ($i = $k; $i < $n; ++$i) { // find largest from // first k-elements $max_var = $arr[$k - 1]; $pos = $k - 1; for ($j = $k - 2; $j >= 0; $j--) { if ($arr[$j] > $max_var) { $max_var = $arr[$j]; $pos = $j; } } // if largest is greater than arr[i] // shift all element one place left if ($max_var > $arr[$i]) { $j = $pos; while ($j < $k - 1) { $arr[$j] = $arr[$j + 1]; $j++; } // make arr[k - 1] = arr[i] $arr[$k - 1] = $arr[$i]; } } // print result for ($i = 0; $i < $k; $i++) echo $arr[$i] ," "; } // Driver Code $arr = array(1, 5, 8, 9, 6, 7, 3, 4, 2, 0); $n = count($arr); $k = 5; printSmall($arr, $n, $k); // This code is contributed by Vt_m?> <script> // JavaScript program for printing smallest k numbers in order // Function to print smallest k numbers // in arr[0..n-1] function printSmall(arr, n, k) { // For each arr[i] find whether // it is a part of n-smallest // with insertion sort concept for (let i = k; i < n; ++i) { // Find largest from top n-element let max_var = arr[k - 1]; let pos = k - 1; for (let j = k - 2; j >= 0; j--) { if (arr[j] > max_var) { max_var = arr[j]; pos = j; } } // If largest is greater than arr[i] // shift all element one place left if (max_var > arr[i]) { let j = pos; while (j < k - 1) { arr[j] = arr[j + 1]; j++; } // make arr[k-1] = arr[i] arr[k - 1] = arr[i]; } } // print result for (let i = 0; i < k; i++) document.write(arr[i] + " "); } // Driver code let arr = [ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 ]; let n = 10; let k = 5; printSmall(arr, n, k); // This code is contributed by sanjoy_62.</script> Output : 1 3 4 2 0 vt_m sanjoy_62 Order-Statistics Arrays Sorting Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Arrays in Java Arrays in C/C++ Program for array rotation Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews
[ { "code": null, "e": 40885, "s": 40857, "text": "\n14 Apr, 2021" }, { "code": null, "e": 41096, "s": 40885, "text": "You are given an array of n-elements you have to find k smallest elements from the array but they must be in the same order as they are in given array and we are allowed to use only O(1) extra space.Examples: " }, { "code": null, "e": 41422, "s": 41096, "text": "Input : arr[] = {4, 2, 6, 1, 5}, \n k = 3\nOutput : 4 2 1\nExplanation : 1, 2 and 4 are three smallest \nnumbers and 4 2 1 is their order in given array\n\nInput : arr[] = {4, 12, 16, 21, 25}, \n k = 3\nOutput : 4 12 16\nExplanation : 4, 12 and 16 are 3 smallest numbers\nand 4 12 16 is their order in given array" }, { "code": null, "e": 41945, "s": 41424, "text": "We have discussed efficient solution to find n smallest elements of above problem with using extra space of O(n). To solve it without using any extra space we will use concept of insertion sort.The idea is to move k minimum elements to beginning in same order. To do this, we start from (k+1)-th element and move till end. For every array element, we replace the largest element of first k elements with the current element if current element is smaller than the largest. To keep the order, we use insertion sort idea. " }, { "code": null, "e": 41949, "s": 41945, "text": "C++" }, { "code": null, "e": 41954, "s": 41949, "text": "Java" }, { "code": null, "e": 41962, "s": 41954, "text": "Python3" }, { "code": null, "e": 41965, "s": 41962, "text": "C#" }, { "code": null, "e": 41969, "s": 41965, "text": "PHP" }, { "code": null, "e": 41980, "s": 41969, "text": "Javascript" }, { "code": "// CPP for printing smallest k numbers in order#include <algorithm>#include <iostream>using namespace std; // Function to print smallest k numbers// in arr[0..n-1]void printSmall(int arr[], int n, int k){ // For each arr[i] find whether // it is a part of n-smallest // with insertion sort concept for (int i = k; i < n; ++i) { // find largest from first k-elements int max_var = arr[k-1]; int pos = k-1; for (int j=k-2; j>=0; j--) { if (arr[j] > max_var) { max_var = arr[j]; pos = j; } } // if largest is greater than arr[i] // shift all element one place left if (max_var > arr[i]) { int j = pos; while (j < k-1) { arr[j] = arr[j+1]; j++; } // make arr[k-1] = arr[i] arr[k-1] = arr[i]; } } // print result for (int i=0; i<k; i++) cout << arr[i] <<\" \"; } // Driver programint main(){ int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 5; printSmall(arr, n, k); return 0;}", "e": 43205, "s": 41980, "text": null }, { "code": "// Java for printing smallest k numbers in orderimport java.util.*;import java.lang.*; public class GfG { // Function to print smallest k numbers // in arr[0..n-1] public static void printSmall(int arr[], int n, int k) { // For each arr[i] find whether // it is a part of n-smallest // with insertion sort concept for (int i = k; i < n; ++i) { // Find largest from top n-element int max_var = arr[k - 1]; int pos = k - 1; for (int j = k - 2; j >= 0; j--) { if (arr[j] > max_var) { max_var = arr[j]; pos = j; } } // If largest is greater than arr[i] // shift all element one place left if (max_var > arr[i]) { int j = pos; while (j < k - 1) { arr[j] = arr[j + 1]; j++; } // make arr[k-1] = arr[i] arr[k - 1] = arr[i]; } } // print result for (int i = 0; i < k; i++) System.out.print(arr[i] + \" \"); } // Driver function public static void main(String argc[]) { int[] arr = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = 10; int k = 5; printSmall(arr, n, k); } }/* This code is contributed by Sagar Shukla */", "e": 44603, "s": 43205, "text": null }, { "code": "# Python 3 for printing smallest# k numbers in order # Function to print smallest k# numbers in arr[0..n-1]def printSmall(arr, n, k): # For each arr[i] find whether # it is a part of n-smallest # with insertion sort concept for i in range(k, n): # find largest from first k-elements max_var = arr[k - 1] pos = k - 1 for j in range(k - 2, -1, -1): if (arr[j] > max_var): max_var = arr[j] pos = j # if largest is greater than arr[i] # shift all element one place left if (max_var > arr[i]): j = pos while (j < k - 1): arr[j] = arr[j + 1] j += 1 # make arr[k-1] = arr[i] arr[k - 1] = arr[i] # print result for i in range(0, k): print(arr[i], end = \" \") # Driver programarr = [1, 5, 8, 9, 6, 7, 3, 4, 2, 0]n = len(arr)k = 5printSmall(arr, n, k) # This code is contributed by# Smitha Dinesh Semwal", "e": 45719, "s": 44603, "text": null }, { "code": "// C# for printing smallest k numbers in orderusing System; public class GfG { // Function to print smallest k numbers // in arr[0..n-1] public static void printSmall(int []arr, int n, int k) { // For each arr[i] find whether // it is a part of n-smallest // with insertion sort concept for (int i = k; i < n; ++i) { // Find largest from top n-element int max_var = arr[k - 1]; int pos = k - 1; for (int j = k - 2; j >= 0; j--) { if (arr[j] > max_var) { max_var = arr[j]; pos = j; } } // If largest is greater than arr[i] // shift all element one place left if (max_var > arr[i]) { int j = pos; while (j < k - 1) { arr[j] = arr[j + 1]; j++; } // make arr[k-1] = arr[i] arr[k - 1] = arr[i]; } } // print result for (int i = 0; i < k; i++) Console.Write(arr[i] + \" \"); } // Driver function public static void Main() { int[] arr = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = 10; int k = 5; printSmall(arr, n, k); }} /* This code is contributed by Vt_m */", "e": 47194, "s": 45719, "text": null }, { "code": "<?php// PHP for printing smallest// k numbers in order // Function to print smallest k// numbers in arr[0..n-1]function printSmall($arr, $n, $k){ // For each arr[i] find whether // it is a part of n-smallest // with insertion sort concept for ($i = $k; $i < $n; ++$i) { // find largest from // first k-elements $max_var = $arr[$k - 1]; $pos = $k - 1; for ($j = $k - 2; $j >= 0; $j--) { if ($arr[$j] > $max_var) { $max_var = $arr[$j]; $pos = $j; } } // if largest is greater than arr[i] // shift all element one place left if ($max_var > $arr[$i]) { $j = $pos; while ($j < $k - 1) { $arr[$j] = $arr[$j + 1]; $j++; } // make arr[k - 1] = arr[i] $arr[$k - 1] = $arr[$i]; } } // print result for ($i = 0; $i < $k; $i++) echo $arr[$i] ,\" \"; } // Driver Code $arr = array(1, 5, 8, 9, 6, 7, 3, 4, 2, 0); $n = count($arr); $k = 5; printSmall($arr, $n, $k); // This code is contributed by Vt_m?>", "e": 48432, "s": 47194, "text": null }, { "code": "<script> // JavaScript program for printing smallest k numbers in order // Function to print smallest k numbers // in arr[0..n-1] function printSmall(arr, n, k) { // For each arr[i] find whether // it is a part of n-smallest // with insertion sort concept for (let i = k; i < n; ++i) { // Find largest from top n-element let max_var = arr[k - 1]; let pos = k - 1; for (let j = k - 2; j >= 0; j--) { if (arr[j] > max_var) { max_var = arr[j]; pos = j; } } // If largest is greater than arr[i] // shift all element one place left if (max_var > arr[i]) { let j = pos; while (j < k - 1) { arr[j] = arr[j + 1]; j++; } // make arr[k-1] = arr[i] arr[k - 1] = arr[i]; } } // print result for (let i = 0; i < k; i++) document.write(arr[i] + \" \"); } // Driver code let arr = [ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 ]; let n = 10; let k = 5; printSmall(arr, n, k); // This code is contributed by sanjoy_62.</script>", "e": 49719, "s": 48432, "text": null }, { "code": null, "e": 49730, "s": 49719, "text": "Output : " }, { "code": null, "e": 49740, "s": 49730, "text": "1 3 4 2 0" }, { "code": null, "e": 49747, "s": 49742, "text": "vt_m" }, { "code": null, "e": 49757, "s": 49747, "text": "sanjoy_62" }, { "code": null, "e": 49774, "s": 49757, "text": "Order-Statistics" }, { "code": null, "e": 49781, "s": 49774, "text": "Arrays" }, { "code": null, "e": 49789, "s": 49781, "text": "Sorting" }, { "code": null, "e": 49796, "s": 49789, "text": "Arrays" }, { "code": null, "e": 49804, "s": 49796, "text": "Sorting" }, { "code": null, "e": 49902, "s": 49804, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49911, "s": 49902, "text": "Comments" }, { "code": null, "e": 49924, "s": 49911, "text": "Old Comments" }, { "code": null, "e": 49939, "s": 49924, "text": "Arrays in Java" }, { "code": null, "e": 49955, "s": 49939, "text": "Arrays in C/C++" }, { "code": null, "e": 49982, "s": 49955, "text": "Program for array rotation" }, { "code": null, "e": 50030, "s": 49982, "text": "Stack Data Structure (Introduction and Program)" } ]
Min window substring in JavaScript
We are required to write a JavaScript function that takes in two strings let's call them str1 and str2. The size of str1 is guaranteed to be greater than that of str2. We are required to find the smallest substring in str1 that contains all the characters contained in str2. For example − If the input strings are − const str1 = 'abcdefgh'; const str2 = 'gedcf'; Then the output should be − const output = 'cdefg'; because this the smallest consecutive substring of str1 that contains all characters of str2. Following is the code − const str1 = 'abcdefgh'; const str2 = 'gedcf'; const subIncludesAll = (str, str2) => { for (let i = 0; i < str.length; i++) { if (str2.indexOf(str[i]) !== -1) { str2 = str2.replace(str[i], ''); }; }; return (str2.length === 0); }; const minWindow = (str1 = '', str2 = '') => { let shortestString = null; for (let i = 0; i < str1.length; i++) { for (let j = i; j < str1.length; j++) { let testString = str1.substr(i, j-i+1); if (subIncludesAll(testString, str2)) { if (shortestString === null || testString.length < shortestString.length) { shortestString = testString; } } } } return shortestString; }; console.log(minWindow(str1, str2)); Following is the output on console − cdefg
[ { "code": null, "e": 1166, "s": 1062, "text": "We are required to write a JavaScript function that takes in two strings let's call them str1 and str2." }, { "code": null, "e": 1337, "s": 1166, "text": "The size of str1 is guaranteed to be greater than that of str2. We are required to find the smallest substring in str1 that contains all the characters contained in str2." }, { "code": null, "e": 1351, "s": 1337, "text": "For example −" }, { "code": null, "e": 1378, "s": 1351, "text": "If the input strings are −" }, { "code": null, "e": 1425, "s": 1378, "text": "const str1 = 'abcdefgh';\nconst str2 = 'gedcf';" }, { "code": null, "e": 1453, "s": 1425, "text": "Then the output should be −" }, { "code": null, "e": 1477, "s": 1453, "text": "const output = 'cdefg';" }, { "code": null, "e": 1571, "s": 1477, "text": "because this the smallest consecutive substring of str1 that contains all characters of str2." }, { "code": null, "e": 1595, "s": 1571, "text": "Following is the code −" }, { "code": null, "e": 2354, "s": 1595, "text": "const str1 = 'abcdefgh';\nconst str2 = 'gedcf';\nconst subIncludesAll = (str, str2) => {\n for (let i = 0; i < str.length; i++) {\n if (str2.indexOf(str[i]) !== -1) {\n str2 = str2.replace(str[i], '');\n };\n };\n return (str2.length === 0);\n};\nconst minWindow = (str1 = '', str2 = '') => {\n let shortestString = null;\n for (let i = 0; i < str1.length; i++) {\n for (let j = i; j < str1.length; j++) {\n let testString = str1.substr(i, j-i+1);\n if (subIncludesAll(testString, str2)) {\n if (shortestString === null || testString.length < shortestString.length) {\n shortestString = testString;\n }\n }\n }\n }\n return shortestString;\n};\nconsole.log(minWindow(str1, str2));" }, { "code": null, "e": 2391, "s": 2354, "text": "Following is the output on console −" }, { "code": null, "e": 2397, "s": 2391, "text": "cdefg" } ]
Why interfaces don't have static initialization block when it can have static methods alone in java?
An interface in Java is similar to class but, it contains only abstract methods and fields which are final and static. A static method is declared using the static keyword and it will be loaded into the memory along with the class. You can access static methods using class name without instantiation. Since Java8 you can have static methods in an interface (with body). You need to call them using the name of the interface, just like static methods of a class. In the following example, we are defining a static method in an interface and accessing it from a class implementing the interface. interface MyInterface{ public void demo(); public static void display() { System.out.println("This is a static method"); } } public class InterfaceExample{ public void demo() { System.out.println("This is the implementation of the demo method"); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.demo(); MyInterface.display(); } } This is the implementation of the demo method This is a static method A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading. public class MyClass { static{ System.out.println("Hello this is a static block"); } public static void main(String args[]){ System.out.println("This is main method"); } } Hello this is a static block This is main method Mainly, static blocks are used to initialize the class/static variables if you have not initialized them at the time of declaration. In case of interfaces when you declare a field in it. It is mandatory to assign value to it else, a compile time error is generated. interface Test{ public abstract void demo(); public static final int num; } Test.java:3: error: = expected public static final int num; ^ 1 error This will be resolved when you assign value to the static final variable in the interface. interface Test{ public abstract void demo(); public static final int num = 400; } Therefore, it is not necessary to have static blocks in the interface.
[ { "code": null, "e": 1181, "s": 1062, "text": "An interface in Java is similar to class but, it contains only abstract methods and fields which are final and static." }, { "code": null, "e": 1364, "s": 1181, "text": "A static method is declared using the static keyword and it will be loaded into the memory along with the class. You can access static methods using class name without instantiation." }, { "code": null, "e": 1525, "s": 1364, "text": "Since Java8 you can have static methods in an interface (with body). You need to call them using the name of the interface, just like static methods of a class." }, { "code": null, "e": 1657, "s": 1525, "text": "In the following example, we are defining a static method in an interface and accessing it from a class implementing the interface." }, { "code": null, "e": 2083, "s": 1657, "text": "interface MyInterface{\n public void demo();\n public static void display() {\n System.out.println(\"This is a static method\");\n }\n}\npublic class InterfaceExample{\n public void demo() {\n System.out.println(\"This is the implementation of the demo method\");\n }\n public static void main(String args[]) {\n InterfaceExample obj = new InterfaceExample();\n obj.demo();\n MyInterface.display();\n }\n}" }, { "code": null, "e": 2153, "s": 2083, "text": "This is the implementation of the demo method\nThis is a static method" }, { "code": null, "e": 2351, "s": 2153, "text": "A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading." }, { "code": null, "e": 2547, "s": 2351, "text": "public class MyClass {\n static{\n System.out.println(\"Hello this is a static block\");\n }\n public static void main(String args[]){\n System.out.println(\"This is main method\");\n }\n}" }, { "code": null, "e": 2596, "s": 2547, "text": "Hello this is a static block\nThis is main method" }, { "code": null, "e": 2729, "s": 2596, "text": "Mainly, static blocks are used to initialize the class/static variables if you have not initialized them at the time of declaration." }, { "code": null, "e": 2862, "s": 2729, "text": "In case of interfaces when you declare a field in it. It is mandatory to assign value to it else, a compile time error is generated." }, { "code": null, "e": 2944, "s": 2862, "text": "interface Test{\n public abstract void demo();\n public static final int num;\n}" }, { "code": null, "e": 3047, "s": 2944, "text": "Test.java:3: error: = expected\n public static final int num;\n ^\n1 error" }, { "code": null, "e": 3138, "s": 3047, "text": "This will be resolved when you assign value to the static final variable in the interface." }, { "code": null, "e": 3226, "s": 3138, "text": "interface Test{\n public abstract void demo();\n public static final int num = 400;\n}" }, { "code": null, "e": 3297, "s": 3226, "text": "Therefore, it is not necessary to have static blocks in the interface." } ]
Python Program to Form a New String Made of the First 2 and Last 2 characters From a Given String
When it is required to form a new string that is made from the first two and last two characters of a given string, a counter can be defined, and indexing can be used to access specific range of elements. Below is the demonstration of the same − Live Demo my_string = "Hi there how are you" my_counter = 0 for i in my_string: my_counter = my_counter + 1 new_string = my_string[0:2] + my_string [my_counter - 2: my_counter ] print("The string is ") print(my_string) print("The new string is ") print(new_string) The string is Hi there how are you The new string is Hiou A string is defined and is displayed on the console. A string is defined and is displayed on the console. A counter is initiated to 0. A counter is initiated to 0. The string is iterated over, and the first 2 and last two elements are accessed using indexing. The string is iterated over, and the first 2 and last two elements are accessed using indexing. This is assigned to a variable. This is assigned to a variable. It is the output that is displayed on the console. It is the output that is displayed on the console.
[ { "code": null, "e": 1267, "s": 1062, "text": "When it is required to form a new string that is made from the first two and last two characters of a given string, a counter can be defined, and indexing can be used to access specific range of elements." }, { "code": null, "e": 1308, "s": 1267, "text": "Below is the demonstration of the same −" }, { "code": null, "e": 1319, "s": 1308, "text": " Live Demo" }, { "code": null, "e": 1580, "s": 1319, "text": "my_string = \"Hi there how are you\"\n\nmy_counter = 0\n\nfor i in my_string:\n my_counter = my_counter + 1\nnew_string = my_string[0:2] + my_string [my_counter - 2: my_counter ]\n\nprint(\"The string is \")\nprint(my_string)\nprint(\"The new string is \")\nprint(new_string)" }, { "code": null, "e": 1638, "s": 1580, "text": "The string is\nHi there how are you\nThe new string is\nHiou" }, { "code": null, "e": 1691, "s": 1638, "text": "A string is defined and is displayed on the console." }, { "code": null, "e": 1744, "s": 1691, "text": "A string is defined and is displayed on the console." }, { "code": null, "e": 1773, "s": 1744, "text": "A counter is initiated to 0." }, { "code": null, "e": 1802, "s": 1773, "text": "A counter is initiated to 0." }, { "code": null, "e": 1898, "s": 1802, "text": "The string is iterated over, and the first 2 and last two elements are accessed using indexing." }, { "code": null, "e": 1994, "s": 1898, "text": "The string is iterated over, and the first 2 and last two elements are accessed using indexing." }, { "code": null, "e": 2026, "s": 1994, "text": "This is assigned to a variable." }, { "code": null, "e": 2058, "s": 2026, "text": "This is assigned to a variable." }, { "code": null, "e": 2109, "s": 2058, "text": "It is the output that is displayed on the console." }, { "code": null, "e": 2160, "s": 2109, "text": "It is the output that is displayed on the console." } ]
Artificial Intelligence - Quick Guide
Since the invention of computers or machines, their capability to perform various tasks went on growing exponentially. Humans have developed the power of computer systems in terms of their diverse working domains, their increasing speed, and reducing size with respect to time. A branch of Computer Science named Artificial Intelligence pursues creating the computers or machines as intelligent as human beings. According to the father of Artificial Intelligence, John McCarthy, it is “The science and engineering of making intelligent machines, especially intelligent computer programs”. Artificial Intelligence is a way of making a computer, a computer-controlled robot, or a software think intelligently, in the similar manner the intelligent humans think. AI is accomplished by studying how human brain thinks, and how humans learn, decide, and work while trying to solve a problem, and then using the outcomes of this study as a basis of developing intelligent software and systems. While exploiting the power of the computer systems, the curiosity of human, lead him to wonder, “Can a machine think and behave like humans do?” Thus, the development of AI started with the intention of creating similar intelligence in machines that we find and regard high in humans. To Create Expert Systems − The systems which exhibit intelligent behavior, learn, demonstrate, explain, and advice its users. To Create Expert Systems − The systems which exhibit intelligent behavior, learn, demonstrate, explain, and advice its users. To Implement Human Intelligence in Machines − Creating systems that understand, think, learn, and behave like humans. To Implement Human Intelligence in Machines − Creating systems that understand, think, learn, and behave like humans. Artificial intelligence is a science and technology based on disciplines such as Computer Science, Biology, Psychology, Linguistics, Mathematics, and Engineering. A major thrust of AI is in the development of computer functions associated with human intelligence, such as reasoning, learning, and problem solving. Out of the following areas, one or multiple areas can contribute to build an intelligent system. The programming without and with AI is different in following ways − In the real world, the knowledge has some unwelcomed properties − Its volume is huge, next to unimaginable. It is not well-organized or well-formatted. It keeps changing constantly. AI Technique is a manner to organize and use the knowledge efficiently in such a way that − It should be perceivable by the people who provide it. It should be easily modifiable to correct errors. It should be useful in many situations though it is incomplete or inaccurate. AI techniques elevate the speed of execution of the complex program it is equipped with. AI has been dominant in various fields such as − Gaming − AI plays crucial role in strategic games such as chess, poker, tic-tac-toe, etc., where machine can think of large number of possible positions based on heuristic knowledge. Gaming − AI plays crucial role in strategic games such as chess, poker, tic-tac-toe, etc., where machine can think of large number of possible positions based on heuristic knowledge. Natural Language Processing − It is possible to interact with the computer that understands natural language spoken by humans. Natural Language Processing − It is possible to interact with the computer that understands natural language spoken by humans. Expert Systems − There are some applications which integrate machine, software, and special information to impart reasoning and advising. They provide explanation and advice to the users. Expert Systems − There are some applications which integrate machine, software, and special information to impart reasoning and advising. They provide explanation and advice to the users. Vision Systems − These systems understand, interpret, and comprehend visual input on the computer. For example, A spying aeroplane takes photographs, which are used to figure out spatial information or map of the areas. Doctors use clinical expert system to diagnose the patient. Police use computer software that can recognize the face of criminal with the stored portrait made by forensic artist. Vision Systems − These systems understand, interpret, and comprehend visual input on the computer. For example, A spying aeroplane takes photographs, which are used to figure out spatial information or map of the areas. A spying aeroplane takes photographs, which are used to figure out spatial information or map of the areas. Doctors use clinical expert system to diagnose the patient. Doctors use clinical expert system to diagnose the patient. Police use computer software that can recognize the face of criminal with the stored portrait made by forensic artist. Police use computer software that can recognize the face of criminal with the stored portrait made by forensic artist. Speech Recognition − Some intelligent systems are capable of hearing and comprehending the language in terms of sentences and their meanings while a human talks to it. It can handle different accents, slang words, noise in the background, change in human’s noise due to cold, etc. Speech Recognition − Some intelligent systems are capable of hearing and comprehending the language in terms of sentences and their meanings while a human talks to it. It can handle different accents, slang words, noise in the background, change in human’s noise due to cold, etc. Handwriting Recognition − The handwriting recognition software reads the text written on paper by a pen or on screen by a stylus. It can recognize the shapes of the letters and convert it into editable text. Handwriting Recognition − The handwriting recognition software reads the text written on paper by a pen or on screen by a stylus. It can recognize the shapes of the letters and convert it into editable text. Intelligent Robots − Robots are able to perform the tasks given by a human. They have sensors to detect physical data from the real world such as light, heat, temperature, movement, sound, bump, and pressure. They have efficient processors, multiple sensors and huge memory, to exhibit intelligence. In addition, they are capable of learning from their mistakes and they can adapt to the new environment. Intelligent Robots − Robots are able to perform the tasks given by a human. They have sensors to detect physical data from the real world such as light, heat, temperature, movement, sound, bump, and pressure. They have efficient processors, multiple sensors and huge memory, to exhibit intelligence. In addition, they are capable of learning from their mistakes and they can adapt to the new environment. Here is the history of AI during 20th century − Karel Čapek play named “Rossum's Universal Robots” (RUR) opens in London, first use of the word "robot" in English. Foundations for neural networks laid. Isaac Asimov, a Columbia University alumni, coined the term Robotics. Alan Turing introduced Turing Test for evaluation of intelligence and published Computing Machinery and Intelligence. Claude Shannon published Detailed Analysis of Chess Playing as a search. John McCarthy coined the term Artificial Intelligence. Demonstration of the first running AI program at Carnegie Mellon University. John McCarthy invents LISP programming language for AI. Danny Bobrow's dissertation at MIT showed that computers can understand natural language well enough to solve algebra word problems correctly. Joseph Weizenbaum at MIT built ELIZA, an interactive problem that carries on a dialogue in English. Scientists at Stanford Research Institute Developed Shakey, a robot, equipped with locomotion, perception, and problem solving. The Assembly Robotics group at Edinburgh University built Freddy, the Famous Scottish Robot, capable of using vision to locate and assemble models. The first computer-controlled autonomous vehicle, Stanford Cart, was built. Harold Cohen created and demonstrated the drawing program, Aaron. Major advances in all areas of AI − Significant demonstrations in machine learning Case-based reasoning Multi-agent planning Scheduling Data mining, Web Crawler natural language understanding and translation Vision, Virtual Reality Games The Deep Blue Chess Program beats the then world chess champion, Garry Kasparov. Interactive robot pets become commercially available. MIT displays Kismet, a robot with a face that expresses emotions. The robot Nomad explores remote regions of Antarctica and locates meteorites. While studying artificially intelligence, you need to know what intelligence is. This chapter covers Idea of intelligence, types, and components of intelligence. The ability of a system to calculate, reason, perceive relationships and analogies, learn from experience, store and retrieve information from memory, solve problems, comprehend complex ideas, use natural language fluently, classify, generalize, and adapt new situations. As described by Howard Gardner, an American developmental psychologist, the Intelligence comes in multifold − You can say a machine or a system is artificially intelligent when it is equipped with at least one and at most all intelligences in it. The intelligence is intangible. It is composed of − Reasoning Learning Problem Solving Perception Linguistic Intelligence Let us go through all the components briefly − Reasoning − It is the set of processes that enables us to provide basis for judgement, making decisions, and prediction. There are broadly two types − Reasoning − It is the set of processes that enables us to provide basis for judgement, making decisions, and prediction. There are broadly two types − Learning − It is the activity of gaining knowledge or skill by studying, practising, being taught, or experiencing something. Learning enhances the awareness of the subjects of the study. The ability of learning is possessed by humans, some animals, and AI-enabled systems. Learning is categorized as − Auditory Learning − It is learning by listening and hearing. For example, students listening to recorded audio lectures. Episodic Learning − To learn by remembering sequences of events that one has witnessed or experienced. This is linear and orderly. Motor Learning − It is learning by precise movement of muscles. For example, picking objects, Writing, etc. Observational Learning − To learn by watching and imitating others. For example, child tries to learn by mimicking her parent. Perceptual Learning − It is learning to recognize stimuli that one has seen before. For example, identifying and classifying objects and situations. Relational Learning − It involves learning to differentiate among various stimuli on the basis of relational properties, rather than absolute properties. For Example, Adding ‘little less’ salt at the time of cooking potatoes that came up salty last time, when cooked with adding say a tablespoon of salt. Spatial Learning − It is learning through visual stimuli such as images, colors, maps, etc. For Example, A person can create roadmap in mind before actually following the road. Stimulus-Response Learning − It is learning to perform a particular behavior when a certain stimulus is present. For example, a dog raises its ear on hearing doorbell. Learning − It is the activity of gaining knowledge or skill by studying, practising, being taught, or experiencing something. Learning enhances the awareness of the subjects of the study. The ability of learning is possessed by humans, some animals, and AI-enabled systems. Learning is categorized as − Auditory Learning − It is learning by listening and hearing. For example, students listening to recorded audio lectures. Auditory Learning − It is learning by listening and hearing. For example, students listening to recorded audio lectures. Episodic Learning − To learn by remembering sequences of events that one has witnessed or experienced. This is linear and orderly. Episodic Learning − To learn by remembering sequences of events that one has witnessed or experienced. This is linear and orderly. Motor Learning − It is learning by precise movement of muscles. For example, picking objects, Writing, etc. Motor Learning − It is learning by precise movement of muscles. For example, picking objects, Writing, etc. Observational Learning − To learn by watching and imitating others. For example, child tries to learn by mimicking her parent. Observational Learning − To learn by watching and imitating others. For example, child tries to learn by mimicking her parent. Perceptual Learning − It is learning to recognize stimuli that one has seen before. For example, identifying and classifying objects and situations. Perceptual Learning − It is learning to recognize stimuli that one has seen before. For example, identifying and classifying objects and situations. Relational Learning − It involves learning to differentiate among various stimuli on the basis of relational properties, rather than absolute properties. For Example, Adding ‘little less’ salt at the time of cooking potatoes that came up salty last time, when cooked with adding say a tablespoon of salt. Relational Learning − It involves learning to differentiate among various stimuli on the basis of relational properties, rather than absolute properties. For Example, Adding ‘little less’ salt at the time of cooking potatoes that came up salty last time, when cooked with adding say a tablespoon of salt. Spatial Learning − It is learning through visual stimuli such as images, colors, maps, etc. For Example, A person can create roadmap in mind before actually following the road. Spatial Learning − It is learning through visual stimuli such as images, colors, maps, etc. For Example, A person can create roadmap in mind before actually following the road. Stimulus-Response Learning − It is learning to perform a particular behavior when a certain stimulus is present. For example, a dog raises its ear on hearing doorbell. Stimulus-Response Learning − It is learning to perform a particular behavior when a certain stimulus is present. For example, a dog raises its ear on hearing doorbell. Problem Solving − It is the process in which one perceives and tries to arrive at a desired solution from a present situation by taking some path, which is blocked by known or unknown hurdles. Problem solving also includes decision making, which is the process of selecting the best suitable alternative out of multiple alternatives to reach the desired goal are available. Problem Solving − It is the process in which one perceives and tries to arrive at a desired solution from a present situation by taking some path, which is blocked by known or unknown hurdles. Problem solving also includes decision making, which is the process of selecting the best suitable alternative out of multiple alternatives to reach the desired goal are available. Perception − It is the process of acquiring, interpreting, selecting, and organizing sensory information. Perception presumes sensing. In humans, perception is aided by sensory organs. In the domain of AI, perception mechanism puts the data acquired by the sensors together in a meaningful manner. Perception − It is the process of acquiring, interpreting, selecting, and organizing sensory information. Perception presumes sensing. In humans, perception is aided by sensory organs. In the domain of AI, perception mechanism puts the data acquired by the sensors together in a meaningful manner. Linguistic Intelligence − It is one’s ability to use, comprehend, speak, and write the verbal and written language. It is important in interpersonal communication. Linguistic Intelligence − It is one’s ability to use, comprehend, speak, and write the verbal and written language. It is important in interpersonal communication. Humans perceive by patterns whereas the machines perceive by set of rules and data. Humans perceive by patterns whereas the machines perceive by set of rules and data. Humans store and recall information by patterns, machines do it by searching algorithms. For example, the number 40404040 is easy to remember, store, and recall as its pattern is simple. Humans store and recall information by patterns, machines do it by searching algorithms. For example, the number 40404040 is easy to remember, store, and recall as its pattern is simple. Humans can figure out the complete object even if some part of it is missing or distorted; whereas the machines cannot do it correctly. Humans can figure out the complete object even if some part of it is missing or distorted; whereas the machines cannot do it correctly. The domain of artificial intelligence is huge in breadth and width. While proceeding, we consider the broadly common and prospering research areas in the domain of AI − These both terms are common in robotics, expert systems and natural language processing. Though these terms are used interchangeably, their objectives are different. The user input spoken at a microphone goes to sound card of the system. The converter turns the analog signal into equivalent digital signal for the speech processing. The database is used to compare the sound patterns to recognize the words. Finally, a reverse feedback is given to the database. This source-language text becomes input to the Translation Engine, which converts it to the target language text. They are supported with interactive GUI, large database of vocabulary, etc. There is a large array of applications where AI is serving common people in their day-to-day lives − Expert Systems Examples − Flight-tracking systems, Clinical systems. Natural Language Processing Examples: Google Now feature, speech recognition, Automatic voice output. Neural Networks Examples − Pattern recognition systems such as face recognition, character recognition, handwriting recognition. Robotics Examples − Industrial robots for moving, spraying, painting, precision checking, drilling, cleaning, coating, carving, etc. Fuzzy Logic Systems Examples − Consumer electronics, automobiles, etc. The domain of AI is classified into Formal tasks, Mundane tasks, and Expert tasks. Computer Vision Speech, Voice Mathematics Geometry Logic Integration and Differentiation Engineering Fault Finding Manufacturing Monitoring Understanding Language Generation Language Translation Go Chess (Deep Blue) Ckeckers Locomotive Humans learn mundane (ordinary) tasks since their birth. They learn by perception, speaking, using language, and locomotives. They learn Formal Tasks and Expert Tasks later, in that order. For humans, the mundane tasks are easiest to learn. The same was considered true before trying to implement mundane tasks in machines. Earlier, all work of AI was concentrated in the mundane task domain. Later, it turned out that the machine requires more knowledge, complex knowledge representation, and complicated algorithms for handling mundane tasks. This is the reason why AI work is more prospering in the Expert Tasks domain now, as the expert task domain needs expert knowledge without common sense, which can be easier to represent and handle. An AI system is composed of an agent and its environment. The agents act in their environment. The environment may contain other agents. An agent is anything that can perceive its environment through sensors and acts upon that environment through effectors. A human agent has sensory organs such as eyes, ears, nose, tongue and skin parallel to the sensors, and other organs such as hands, legs, mouth, for effectors. A human agent has sensory organs such as eyes, ears, nose, tongue and skin parallel to the sensors, and other organs such as hands, legs, mouth, for effectors. A robotic agent replaces cameras and infrared range finders for the sensors, and various motors and actuators for effectors. A robotic agent replaces cameras and infrared range finders for the sensors, and various motors and actuators for effectors. A software agent has encoded bit strings as its programs and actions. A software agent has encoded bit strings as its programs and actions. Performance Measure of Agent − It is the criteria, which determines how successful an agent is. Performance Measure of Agent − It is the criteria, which determines how successful an agent is. Behavior of Agent − It is the action that agent performs after any given sequence of percepts. Behavior of Agent − It is the action that agent performs after any given sequence of percepts. Percept − It is agent’s perceptual inputs at a given instance. Percept − It is agent’s perceptual inputs at a given instance. Percept Sequence − It is the history of all that an agent has perceived till date. Percept Sequence − It is the history of all that an agent has perceived till date. Agent Function − It is a map from the precept sequence to an action. Agent Function − It is a map from the precept sequence to an action. Rationality is nothing but status of being reasonable, sensible, and having good sense of judgment. Rationality is concerned with expected actions and results depending upon what the agent has perceived. Performing actions with the aim of obtaining useful information is an important part of rationality. An ideal rational agent is the one, which is capable of doing expected actions to maximize its performance measure, on the basis of − Its percept sequence Its built-in knowledge base Rationality of an agent depends on the following − The performance measures, which determine the degree of success. The performance measures, which determine the degree of success. Agent’s Percept Sequence till now. Agent’s Percept Sequence till now. The agent’s prior knowledge about the environment. The agent’s prior knowledge about the environment. The actions that the agent can carry out. The actions that the agent can carry out. A rational agent always performs right action, where the right action means the action that causes the agent to be most successful in the given percept sequence. The problem the agent solves is characterized by Performance Measure, Environment, Actuators, and Sensors (PEAS). Agent’s structure can be viewed as − Agent = Architecture + Agent Program Architecture = the machinery that an agent executes on. Agent Program = an implementation of an agent function. They choose actions only based on the current percept. They are rational only if a correct decision is made only on the basis of current precept. Their environment is completely observable. Condition-Action Rule − It is a rule that maps a state (condition) to an action. They use a model of the world to choose their actions. They maintain an internal state. Model − knowledge about “how the things happen in the world”. Internal State − It is a representation of unobserved aspects of current state depending on percept history. Updating the state requires the information about − How the world evolves. How the agent’s actions affect the world. They choose their actions in order to achieve goals. Goal-based approach is more flexible than reflex agent since the knowledge supporting a decision is explicitly modeled, thereby allowing for modifications. Goal − It is the description of desirable situations. They choose actions based on a preference (utility) for each state. Goals are inadequate when − There are conflicting goals, out of which only few can be achieved. There are conflicting goals, out of which only few can be achieved. Goals have some uncertainty of being achieved and you need to weigh likelihood of success against the importance of a goal. Goals have some uncertainty of being achieved and you need to weigh likelihood of success against the importance of a goal. Some programs operate in the entirely artificial environment confined to keyboard input, database, computer file systems and character output on a screen. In contrast, some software agents (software robots or softbots) exist in rich, unlimited softbots domains. The simulator has a very detailed, complex environment. The software agent needs to choose from a long array of actions in real time. A softbot designed to scan the online preferences of the customer and show interesting items to the customer works in the real as well as an artificial environment. The most famous artificial environment is the Turing Test environment, in which one real and other artificial agents are tested on equal ground. This is a very challenging environment as it is highly difficult for a software agent to perform as well as a human. The success of an intelligent behavior of a system can be measured with Turing Test. Two persons and a machine to be evaluated participate in the test. Out of the two persons, one plays the role of the tester. Each of them sits in different rooms. The tester is unaware of who is machine and who is a human. He interrogates the questions by typing and sending them to both intelligences, to which he receives typed responses. This test aims at fooling the tester. If the tester fails to determine machine’s response from the human response, then the machine is said to be intelligent. The environment has multifold properties − Discrete / Continuous − If there are a limited number of distinct, clearly defined, states of the environment, the environment is discrete (For example, chess); otherwise it is continuous (For example, driving). Discrete / Continuous − If there are a limited number of distinct, clearly defined, states of the environment, the environment is discrete (For example, chess); otherwise it is continuous (For example, driving). Observable / Partially Observable − If it is possible to determine the complete state of the environment at each time point from the percepts it is observable; otherwise it is only partially observable. Observable / Partially Observable − If it is possible to determine the complete state of the environment at each time point from the percepts it is observable; otherwise it is only partially observable. Static / Dynamic − If the environment does not change while an agent is acting, then it is static; otherwise it is dynamic. Static / Dynamic − If the environment does not change while an agent is acting, then it is static; otherwise it is dynamic. Single agent / Multiple agents − The environment may contain other agents which may be of the same or different kind as that of the agent. Single agent / Multiple agents − The environment may contain other agents which may be of the same or different kind as that of the agent. Accessible / Inaccessible − If the agent’s sensory apparatus can have access to the complete state of the environment, then the environment is accessible to that agent. Accessible / Inaccessible − If the agent’s sensory apparatus can have access to the complete state of the environment, then the environment is accessible to that agent. Deterministic / Non-deterministic − If the next state of the environment is completely determined by the current state and the actions of the agent, then the environment is deterministic; otherwise it is non-deterministic. Deterministic / Non-deterministic − If the next state of the environment is completely determined by the current state and the actions of the agent, then the environment is deterministic; otherwise it is non-deterministic. Episodic / Non-episodic − In an episodic environment, each episode consists of the agent perceiving and then acting. The quality of its action depends just on the episode itself. Subsequent episodes do not depend on the actions in the previous episodes. Episodic environments are much simpler because the agent does not need to think ahead. Episodic / Non-episodic − In an episodic environment, each episode consists of the agent perceiving and then acting. The quality of its action depends just on the episode itself. Subsequent episodes do not depend on the actions in the previous episodes. Episodic environments are much simpler because the agent does not need to think ahead. Searching is the universal technique of problem solving in AI. There are some single-player games such as tile games, Sudoku, crossword, etc. The search algorithms help you to search for a particular position in such games. The games such as 3X3 eight-tile, 4X4 fifteen-tile, and 5X5 twenty four tile puzzles are single-agent-path-finding challenges. They consist of a matrix of tiles with a blank tile. The player is required to arrange the tiles by sliding a tile either vertically or horizontally into a blank space with the aim of accomplishing some objective. The other examples of single agent pathfinding problems are Travelling Salesman Problem, Rubik’s Cube, and Theorem Proving. Problem Space − It is the environment in which the search takes place. (A set of states and set of operators to change those states) Problem Space − It is the environment in which the search takes place. (A set of states and set of operators to change those states) Problem Instance − It is Initial state + Goal state. Problem Instance − It is Initial state + Goal state. Problem Space Graph − It represents problem state. States are shown by nodes and operators are shown by edges. Problem Space Graph − It represents problem state. States are shown by nodes and operators are shown by edges. Depth of a problem − Length of a shortest path or shortest sequence of operators from Initial State to goal state. Depth of a problem − Length of a shortest path or shortest sequence of operators from Initial State to goal state. Space Complexity − The maximum number of nodes that are stored in memory. Space Complexity − The maximum number of nodes that are stored in memory. Time Complexity − The maximum number of nodes that are created. Time Complexity − The maximum number of nodes that are created. Admissibility − A property of an algorithm to always find an optimal solution. Admissibility − A property of an algorithm to always find an optimal solution. Branching Factor − The average number of child nodes in the problem space graph. Branching Factor − The average number of child nodes in the problem space graph. Depth − Length of the shortest path from initial state to goal state. Depth − Length of the shortest path from initial state to goal state. They are most simple, as they do not need any domain-specific knowledge. They work fine with small number of possible states. Requirements − State description A set of valid operators Initial state Goal state description It starts from the root node, explores the neighboring nodes first and moves towards the next level neighbors. It generates one tree at a time until the solution is found. It can be implemented using FIFO queue data structure. This method provides shortest path to the solution. If branching factor (average number of child nodes for a given node) = b and depth = d, then number of nodes at level d = bd. The total no of nodes created in worst case is b + b2 + b3 + ... + bd. Disadvantage − Since each level of nodes is saved for creating next one, it consumes a lot of memory space. Space requirement to store nodes is exponential. Its complexity depends on the number of nodes. It can check duplicate nodes. It is implemented in recursion with LIFO stack data structure. It creates the same set of nodes as Breadth-First method, only in the different order. As the nodes on the single path are stored in each iteration from root to leaf node, the space requirement to store nodes is linear. With branching factor b and depth as m, the storage space is bm. Disadvantage − This algorithm may not terminate and go on infinitely on one path. The solution to this issue is to choose a cut-off depth. If the ideal cut-off is d, and if chosen cut-off is lesser than d, then this algorithm may fail. If chosen cut-off is more than d, then execution time increases. Its complexity depends on the number of paths. It cannot check duplicate nodes. It searches forward from initial state and backward from goal state till both meet to identify a common state. The path from initial state is concatenated with the inverse path from the goal state. Each search is done only up to half of the total path. Sorting is done in increasing cost of the path to a node. It always expands the least cost node. It is identical to Breadth First search if each transition has the same cost. It explores paths in the increasing order of cost. Disadvantage − There can be multiple long paths with the cost ≤ C*. Uniform Cost search must explore them all. It performs depth-first search to level 1, starts over, executes a complete depth-first search to level 2, and continues in such way till the solution is found. It never creates a node until all lower nodes are generated. It only saves a stack of nodes. The algorithm ends when it finds a solution at depth d. The number of nodes created at depth d is bd and at depth d-1 is bd-1. Let us see the performance of algorithms based on various criteria − To solve large problems with large number of possible states, problem-specific knowledge needs to be added to increase the efficiency of search algorithms. They calculate the cost of optimal path between two states. A heuristic function for sliding-tiles games is computed by counting number of moves that each tile makes from its goal state and adding these number of moves for all tiles. It expands nodes in the order of their heuristic values. It creates two lists, a closed list for the already expanded nodes and an open list for the created but unexpanded nodes. In each iteration, a node with a minimum heuristic value is expanded, all its child nodes are created and placed in the closed list. Then, the heuristic function is applied to the child nodes and they are placed in the open list according to their heuristic value. The shorter paths are saved and the longer ones are disposed. It is best-known form of Best First search. It avoids expanding paths that are already expensive, but expands most promising paths first. f(n) = g(n) + h(n), where g(n) the cost (so far) to reach the node h(n) estimated cost to get from the node to the goal f(n) estimated total cost of path through n to goal. It is implemented using priority queue by increasing f(n). It expands the node that is estimated to be closest to goal. It expands nodes based on f(n) = h(n). It is implemented using priority queue. Disadvantage − It can get stuck in loops. It is not optimal. They start from a prospective solution and then move to a neighboring solution. They can return a valid solution even if it is interrupted at any time before they end. It is an iterative algorithm that starts with an arbitrary solution to a problem and attempts to find a better solution by changing a single element of the solution incrementally. If the change produces a better solution, an incremental change is taken as a new solution. This process is repeated until there are no further improvements. function Hill-Climbing (problem), returns a state that is a local maximum. inputs: problem, a problem local variables: current, a node neighbor, a node current <-Make_Node(Initial-State[problem]) loop do neighbor <- a highest_valued successor of current if Value[neighbor] ≤ Value[current] then return State[current] current <- neighbor end Disadvantage − This algorithm is neither complete, nor optimal. In this algorithm, it holds k number of states at any given time. At the start, these states are generated randomly. The successors of these k states are computed with the help of objective function. If any of these successors is the maximum value of the objective function, then the algorithm stops. Otherwise the (initial k states and k number of successors of the states = 2k) states are placed in a pool. The pool is then sorted numerically. The highest k states are selected as new initial states. This process continues until a maximum value is reached. function BeamSearch( problem, k), returns a solution state. start with k randomly generated states loop generate all successors of all k states if any of the states = solution, then return the state else select the k best successors end Annealing is the process of heating and cooling a metal to change its internal structure for modifying its physical properties. When the metal cools, its new structure is seized, and the metal retains its newly obtained properties. In simulated annealing process, the temperature is kept variable. We initially set the temperature high and then allow it to ‘cool' slowly as the algorithm proceeds. When the temperature is high, the algorithm is allowed to accept worse solutions with high frequency. Start Initialize k = 0; L = integer number of variables; From i → j, search the performance difference Δ. If Δ <= 0 then accept else if exp(-Δ/T(k)) > random(0,1) then accept; Repeat steps 1 and 2 for L(k) steps. k = k + 1; Repeat steps 1 through 4 till the criteria is met. End In this algorithm, the objective is to find a low-cost tour that starts from a city, visits all cities en-route exactly once and ends at the same starting city. Start Find out all (n -1)! Possible solutions, where n is the total number of cities. Determine the minimum cost by finding out the cost of each of these (n -1)! solutions. Finally, keep the one with the minimum cost. end Fuzzy Logic Systems (FLS) produce acceptable but definite output in response to incomplete, ambiguous, distorted, or inaccurate (fuzzy) input. Fuzzy Logic (FL) is a method of reasoning that resembles human reasoning. The approach of FL imitates the way of decision making in humans that involves all intermediate possibilities between digital values YES and NO. The conventional logic block that a computer can understand takes precise input and produces a definite output as TRUE or FALSE, which is equivalent to human’s YES or NO. The inventor of fuzzy logic, Lotfi Zadeh, observed that unlike computers, the human decision making includes a range of possibilities between YES and NO, such as − The fuzzy logic works on the levels of possibilities of input to achieve the definite output. It can be implemented in systems with various sizes and capabilities ranging from small micro-controllers to large, networked, workstation-based control systems. It can be implemented in systems with various sizes and capabilities ranging from small micro-controllers to large, networked, workstation-based control systems. It can be implemented in hardware, software, or a combination of both. It can be implemented in hardware, software, or a combination of both. Fuzzy logic is useful for commercial and practical purposes. It can control machines and consumer products. It may not give accurate reasoning, but acceptable reasoning. Fuzzy logic helps to deal with the uncertainty in engineering. It has four main parts as shown − Fuzzification Module − It transforms the system inputs, which are crisp numbers, into fuzzy sets. It splits the input signal into five steps such as − Fuzzification Module − It transforms the system inputs, which are crisp numbers, into fuzzy sets. It splits the input signal into five steps such as − Knowledge Base − It stores IF-THEN rules provided by experts. Knowledge Base − It stores IF-THEN rules provided by experts. Inference Engine − It simulates the human reasoning process by making fuzzy inference on the inputs and IF-THEN rules. Inference Engine − It simulates the human reasoning process by making fuzzy inference on the inputs and IF-THEN rules. Defuzzification Module − It transforms the fuzzy set obtained by the inference engine into a crisp value. Defuzzification Module − It transforms the fuzzy set obtained by the inference engine into a crisp value. The membership functions work on fuzzy sets of variables. Membership functions allow you to quantify linguistic term and represent a fuzzy set graphically. A membership function for a fuzzy set A on the universe of discourse X is defined as μA:X → [0,1]. Here, each element of X is mapped to a value between 0 and 1. It is called membership value or degree of membership. It quantifies the degree of membership of the element in X to the fuzzy set A. x axis represents the universe of discourse. y axis represents the degrees of membership in the [0, 1] interval. There can be multiple membership functions applicable to fuzzify a numerical value. Simple membership functions are used as use of complex functions does not add more precision in the output. All membership functions for LP, MP, S, MN, and LN are shown as below − The triangular membership function shapes are most common among various other membership function shapes such as trapezoidal, singleton, and Gaussian. Here, the input to 5-level fuzzifier varies from -10 volts to +10 volts. Hence the corresponding output also changes. Let us consider an air conditioning system with 5-level fuzzy logic system. This system adjusts the temperature of air conditioner by comparing the room temperature and the target temperature value. Define linguistic Variables and terms (start) Construct membership functions for them. (start) Construct knowledge base of rules (start) Convert crisp data into fuzzy data sets using membership functions. (fuzzification) Evaluate rules in the rule base. (Inference Engine) Combine results from each rule. (Inference Engine) Convert output data into non-fuzzy values. (defuzzification) Step 1 − Define linguistic variables and terms Linguistic variables are input and output variables in the form of simple words or sentences. For room temperature, cold, warm, hot, etc., are linguistic terms. Temperature (t) = {very-cold, cold, warm, very-warm, hot} Every member of this set is a linguistic term and it can cover some portion of overall temperature values. Step 2 − Construct membership functions for them The membership functions of temperature variable are as shown − Step3 − Construct knowledge base rules Create a matrix of room temperature values versus target temperature values that an air conditioning system is expected to provide. Build a set of rules into the knowledge base in the form of IF-THEN-ELSE structures. Step 4 − Obtain fuzzy value Fuzzy set operations perform evaluation of rules. The operations used for OR and AND are Max and Min respectively. Combine all results of evaluation to form a final result. This result is a fuzzy value. Step 5 − Perform defuzzification Defuzzification is then performed according to membership function for output variable. The key application areas of fuzzy logic are as given − Automotive Systems Automatic Gearboxes Four-Wheel Steering Vehicle environment control Consumer Electronic Goods Hi-Fi Systems Photocopiers Still and Video Cameras Television Domestic Goods Microwave Ovens Refrigerators Toasters Vacuum Cleaners Washing Machines Environment Control Air Conditioners/Dryers/Heaters Humidifiers Mathematical concepts within fuzzy reasoning are very simple. Mathematical concepts within fuzzy reasoning are very simple. You can modify a FLS by just adding or deleting rules due to flexibility of fuzzy logic. You can modify a FLS by just adding or deleting rules due to flexibility of fuzzy logic. Fuzzy logic Systems can take imprecise, distorted, noisy input information. Fuzzy logic Systems can take imprecise, distorted, noisy input information. FLSs are easy to construct and understand. FLSs are easy to construct and understand. Fuzzy logic is a solution to complex problems in all fields of life, including medicine, as it resembles human reasoning and decision making. Fuzzy logic is a solution to complex problems in all fields of life, including medicine, as it resembles human reasoning and decision making. There is no systematic approach to fuzzy system designing. They are understandable only when simple. They are suitable for the problems which do not need high accuracy. Natural Language Processing (NLP) refers to AI method of communicating with an intelligent systems using a natural language such as English. Processing of Natural Language is required when you want an intelligent system like robot to perform as per your instructions, when you want to hear decision from a dialogue based clinical expert system, etc. The field of NLP involves making computers to perform useful tasks with the natural languages humans use. The input and output of an NLP system can be − Speech Written Text There are two components of NLP as given − Understanding involves the following tasks − Mapping the given input in natural language into useful representations. Analyzing different aspects of the language. It is the process of producing meaningful phrases and sentences in the form of natural language from some internal representation. It involves − Text planning − It includes retrieving the relevant content from knowledge base. Text planning − It includes retrieving the relevant content from knowledge base. Sentence planning − It includes choosing required words, forming meaningful phrases, setting tone of the sentence. Sentence planning − It includes choosing required words, forming meaningful phrases, setting tone of the sentence. Text Realization − It is mapping sentence plan into sentence structure. Text Realization − It is mapping sentence plan into sentence structure. The NLU is harder than NLG. NL has an extremely rich form and structure. It is very ambiguous. There can be different levels of ambiguity − Lexical ambiguity − It is at very primitive level such as word-level. Lexical ambiguity − It is at very primitive level such as word-level. For example, treating the word “board” as noun or verb? For example, treating the word “board” as noun or verb? Syntax Level ambiguity − A sentence can be parsed in different ways. Syntax Level ambiguity − A sentence can be parsed in different ways. For example, “He lifted the beetle with red cap.” − Did he use cap to lift the beetle or he lifted a beetle that had red cap? For example, “He lifted the beetle with red cap.” − Did he use cap to lift the beetle or he lifted a beetle that had red cap? Referential ambiguity − Referring to something using pronouns. For example, Rima went to Gauri. She said, “I am tired.” − Exactly who is tired? Referential ambiguity − Referring to something using pronouns. For example, Rima went to Gauri. She said, “I am tired.” − Exactly who is tired? One input can mean different meanings. One input can mean different meanings. Many inputs can mean the same thing. Many inputs can mean the same thing. Phonology − It is study of organizing sound systematically. Phonology − It is study of organizing sound systematically. Morphology − It is a study of construction of words from primitive meaningful units. Morphology − It is a study of construction of words from primitive meaningful units. Morpheme − It is primitive unit of meaning in a language. Morpheme − It is primitive unit of meaning in a language. Syntax − It refers to arranging words to make a sentence. It also involves determining the structural role of words in the sentence and in phrases. Syntax − It refers to arranging words to make a sentence. It also involves determining the structural role of words in the sentence and in phrases. Semantics − It is concerned with the meaning of words and how to combine words into meaningful phrases and sentences. Semantics − It is concerned with the meaning of words and how to combine words into meaningful phrases and sentences. Pragmatics − It deals with using and understanding sentences in different situations and how the interpretation of the sentence is affected. Pragmatics − It deals with using and understanding sentences in different situations and how the interpretation of the sentence is affected. Discourse − It deals with how the immediately preceding sentence can affect the interpretation of the next sentence. Discourse − It deals with how the immediately preceding sentence can affect the interpretation of the next sentence. World Knowledge − It includes the general knowledge about the world. World Knowledge − It includes the general knowledge about the world. There are general five steps − Lexical Analysis − It involves identifying and analyzing the structure of words. Lexicon of a language means the collection of words and phrases in a language. Lexical analysis is dividing the whole chunk of txt into paragraphs, sentences, and words. Lexical Analysis − It involves identifying and analyzing the structure of words. Lexicon of a language means the collection of words and phrases in a language. Lexical analysis is dividing the whole chunk of txt into paragraphs, sentences, and words. Syntactic Analysis (Parsing) − It involves analysis of words in the sentence for grammar and arranging words in a manner that shows the relationship among the words. The sentence such as “The school goes to boy” is rejected by English syntactic analyzer. Syntactic Analysis (Parsing) − It involves analysis of words in the sentence for grammar and arranging words in a manner that shows the relationship among the words. The sentence such as “The school goes to boy” is rejected by English syntactic analyzer. Semantic Analysis − It draws the exact meaning or the dictionary meaning from the text. The text is checked for meaningfulness. It is done by mapping syntactic structures and objects in the task domain. The semantic analyzer disregards sentence such as “hot ice-cream”. Semantic Analysis − It draws the exact meaning or the dictionary meaning from the text. The text is checked for meaningfulness. It is done by mapping syntactic structures and objects in the task domain. The semantic analyzer disregards sentence such as “hot ice-cream”. Discourse Integration − The meaning of any sentence depends upon the meaning of the sentence just before it. In addition, it also brings about the meaning of immediately succeeding sentence. Discourse Integration − The meaning of any sentence depends upon the meaning of the sentence just before it. In addition, it also brings about the meaning of immediately succeeding sentence. Pragmatic Analysis − During this, what was said is re-interpreted on what it actually meant. It involves deriving those aspects of language which require real world knowledge. Pragmatic Analysis − During this, what was said is re-interpreted on what it actually meant. It involves deriving those aspects of language which require real world knowledge. There are a number of algorithms researchers have developed for syntactic analysis, but we consider only the following simple methods − Context-Free Grammar Top-Down Parser Let us see them in detail − It is the grammar that consists rules with a single symbol on the left-hand side of the rewrite rules. Let us create grammar to parse a sentence − “The bird pecks the grains” Articles (DET) − a | an | the Nouns − bird | birds | grain | grains Noun Phrase (NP) − Article + Noun | Article + Adjective + Noun = DET N | DET ADJ N Verbs − pecks | pecking | pecked Verb Phrase (VP) − NP V | V NP Adjectives (ADJ) − beautiful | small | chirping The parse tree breaks down the sentence into structured parts so that the computer can easily understand and process it. In order for the parsing algorithm to construct this parse tree, a set of rewrite rules, which describe what tree structures are legal, need to be constructed. These rules say that a certain symbol may be expanded in the tree by a sequence of other symbols. According to first order logic rule, if there are two strings Noun Phrase (NP) and Verb Phrase (VP), then the string combined by NP followed by VP is a sentence. The rewrite rules for the sentence are as follows − S → NP VP NP → DET N | DET ADJ N VP → V NP Lexocon − DET → a | the ADJ → beautiful | perching N → bird | birds | grain | grains V → peck | pecks | pecking The parse tree can be created as shown − Now consider the above rewrite rules. Since V can be replaced by both, "peck" or "pecks", sentences such as "The bird peck the grains" can be wrongly permitted. i. e. the subject-verb agreement error is approved as correct. Merit − The simplest style of grammar, therefore widely used one. Demerits − They are not highly precise. For example, “The grains peck the bird”, is a syntactically correct according to parser, but even if it makes no sense, parser takes it as a correct sentence. They are not highly precise. For example, “The grains peck the bird”, is a syntactically correct according to parser, but even if it makes no sense, parser takes it as a correct sentence. To bring out high precision, multiple sets of grammar need to be prepared. It may require a completely different sets of rules for parsing singular and plural variations, passive sentences, etc., which can lead to creation of huge set of rules that are unmanageable. To bring out high precision, multiple sets of grammar need to be prepared. It may require a completely different sets of rules for parsing singular and plural variations, passive sentences, etc., which can lead to creation of huge set of rules that are unmanageable. Here, the parser starts with the S symbol and attempts to rewrite it into a sequence of terminal symbols that matches the classes of the words in the input sentence until it consists entirely of terminal symbols. These are then checked with the input sentence to see if it matched. If not, the process is started over again with a different set of rules. This is repeated until a specific rule is found which describes the structure of the sentence. Merit − It is simple to implement. Demerits − It is inefficient, as the search process has to be repeated if an error occurs. Slow speed of working. Expert systems (ES) are one of the prominent research domains of AI. It is introduced by the researchers at Stanford University, Computer Science Department. The expert systems are the computer applications developed to solve complex problems in a particular domain, at the level of extra-ordinary human intelligence and expertise. High performance Understandable Reliable Highly responsive The expert systems are capable of − Advising Instructing and assisting human in decision making Demonstrating Deriving a solution Diagnosing Explaining Interpreting input Predicting results Justifying the conclusion Suggesting alternative options to a problem They are incapable of − Substituting human decision makers Possessing human capabilities Producing accurate output for inadequate knowledge base Refining their own knowledge The components of ES include − Knowledge Base Inference Engine User Interface Let us see them one by one briefly − It contains domain-specific and high-quality knowledge. Knowledge is required to exhibit intelligence. The success of any ES majorly depends upon the collection of highly accurate and precise knowledge. The data is collection of facts. The information is organized as data and facts about the task domain. Data, information, and past experience combined together are termed as knowledge. The knowledge base of an ES is a store of both, factual and heuristic knowledge. Factual Knowledge − It is the information widely accepted by the Knowledge Engineers and scholars in the task domain. Factual Knowledge − It is the information widely accepted by the Knowledge Engineers and scholars in the task domain. Heuristic Knowledge − It is about practice, accurate judgement, one’s ability of evaluation, and guessing. Heuristic Knowledge − It is about practice, accurate judgement, one’s ability of evaluation, and guessing. It is the method used to organize and formalize the knowledge in the knowledge base. It is in the form of IF-THEN-ELSE rules. The success of any expert system majorly depends on the quality, completeness, and accuracy of the information stored in the knowledge base. The knowledge base is formed by readings from various experts, scholars, and the Knowledge Engineers. The knowledge engineer is a person with the qualities of empathy, quick learning, and case analyzing skills. He acquires information from subject expert by recording, interviewing, and observing him at work, etc. He then categorizes and organizes the information in a meaningful way, in the form of IF-THEN-ELSE rules, to be used by interference machine. The knowledge engineer also monitors the development of the ES. Use of efficient procedures and rules by the Inference Engine is essential in deducting a correct, flawless solution. In case of knowledge-based ES, the Inference Engine acquires and manipulates the knowledge from the knowledge base to arrive at a particular solution. In case of rule based ES, it − Applies rules repeatedly to the facts, which are obtained from earlier rule application. Applies rules repeatedly to the facts, which are obtained from earlier rule application. Adds new knowledge into the knowledge base if required. Adds new knowledge into the knowledge base if required. Resolves rules conflict when multiple rules are applicable to a particular case. Resolves rules conflict when multiple rules are applicable to a particular case. To recommend a solution, the Inference Engine uses the following strategies − Forward Chaining Backward Chaining It is a strategy of an expert system to answer the question, “What can happen next?” Here, the Inference Engine follows the chain of conditions and derivations and finally deduces the outcome. It considers all the facts and rules, and sorts them before concluding to a solution. This strategy is followed for working on conclusion, result, or effect. For example, prediction of share market status as an effect of changes in interest rates. With this strategy, an expert system finds out the answer to the question, “Why this happened?” On the basis of what has already happened, the Inference Engine tries to find out which conditions could have happened in the past for this result. This strategy is followed for finding out cause or reason. For example, diagnosis of blood cancer in humans. User interface provides interaction between user of the ES and the ES itself. It is generally Natural Language Processing so as to be used by the user who is well-versed in the task domain. The user of the ES need not be necessarily an expert in Artificial Intelligence. It explains how the ES has arrived at a particular recommendation. The explanation may appear in the following forms − Natural language displayed on screen. Verbal narrations in natural language. Listing of rule numbers displayed on the screen. The user interface makes it easy to trace the credibility of the deductions. It should help users to accomplish their goals in shortest possible way. It should help users to accomplish their goals in shortest possible way. It should be designed to work for user’s existing or desired work practices. It should be designed to work for user’s existing or desired work practices. Its technology should be adaptable to user’s requirements; not the other way round. Its technology should be adaptable to user’s requirements; not the other way round. It should make efficient use of user input. It should make efficient use of user input. No technology can offer easy and complete solution. Large systems are costly, require significant development time, and computer resources. ESs have their limitations which include − Limitations of the technology Difficult knowledge acquisition ES are difficult to maintain High development costs The following table shows where ES can be applied. There are several levels of ES technologies available. Expert systems technologies include − Expert System Development Environment − The ES development environment includes hardware and tools. They are − Workstations, minicomputers, mainframes. High level Symbolic Programming Languages such as LISt Programming (LISP) and PROgrammation en LOGique (PROLOG). Large databases. Expert System Development Environment − The ES development environment includes hardware and tools. They are − Workstations, minicomputers, mainframes. Workstations, minicomputers, mainframes. High level Symbolic Programming Languages such as LISt Programming (LISP) and PROgrammation en LOGique (PROLOG). High level Symbolic Programming Languages such as LISt Programming (LISP) and PROgrammation en LOGique (PROLOG). Large databases. Large databases. Tools − They reduce the effort and cost involved in developing an expert system to large extent. Powerful editors and debugging tools with multi-windows. They provide rapid prototyping Have Inbuilt definitions of model, knowledge representation, and inference design. Tools − They reduce the effort and cost involved in developing an expert system to large extent. Powerful editors and debugging tools with multi-windows. Powerful editors and debugging tools with multi-windows. They provide rapid prototyping They provide rapid prototyping Have Inbuilt definitions of model, knowledge representation, and inference design. Have Inbuilt definitions of model, knowledge representation, and inference design. Shells − A shell is nothing but an expert system without knowledge base. A shell provides the developers with knowledge acquisition, inference engine, user interface, and explanation facility. For example, few shells are given below − Java Expert System Shell (JESS) that provides fully developed Java API for creating an expert system. Vidwan, a shell developed at the National Centre for Software Technology, Mumbai in 1993. It enables knowledge encoding in the form of IF-THEN rules. Shells − A shell is nothing but an expert system without knowledge base. A shell provides the developers with knowledge acquisition, inference engine, user interface, and explanation facility. For example, few shells are given below − Java Expert System Shell (JESS) that provides fully developed Java API for creating an expert system. Java Expert System Shell (JESS) that provides fully developed Java API for creating an expert system. Vidwan, a shell developed at the National Centre for Software Technology, Mumbai in 1993. It enables knowledge encoding in the form of IF-THEN rules. Vidwan, a shell developed at the National Centre for Software Technology, Mumbai in 1993. It enables knowledge encoding in the form of IF-THEN rules. The process of ES development is iterative. Steps in developing the ES include − The problem must be suitable for an expert system to solve it. Find the experts in task domain for the ES project. Establish cost-effectiveness of the system. Identify the ES Technology Identify the ES Technology Know and establish the degree of integration with the other systems and databases. Know and establish the degree of integration with the other systems and databases. Realize how the concepts can represent the domain knowledge best. Realize how the concepts can represent the domain knowledge best. From Knowledge Base: The knowledge engineer works to − Acquire domain knowledge from the expert. Represent it in the form of If-THEN-ELSE rules. The knowledge engineer uses sample cases to test the prototype for any deficiencies in performance. The knowledge engineer uses sample cases to test the prototype for any deficiencies in performance. End users test the prototypes of the ES. End users test the prototypes of the ES. Test and ensure the interaction of the ES with all elements of its environment, including end users, databases, and other information systems. Test and ensure the interaction of the ES with all elements of its environment, including end users, databases, and other information systems. Document the ES project well. Document the ES project well. Train the user to use ES. Train the user to use ES. Keep the knowledge base up-to-date by regular review and update. Keep the knowledge base up-to-date by regular review and update. Cater for new interfaces with other information systems, as those systems evolve. Cater for new interfaces with other information systems, as those systems evolve. Availability − They are easily available due to mass production of software. Availability − They are easily available due to mass production of software. Less Production Cost − Production cost is reasonable. This makes them affordable. Less Production Cost − Production cost is reasonable. This makes them affordable. Speed − They offer great speed. They reduce the amount of work an individual puts in. Speed − They offer great speed. They reduce the amount of work an individual puts in. Less Error Rate − Error rate is low as compared to human errors. Less Error Rate − Error rate is low as compared to human errors. Reducing Risk − They can work in the environment dangerous to humans. Reducing Risk − They can work in the environment dangerous to humans. Steady response − They work steadily without getting motional, tensed or fatigued. Steady response − They work steadily without getting motional, tensed or fatigued. Robotics is a domain in artificial intelligence that deals with the study of creating intelligent and efficient robots. Robots are the artificial agents acting in real world environment. Robots are aimed at manipulating the objects by perceiving, picking, moving, modifying the physical properties of object, destroying it, or to have an effect thereby freeing manpower from doing repetitive functions without getting bored, distracted, or exhausted. Robotics is a branch of AI, which is composed of Electrical Engineering, Mechanical Engineering, and Computer Science for designing, construction, and application of robots. The robots have mechanical construction, form, or shape designed to accomplish a particular task. The robots have mechanical construction, form, or shape designed to accomplish a particular task. They have electrical components which power and control the machinery. They have electrical components which power and control the machinery. They contain some level of computer program that determines what, when and how a robot does something. They contain some level of computer program that determines what, when and how a robot does something. Here is the difference between the two − Locomotion is the mechanism that makes a robot capable of moving in its environment. There are various types of locomotions − Legged Wheeled Combination of Legged and Wheeled Locomotion Tracked slip/skid This type of locomotion consumes more power while demonstrating walk, jump, trot, hop, climb up or down, etc. This type of locomotion consumes more power while demonstrating walk, jump, trot, hop, climb up or down, etc. It requires more number of motors to accomplish a movement. It is suited for rough as well as smooth terrain where irregular or too smooth surface makes it consume more power for a wheeled locomotion. It is little difficult to implement because of stability issues. It requires more number of motors to accomplish a movement. It is suited for rough as well as smooth terrain where irregular or too smooth surface makes it consume more power for a wheeled locomotion. It is little difficult to implement because of stability issues. It comes with the variety of one, two, four, and six legs. If a robot has multiple legs then leg coordination is necessary for locomotion. It comes with the variety of one, two, four, and six legs. If a robot has multiple legs then leg coordination is necessary for locomotion. The total number of possible gaits (a periodic sequence of lift and release events for each of the total legs) a robot can travel depends upon the number of its legs. If a robot has k legs, then the number of possible events N = (2k-1)!. In case of a two-legged robot (k=2), the number of possible events is N = (2k-1)! = (2*2-1)! = 3! = 6. Hence there are six possible different events − Lifting the Left leg Releasing the Left leg Lifting the Right leg Releasing the Right leg Lifting both the legs together Releasing both the legs together In case of k=6 legs, there are 39916800 possible events. Hence the complexity of robots is directly proportional to the number of legs. It requires fewer number of motors to accomplish a movement. It is little easy to implement as there are less stability issues in case of more number of wheels. It is power efficient as compared to legged locomotion. Standard wheel − Rotates around the wheel axle and around the contact Standard wheel − Rotates around the wheel axle and around the contact Castor wheel − Rotates around the wheel axle and the offset steering joint. Castor wheel − Rotates around the wheel axle and the offset steering joint. Swedish 45o and Swedish 90o wheels − Omni-wheel, rotates around the contact point, around the wheel axle, and around the rollers. Swedish 45o and Swedish 90o wheels − Omni-wheel, rotates around the contact point, around the wheel axle, and around the rollers. Ball or spherical wheel − Omnidirectional wheel, technically difficult to implement. Ball or spherical wheel − Omnidirectional wheel, technically difficult to implement. In this type, the vehicles use tracks as in a tank. The robot is steered by moving the tracks with different speeds in the same or opposite direction. It offers stability because of large contact area of track and ground. Robots are constructed with the following − Power Supply − The robots are powered by batteries, solar power, hydraulic, or pneumatic power sources. Power Supply − The robots are powered by batteries, solar power, hydraulic, or pneumatic power sources. Actuators − They convert energy into movement. Actuators − They convert energy into movement. Electric motors (AC/DC) − They are required for rotational movement. Electric motors (AC/DC) − They are required for rotational movement. Pneumatic Air Muscles − They contract almost 40% when air is sucked in them. Pneumatic Air Muscles − They contract almost 40% when air is sucked in them. Muscle Wires − They contract by 5% when electric current is passed through them. Muscle Wires − They contract by 5% when electric current is passed through them. Piezo Motors and Ultrasonic Motors − Best for industrial robots. Piezo Motors and Ultrasonic Motors − Best for industrial robots. Sensors − They provide knowledge of real time information on the task environment. Robots are equipped with vision sensors to be to compute the depth in the environment. A tactile sensor imitates the mechanical properties of touch receptors of human fingertips. Sensors − They provide knowledge of real time information on the task environment. Robots are equipped with vision sensors to be to compute the depth in the environment. A tactile sensor imitates the mechanical properties of touch receptors of human fingertips. This is a technology of AI with which the robots can see. The computer vision plays vital role in the domains of safety, security, health, access, and entertainment. Computer vision automatically extracts, analyzes, and comprehends useful information from a single image or an array of images. This process involves development of algorithms to accomplish automatic visual comprehension. This involves − Power supply Image acquisition device such as camera A processor A software A display device for monitoring the system Accessories such as camera stands, cables, and connectors OCR − In the domain of computers, Optical Character Reader, a software to convert scanned documents into editable text, which accompanies a scanner. OCR − In the domain of computers, Optical Character Reader, a software to convert scanned documents into editable text, which accompanies a scanner. Face Detection − Many state-of-the-art cameras come with this feature, which enables to read the face and take the picture of that perfect expression. It is used to let a user access the software on correct match. Face Detection − Many state-of-the-art cameras come with this feature, which enables to read the face and take the picture of that perfect expression. It is used to let a user access the software on correct match. Object Recognition − They are installed in supermarkets, cameras, high-end cars such as BMW, GM, and Volvo. Object Recognition − They are installed in supermarkets, cameras, high-end cars such as BMW, GM, and Volvo. Estimating Position − It is estimating position of an object with respect to camera as in position of tumor in human’s body. Estimating Position − It is estimating position of an object with respect to camera as in position of tumor in human’s body. Agriculture Autonomous vehicles Biometrics Character recognition Forensics, security, and surveillance Industrial quality inspection Face recognition Gesture analysis Geoscience Medical imagery Pollution monitoring Process control Remote sensing Robotics Transport The robotics has been instrumental in the various domains such as − Industries − Robots are used for handling material, cutting, welding, color coating, drilling, polishing, etc. Industries − Robots are used for handling material, cutting, welding, color coating, drilling, polishing, etc. Military − Autonomous robots can reach inaccessible and hazardous zones during war. A robot named Daksh, developed by Defense Research and Development Organization (DRDO), is in function to destroy life-threatening objects safely. Military − Autonomous robots can reach inaccessible and hazardous zones during war. A robot named Daksh, developed by Defense Research and Development Organization (DRDO), is in function to destroy life-threatening objects safely. Medicine − The robots are capable of carrying out hundreds of clinical tests simultaneously, rehabilitating permanently disabled people, and performing complex surgeries such as brain tumors. Medicine − The robots are capable of carrying out hundreds of clinical tests simultaneously, rehabilitating permanently disabled people, and performing complex surgeries such as brain tumors. Exploration − The robot rock climbers used for space exploration, underwater drones used for ocean exploration are to name a few. Exploration − The robot rock climbers used for space exploration, underwater drones used for ocean exploration are to name a few. Entertainment − Disney’s engineers have created hundreds of robots for movie making. Entertainment − Disney’s engineers have created hundreds of robots for movie making. Yet another research area in AI, neural networks, is inspired from the natural neural network of human nervous system. The inventor of the first neurocomputer, Dr. Robert Hecht-Nielsen, defines a neural network as − The idea of ANNs is based on the belief that working of human brain by making the right connections, can be imitated using silicon and wires as living neurons and dendrites. The human brain is composed of 86 billion nerve cells called neurons. They are connected to other thousand cells by Axons. Stimuli from external environment or inputs from sensory organs are accepted by dendrites. These inputs create electric impulses, which quickly travel through the neural network. A neuron can then send the message to other neuron to handle the issue or does not send it forward. ANNs are composed of multiple nodes, which imitate biological neurons of human brain. The neurons are connected by links and they interact with each other. The nodes can take input data and perform simple operations on the data. The result of these operations is passed to other neurons. The output at each node is called its activation or node value. Each link is associated with weight. ANNs are capable of learning, which takes place by altering weight values. The following illustration shows a simple ANN − There are two Artificial Neural Network topologies − FeedForward and Feedback. In this ANN, the information flow is unidirectional. A unit sends information to other unit from which it does not receive any information. There are no feedback loops. They are used in pattern generation/recognition/classification. They have fixed inputs and outputs. Here, feedback loops are allowed. They are used in content addressable memories. In the topology diagrams shown, each arrow represents a connection between two neurons and indicates the pathway for the flow of information. Each connection has a weight, an integer number that controls the signal between the two neurons. If the network generates a “good or desired” output, there is no need to adjust the weights. However, if the network generates a “poor or undesired” output or an error, then the system alters the weights in order to improve subsequent results. ANNs are capable of learning and they need to be trained. There are several learning strategies − Supervised Learning − It involves a teacher that is scholar than the ANN itself. For example, the teacher feeds some example data about which the teacher already knows the answers. For example, pattern recognizing. The ANN comes up with guesses while recognizing. Then the teacher provides the ANN with the answers. The network then compares it guesses with the teacher’s “correct” answers and makes adjustments according to errors. Supervised Learning − It involves a teacher that is scholar than the ANN itself. For example, the teacher feeds some example data about which the teacher already knows the answers. For example, pattern recognizing. The ANN comes up with guesses while recognizing. Then the teacher provides the ANN with the answers. The network then compares it guesses with the teacher’s “correct” answers and makes adjustments according to errors. Unsupervised Learning − It is required when there is no example data set with known answers. For example, searching for a hidden pattern. In this case, clustering i.e. dividing a set of elements into groups according to some unknown pattern is carried out based on the existing data sets present. Unsupervised Learning − It is required when there is no example data set with known answers. For example, searching for a hidden pattern. In this case, clustering i.e. dividing a set of elements into groups according to some unknown pattern is carried out based on the existing data sets present. Reinforcement Learning − This strategy built on observation. The ANN makes a decision by observing its environment. If the observation is negative, the network adjusts its weights to be able to make a different required decision the next time. Reinforcement Learning − This strategy built on observation. The ANN makes a decision by observing its environment. If the observation is negative, the network adjusts its weights to be able to make a different required decision the next time. It is the training or learning algorithm. It learns by example. If you submit to the algorithm the example of what you want the network to do, it changes the network’s weights so that it can produce desired output for a particular input on finishing the training. Back Propagation networks are ideal for simple Pattern Recognition and Mapping Tasks. These are the graphical structures used to represent the probabilistic relationship among a set of random variables. Bayesian networks are also called Belief Networks or Bayes Nets. BNs reason about uncertain domain. In these networks, each node represents a random variable with specific propositions. For example, in a medical diagnosis domain, the node Cancer represents the proposition that a patient has cancer. The edges connecting the nodes represent probabilistic dependencies among those random variables. If out of two nodes, one is affecting the other then they must be directly connected in the directions of the effect. The strength of the relationship between variables is quantified by the probability associated with each node. There is an only constraint on the arcs in a BN that you cannot return to a node simply by following directed arcs. Hence the BNs are called Directed Acyclic Graphs (DAGs). BNs are capable of handling multivalued variables simultaneously. The BN variables are composed of two dimensions − Range of prepositions Probability assigned to each of the prepositions. Consider a finite set X = {X1, X2, ...,Xn} of discrete random variables, where each variable Xi may take values from a finite set, denoted by Val(Xi). If there is a directed link from variable Xi to variable, Xj, then variable Xi will be a parent of variable Xj showing direct dependencies between the variables. The structure of BN is ideal for combining prior knowledge and observed data. BN can be used to learn the causal relationships and understand various problem domains and to predict future events, even in case of missing data. A knowledge engineer can build a Bayesian network. There are a number of steps the knowledge engineer needs to take while building it. Example problem − Lung cancer. A patient has been suffering from breathlessness. He visits the doctor, suspecting he has lung cancer. The doctor knows that barring lung cancer, there are various other possible diseases the patient might have such as tuberculosis and bronchitis. Gather Relevant Information of Problem Is the patient a smoker? If yes, then high chances of cancer and bronchitis. Is the patient exposed to air pollution? If yes, what sort of air pollution? Take an X-Ray positive X-ray would indicate either TB or lung cancer. Identify Interesting Variables The knowledge engineer tries to answer the questions − Which nodes to represent? What values can they take? In which state can they be? For now let us consider nodes, with only discrete values. The variable must take on exactly one of these values at a time. Common types of discrete nodes are − Boolean nodes − They represent propositions, taking binary values TRUE (T) and FALSE (F). Boolean nodes − They represent propositions, taking binary values TRUE (T) and FALSE (F). Ordered values − A node Pollution might represent and take values from {low, medium, high} describing degree of a patient’s exposure to pollution. Ordered values − A node Pollution might represent and take values from {low, medium, high} describing degree of a patient’s exposure to pollution. Integral values − A node called Age might represent patient’s age with possible values from 1 to 120. Even at this early stage, modeling choices are being made. Integral values − A node called Age might represent patient’s age with possible values from 1 to 120. Even at this early stage, modeling choices are being made. Possible nodes and values for the lung cancer example − Create Arcs between Nodes Topology of the network should capture qualitative relationships between variables. For example, what causes a patient to have lung cancer? - Pollution and smoking. Then add arcs from node Pollution and node Smoker to node Lung-Cancer. Similarly if patient has lung cancer, then X-ray result will be positive. Then add arcs from node Lung-Cancer to node X-Ray. Specify Topology Conventionally, BNs are laid out so that the arcs point from top to bottom. The set of parent nodes of a node X is given by Parents(X). The Lung-Cancer node has two parents (reasons or causes): Pollution and Smoker, while node Smoker is an ancestor of node X-Ray. Similarly, X-Ray is a child (consequence or effects) of node Lung-Cancer and successor of nodes Smoker and Pollution. Conditional Probabilities Now quantify the relationships between connected nodes: this is done by specifying a conditional probability distribution for each node. As only discrete variables are considered here, this takes the form of a Conditional Probability Table (CPT). First, for each node we need to look at all the possible combinations of values of those parent nodes. Each such combination is called an instantiation of the parent set. For each distinct instantiation of parent node values, we need to specify the probability that the child will take. For example, the Lung-Cancer node’s parents are Pollution and Smoking. They take the possible values = { (H,T), ( H,F), (L,T), (L,F)}. The CPT specifies the probability of cancer for each of these cases as <0.05, 0.02, 0.03, 0.001> respectively. Each node will have conditional probability associated as follows − They can perform tasks that are easy for a human but difficult for a machine − Aerospace − Autopilot aircrafts, aircraft fault detection. Aerospace − Autopilot aircrafts, aircraft fault detection. Automotive − Automobile guidance systems. Automotive − Automobile guidance systems. Military − Weapon orientation and steering, target tracking, object discrimination, facial recognition, signal/image identification. Military − Weapon orientation and steering, target tracking, object discrimination, facial recognition, signal/image identification. Electronics − Code sequence prediction, IC chip layout, chip failure analysis, machine vision, voice synthesis. Electronics − Code sequence prediction, IC chip layout, chip failure analysis, machine vision, voice synthesis. Financial − Real estate appraisal, loan advisor, mortgage screening, corporate bond rating, portfolio trading program, corporate financial analysis, currency value prediction, document readers, credit application evaluators. Financial − Real estate appraisal, loan advisor, mortgage screening, corporate bond rating, portfolio trading program, corporate financial analysis, currency value prediction, document readers, credit application evaluators. Industrial − Manufacturing process control, product design and analysis, quality inspection systems, welding quality analysis, paper quality prediction, chemical product design analysis, dynamic modeling of chemical process systems, machine maintenance analysis, project bidding, planning, and management. Industrial − Manufacturing process control, product design and analysis, quality inspection systems, welding quality analysis, paper quality prediction, chemical product design analysis, dynamic modeling of chemical process systems, machine maintenance analysis, project bidding, planning, and management. Medical − Cancer cell analysis, EEG and ECG analysis, prosthetic design, transplant time optimizer. Medical − Cancer cell analysis, EEG and ECG analysis, prosthetic design, transplant time optimizer. Speech − Speech recognition, speech classification, text to speech conversion. Speech − Speech recognition, speech classification, text to speech conversion. Telecommunications − Image and data compression, automated information services, real-time spoken language translation. Telecommunications − Image and data compression, automated information services, real-time spoken language translation. Transportation − Truck Brake system diagnosis, vehicle scheduling, routing systems. Transportation − Truck Brake system diagnosis, vehicle scheduling, routing systems. Software − Pattern Recognition in facial recognition, optical character recognition, etc. Software − Pattern Recognition in facial recognition, optical character recognition, etc. Time Series Prediction − ANNs are used to make predictions on stocks and natural calamities. Time Series Prediction − ANNs are used to make predictions on stocks and natural calamities. Signal Processing − Neural networks can be trained to process an audio signal and filter it appropriately in the hearing aids. Signal Processing − Neural networks can be trained to process an audio signal and filter it appropriately in the hearing aids. Control − ANNs are often used to make steering decisions of physical vehicles. Control − ANNs are often used to make steering decisions of physical vehicles. Anomaly Detection − As ANNs are expert at recognizing patterns, they can also be trained to generate an output when something unusual occurs that misfits the pattern. Anomaly Detection − As ANNs are expert at recognizing patterns, they can also be trained to generate an output when something unusual occurs that misfits the pattern. AI is developing with such an incredible speed, sometimes it seems magical. There is an opinion among researchers and developers that AI could grow so immensely strong that it would be difficult for humans to control. Humans developed AI systems by introducing into them every possible intelligence they could, for which the humans themselves now seem threatened. An AI program that recognizes speech and understands natural language is theoretically capable of understanding each conversation on e-mails and telephones. AI systems have already started replacing the human beings in few industries. It should not replace people in the sectors where they are holding dignified positions which are pertaining to ethics such as nursing, surgeon, judge, police officer, etc. The self-improving AI systems can become so mighty than humans that could be very difficult to stop from achieving their goals, which may lead to unintended consequences. Here is the list of frequently used terms in the domain of AI − Agent Agents are systems or software programs capable of autonomous, purposeful and reasoning directed towards one or more goals. They are also called assistants, brokers, bots, droids, intelligent agents, and software agents. Autonomous Robot Robot free from external control or influence and able to control itself independently. Backward Chaining Strategy of working backward for Reason/Cause of a problem. Blackboard It is the memory inside computer, which is used for communication between the cooperating expert systems. Environment It is the part of real or computational world inhabited by the agent. Forward Chaining Strategy of working forward for conclusion/solution of a problem. Heuristics It is the knowledge based on Trial-and-error, evaluations, and experimentation. Knowledge Engineering Acquiring knowledge from human experts and other resources. Percepts It is the format in which the agent obtains information about the environment. Pruning Overriding unnecessary and irrelevant considerations in AI systems. Rule It is a format of representing knowledge base in Expert System. It is in the form of IF-THEN-ELSE. Shell A shell is a software that helps in designing inference engine, knowledge base, and user interface of an expert system. Task It is the goal the agent is tries to accomplish. Turing Test A test developed by Allan Turing to test the intelligence of a machine as compared to human intelligence. 78 Lectures 7 hours Arnab Chakraborty 87 Lectures 9.5 hours DigiFisk (Programming Is Fun) 10 Lectures 1 hours Nikoloz Sanakoevi 15 Lectures 54 mins Mukund Kumar Mishra 11 Lectures 1 hours Gilad James, PhD 20 Lectures 2 hours Gilad James, PhD Print Add Notes Bookmark this page
[ { "code": null, "e": 2167, "s": 1889, "text": "Since the invention of computers or machines, their capability to perform various tasks went on growing exponentially. Humans have developed the power of computer systems in terms of their diverse working domains, their increasing speed, and reducing size with respect to time." }, { "code": null, "e": 2301, "s": 2167, "text": "A branch of Computer Science named Artificial Intelligence pursues creating the computers or machines as intelligent as human beings." }, { "code": null, "e": 2478, "s": 2301, "text": "According to the father of Artificial Intelligence, John McCarthy, it is “The science and engineering of making intelligent machines, especially intelligent computer programs”." }, { "code": null, "e": 2649, "s": 2478, "text": "Artificial Intelligence is a way of making a computer, a computer-controlled robot, or a software think intelligently, in the similar manner the intelligent humans think." }, { "code": null, "e": 2877, "s": 2649, "text": "AI is accomplished by studying how human brain thinks, and how humans learn, decide, and work while trying to solve a problem, and then using the outcomes of this study as a basis of developing intelligent software and systems." }, { "code": null, "e": 3022, "s": 2877, "text": "While exploiting the power of the computer systems, the curiosity of human, lead him to wonder, “Can a machine think and behave like humans do?”" }, { "code": null, "e": 3162, "s": 3022, "text": "Thus, the development of AI started with the intention of creating similar intelligence in machines that we find and regard high in humans." }, { "code": null, "e": 3288, "s": 3162, "text": "To Create Expert Systems − The systems which exhibit intelligent behavior, learn, demonstrate, explain, and advice its users." }, { "code": null, "e": 3414, "s": 3288, "text": "To Create Expert Systems − The systems which exhibit intelligent behavior, learn, demonstrate, explain, and advice its users." }, { "code": null, "e": 3532, "s": 3414, "text": "To Implement Human Intelligence in Machines − Creating systems that understand, think, learn, and behave like humans." }, { "code": null, "e": 3650, "s": 3532, "text": "To Implement Human Intelligence in Machines − Creating systems that understand, think, learn, and behave like humans." }, { "code": null, "e": 3964, "s": 3650, "text": "Artificial intelligence is a science and technology based on disciplines such as Computer Science, Biology, Psychology, Linguistics, Mathematics, and Engineering. A major thrust of AI is in the development of computer functions associated with human intelligence, such as reasoning, learning, and problem solving." }, { "code": null, "e": 4061, "s": 3964, "text": "Out of the following areas, one or multiple areas can contribute to build an intelligent system." }, { "code": null, "e": 4130, "s": 4061, "text": "The programming without and with AI is different in following ways −" }, { "code": null, "e": 4196, "s": 4130, "text": "In the real world, the knowledge has some unwelcomed properties −" }, { "code": null, "e": 4238, "s": 4196, "text": "Its volume is huge, next to unimaginable." }, { "code": null, "e": 4282, "s": 4238, "text": "It is not well-organized or well-formatted." }, { "code": null, "e": 4312, "s": 4282, "text": "It keeps changing constantly." }, { "code": null, "e": 4404, "s": 4312, "text": "AI Technique is a manner to organize and use the knowledge efficiently in such a way that −" }, { "code": null, "e": 4459, "s": 4404, "text": "It should be perceivable by the people who provide it." }, { "code": null, "e": 4509, "s": 4459, "text": "It should be easily modifiable to correct errors." }, { "code": null, "e": 4587, "s": 4509, "text": "It should be useful in many situations though it is incomplete or inaccurate." }, { "code": null, "e": 4676, "s": 4587, "text": "AI techniques elevate the speed of execution of the complex program it is equipped with." }, { "code": null, "e": 4725, "s": 4676, "text": "AI has been dominant in various fields such as −" }, { "code": null, "e": 4908, "s": 4725, "text": "Gaming − AI plays crucial role in strategic games such as chess, poker, tic-tac-toe, etc., where machine can think of large number of possible positions based on heuristic knowledge." }, { "code": null, "e": 5091, "s": 4908, "text": "Gaming − AI plays crucial role in strategic games such as chess, poker, tic-tac-toe, etc., where machine can think of large number of possible positions based on heuristic knowledge." }, { "code": null, "e": 5218, "s": 5091, "text": "Natural Language Processing − It is possible to interact with the computer that understands natural language spoken by humans." }, { "code": null, "e": 5345, "s": 5218, "text": "Natural Language Processing − It is possible to interact with the computer that understands natural language spoken by humans." }, { "code": null, "e": 5533, "s": 5345, "text": "Expert Systems − There are some applications which integrate machine, software, and special information to impart reasoning and advising. They provide explanation and advice to the users." }, { "code": null, "e": 5721, "s": 5533, "text": "Expert Systems − There are some applications which integrate machine, software, and special information to impart reasoning and advising. They provide explanation and advice to the users." }, { "code": null, "e": 6123, "s": 5721, "text": "Vision Systems − These systems understand, interpret, and comprehend visual input on the computer. For example,\n\nA spying aeroplane takes photographs, which are used to figure out spatial information or map of the areas.\nDoctors use clinical expert system to diagnose the patient.\nPolice use computer software that can recognize the face of criminal with the stored portrait made by forensic artist.\n\n" }, { "code": null, "e": 6235, "s": 6123, "text": "Vision Systems − These systems understand, interpret, and comprehend visual input on the computer. For example," }, { "code": null, "e": 6343, "s": 6235, "text": "A spying aeroplane takes photographs, which are used to figure out spatial information or map of the areas." }, { "code": null, "e": 6451, "s": 6343, "text": "A spying aeroplane takes photographs, which are used to figure out spatial information or map of the areas." }, { "code": null, "e": 6511, "s": 6451, "text": "Doctors use clinical expert system to diagnose the patient." }, { "code": null, "e": 6571, "s": 6511, "text": "Doctors use clinical expert system to diagnose the patient." }, { "code": null, "e": 6690, "s": 6571, "text": "Police use computer software that can recognize the face of criminal with the stored portrait made by forensic artist." }, { "code": null, "e": 6809, "s": 6690, "text": "Police use computer software that can recognize the face of criminal with the stored portrait made by forensic artist." }, { "code": null, "e": 7090, "s": 6809, "text": "Speech Recognition − Some intelligent systems are capable of hearing and comprehending the language in terms of sentences and their meanings while a human talks to it. It can handle different accents, slang words, noise in the background, change in human’s noise due to cold, etc." }, { "code": null, "e": 7371, "s": 7090, "text": "Speech Recognition − Some intelligent systems are capable of hearing and comprehending the language in terms of sentences and their meanings while a human talks to it. It can handle different accents, slang words, noise in the background, change in human’s noise due to cold, etc." }, { "code": null, "e": 7579, "s": 7371, "text": "Handwriting Recognition − The handwriting recognition software reads the text written on paper by a pen or on screen by a stylus. It can recognize the shapes of the letters and convert it into editable text." }, { "code": null, "e": 7787, "s": 7579, "text": "Handwriting Recognition − The handwriting recognition software reads the text written on paper by a pen or on screen by a stylus. It can recognize the shapes of the letters and convert it into editable text." }, { "code": null, "e": 8192, "s": 7787, "text": "Intelligent Robots − Robots are able to perform the tasks given by a human. They have sensors to detect physical data from the real world such as light, heat, temperature, movement, sound, bump, and pressure. They have efficient processors, multiple sensors and huge memory, to exhibit intelligence. In addition, they are capable of learning from their mistakes and they can adapt to the new environment." }, { "code": null, "e": 8597, "s": 8192, "text": "Intelligent Robots − Robots are able to perform the tasks given by a human. They have sensors to detect physical data from the real world such as light, heat, temperature, movement, sound, bump, and pressure. They have efficient processors, multiple sensors and huge memory, to exhibit intelligence. In addition, they are capable of learning from their mistakes and they can adapt to the new environment." }, { "code": null, "e": 8645, "s": 8597, "text": "Here is the history of AI during 20th century −" }, { "code": null, "e": 8762, "s": 8645, "text": "Karel Čapek play named “Rossum's Universal Robots” (RUR) opens in London, first use of the word \"robot\" in English." }, { "code": null, "e": 8800, "s": 8762, "text": "Foundations for neural networks laid." }, { "code": null, "e": 8870, "s": 8800, "text": "Isaac Asimov, a Columbia University alumni, coined the term Robotics." }, { "code": null, "e": 9061, "s": 8870, "text": "Alan Turing introduced Turing Test for evaluation of intelligence and published Computing Machinery and Intelligence. Claude Shannon published Detailed Analysis of Chess Playing as a search." }, { "code": null, "e": 9193, "s": 9061, "text": "John McCarthy coined the term Artificial Intelligence. Demonstration of the first running AI program at Carnegie Mellon University." }, { "code": null, "e": 9249, "s": 9193, "text": "John McCarthy invents LISP programming language for AI." }, { "code": null, "e": 9392, "s": 9249, "text": "Danny Bobrow's dissertation at MIT showed that computers can understand natural language well enough to solve algebra word problems correctly." }, { "code": null, "e": 9492, "s": 9392, "text": "Joseph Weizenbaum at MIT built ELIZA, an interactive problem that carries on a dialogue in English." }, { "code": null, "e": 9620, "s": 9492, "text": "Scientists at Stanford Research Institute Developed Shakey, a robot, equipped with locomotion, perception, and problem solving." }, { "code": null, "e": 9768, "s": 9620, "text": "The Assembly Robotics group at Edinburgh University built Freddy, the Famous Scottish Robot, capable of using vision to locate and assemble models." }, { "code": null, "e": 9844, "s": 9768, "text": "The first computer-controlled autonomous vehicle, Stanford Cart, was built." }, { "code": null, "e": 9910, "s": 9844, "text": "Harold Cohen created and demonstrated the drawing program, Aaron." }, { "code": null, "e": 9946, "s": 9910, "text": "Major advances in all areas of AI −" }, { "code": null, "e": 9993, "s": 9946, "text": "Significant demonstrations in machine learning" }, { "code": null, "e": 10014, "s": 9993, "text": "Case-based reasoning" }, { "code": null, "e": 10035, "s": 10014, "text": "Multi-agent planning" }, { "code": null, "e": 10046, "s": 10035, "text": "Scheduling" }, { "code": null, "e": 10071, "s": 10046, "text": "Data mining, Web Crawler" }, { "code": null, "e": 10118, "s": 10071, "text": "natural language understanding and translation" }, { "code": null, "e": 10142, "s": 10118, "text": "Vision, Virtual Reality" }, { "code": null, "e": 10148, "s": 10142, "text": "Games" }, { "code": null, "e": 10229, "s": 10148, "text": "The Deep Blue Chess Program beats the then world chess champion, Garry Kasparov." }, { "code": null, "e": 10427, "s": 10229, "text": "Interactive robot pets become commercially available. MIT displays Kismet, a robot with a face that expresses emotions. The robot Nomad explores remote regions of Antarctica and locates meteorites." }, { "code": null, "e": 10589, "s": 10427, "text": "While studying artificially intelligence, you need to know what intelligence is. This chapter covers Idea of intelligence, types, and components of intelligence." }, { "code": null, "e": 10861, "s": 10589, "text": "The ability of a system to calculate, reason, perceive relationships and analogies, learn from experience, store and retrieve information from memory, solve problems, comprehend complex ideas, use natural language fluently, classify, generalize, and adapt new situations." }, { "code": null, "e": 10971, "s": 10861, "text": "As described by Howard Gardner, an American developmental psychologist, the Intelligence comes in multifold −" }, { "code": null, "e": 11108, "s": 10971, "text": "You can say a machine or a system is artificially intelligent when it is equipped with at least one and at most all intelligences in it." }, { "code": null, "e": 11160, "s": 11108, "text": "The intelligence is intangible. It is composed of −" }, { "code": null, "e": 11170, "s": 11160, "text": "Reasoning" }, { "code": null, "e": 11179, "s": 11170, "text": "Learning" }, { "code": null, "e": 11195, "s": 11179, "text": "Problem Solving" }, { "code": null, "e": 11206, "s": 11195, "text": "Perception" }, { "code": null, "e": 11230, "s": 11206, "text": "Linguistic Intelligence" }, { "code": null, "e": 11277, "s": 11230, "text": "Let us go through all the components briefly −" }, { "code": null, "e": 11428, "s": 11277, "text": "Reasoning − It is the set of processes that enables us to provide basis for judgement, making decisions, and prediction. There are broadly two types −" }, { "code": null, "e": 11579, "s": 11428, "text": "Reasoning − It is the set of processes that enables us to provide basis for judgement, making decisions, and prediction. There are broadly two types −" }, { "code": null, "e": 13173, "s": 11579, "text": "Learning − It is the activity of gaining knowledge or skill by studying, practising, being taught, or experiencing something. Learning enhances the awareness of the subjects of the study.\nThe ability of learning is possessed by humans, some animals, and AI-enabled systems. Learning is categorized as −\n\nAuditory Learning − It is learning by listening and hearing. For example, students listening to recorded audio lectures.\nEpisodic Learning − To learn by remembering sequences of events that one has witnessed or experienced. This is linear and orderly.\nMotor Learning − It is learning by precise movement of muscles. For example, picking objects, Writing, etc.\nObservational Learning − To learn by watching and imitating others. For example, child tries to learn by mimicking her parent.\nPerceptual Learning − It is learning to recognize stimuli that one has seen before. For example, identifying and classifying objects and situations.\nRelational Learning − It involves learning to differentiate among various stimuli on the basis of relational properties, rather than absolute properties. For Example, Adding ‘little less’ salt at the time of cooking potatoes that came up salty last time, when cooked with adding say a tablespoon of salt.\nSpatial Learning − It is learning through visual stimuli such as images, colors, maps, etc. For Example, A person can create roadmap in mind before actually following the road.\nStimulus-Response Learning − It is learning to perform a particular behavior when a certain stimulus is present. For example, a dog raises its ear on hearing doorbell.\n\n" }, { "code": null, "e": 13361, "s": 13173, "text": "Learning − It is the activity of gaining knowledge or skill by studying, practising, being taught, or experiencing something. Learning enhances the awareness of the subjects of the study." }, { "code": null, "e": 13478, "s": 13361, "text": "The ability of learning is possessed by humans, some animals, and AI-enabled systems. Learning is categorized as −" }, { "code": null, "e": 13599, "s": 13478, "text": "Auditory Learning − It is learning by listening and hearing. For example, students listening to recorded audio lectures." }, { "code": null, "e": 13720, "s": 13599, "text": "Auditory Learning − It is learning by listening and hearing. For example, students listening to recorded audio lectures." }, { "code": null, "e": 13851, "s": 13720, "text": "Episodic Learning − To learn by remembering sequences of events that one has witnessed or experienced. This is linear and orderly." }, { "code": null, "e": 13982, "s": 13851, "text": "Episodic Learning − To learn by remembering sequences of events that one has witnessed or experienced. This is linear and orderly." }, { "code": null, "e": 14090, "s": 13982, "text": "Motor Learning − It is learning by precise movement of muscles. For example, picking objects, Writing, etc." }, { "code": null, "e": 14198, "s": 14090, "text": "Motor Learning − It is learning by precise movement of muscles. For example, picking objects, Writing, etc." }, { "code": null, "e": 14325, "s": 14198, "text": "Observational Learning − To learn by watching and imitating others. For example, child tries to learn by mimicking her parent." }, { "code": null, "e": 14452, "s": 14325, "text": "Observational Learning − To learn by watching and imitating others. For example, child tries to learn by mimicking her parent." }, { "code": null, "e": 14601, "s": 14452, "text": "Perceptual Learning − It is learning to recognize stimuli that one has seen before. For example, identifying and classifying objects and situations." }, { "code": null, "e": 14750, "s": 14601, "text": "Perceptual Learning − It is learning to recognize stimuli that one has seen before. For example, identifying and classifying objects and situations." }, { "code": null, "e": 15055, "s": 14750, "text": "Relational Learning − It involves learning to differentiate among various stimuli on the basis of relational properties, rather than absolute properties. For Example, Adding ‘little less’ salt at the time of cooking potatoes that came up salty last time, when cooked with adding say a tablespoon of salt." }, { "code": null, "e": 15360, "s": 15055, "text": "Relational Learning − It involves learning to differentiate among various stimuli on the basis of relational properties, rather than absolute properties. For Example, Adding ‘little less’ salt at the time of cooking potatoes that came up salty last time, when cooked with adding say a tablespoon of salt." }, { "code": null, "e": 15537, "s": 15360, "text": "Spatial Learning − It is learning through visual stimuli such as images, colors, maps, etc. For Example, A person can create roadmap in mind before actually following the road." }, { "code": null, "e": 15714, "s": 15537, "text": "Spatial Learning − It is learning through visual stimuli such as images, colors, maps, etc. For Example, A person can create roadmap in mind before actually following the road." }, { "code": null, "e": 15882, "s": 15714, "text": "Stimulus-Response Learning − It is learning to perform a particular behavior when a certain stimulus is present. For example, a dog raises its ear on hearing doorbell." }, { "code": null, "e": 16050, "s": 15882, "text": "Stimulus-Response Learning − It is learning to perform a particular behavior when a certain stimulus is present. For example, a dog raises its ear on hearing doorbell." }, { "code": null, "e": 16424, "s": 16050, "text": "Problem Solving − It is the process in which one perceives and tries to arrive at a desired solution from a present situation by taking some path, which is blocked by known or unknown hurdles.\nProblem solving also includes decision making, which is the process of selecting the best suitable alternative out of multiple alternatives to reach the desired goal are available." }, { "code": null, "e": 16617, "s": 16424, "text": "Problem Solving − It is the process in which one perceives and tries to arrive at a desired solution from a present situation by taking some path, which is blocked by known or unknown hurdles." }, { "code": null, "e": 16798, "s": 16617, "text": "Problem solving also includes decision making, which is the process of selecting the best suitable alternative out of multiple alternatives to reach the desired goal are available." }, { "code": null, "e": 17096, "s": 16798, "text": "Perception − It is the process of acquiring, interpreting, selecting, and organizing sensory information.\nPerception presumes sensing. In humans, perception is aided by sensory organs. In the domain of AI, perception mechanism puts the data acquired by the sensors together in a meaningful manner." }, { "code": null, "e": 17202, "s": 17096, "text": "Perception − It is the process of acquiring, interpreting, selecting, and organizing sensory information." }, { "code": null, "e": 17394, "s": 17202, "text": "Perception presumes sensing. In humans, perception is aided by sensory organs. In the domain of AI, perception mechanism puts the data acquired by the sensors together in a meaningful manner." }, { "code": null, "e": 17558, "s": 17394, "text": "Linguistic Intelligence − It is one’s ability to use, comprehend, speak, and write the verbal and written language. It is important in interpersonal communication." }, { "code": null, "e": 17722, "s": 17558, "text": "Linguistic Intelligence − It is one’s ability to use, comprehend, speak, and write the verbal and written language. It is important in interpersonal communication." }, { "code": null, "e": 17806, "s": 17722, "text": "Humans perceive by patterns whereas the machines perceive by set of rules and data." }, { "code": null, "e": 17890, "s": 17806, "text": "Humans perceive by patterns whereas the machines perceive by set of rules and data." }, { "code": null, "e": 18077, "s": 17890, "text": "Humans store and recall information by patterns, machines do it by searching algorithms. For example, the number 40404040 is easy to remember, store, and recall as its pattern is simple." }, { "code": null, "e": 18264, "s": 18077, "text": "Humans store and recall information by patterns, machines do it by searching algorithms. For example, the number 40404040 is easy to remember, store, and recall as its pattern is simple." }, { "code": null, "e": 18400, "s": 18264, "text": "Humans can figure out the complete object even if some part of it is missing or distorted; whereas the machines cannot do it correctly." }, { "code": null, "e": 18536, "s": 18400, "text": "Humans can figure out the complete object even if some part of it is missing or distorted; whereas the machines cannot do it correctly." }, { "code": null, "e": 18705, "s": 18536, "text": "The domain of artificial intelligence is huge in breadth and width. While proceeding, we consider the broadly common and prospering research areas in the domain of AI −" }, { "code": null, "e": 18871, "s": 18705, "text": "These both terms are common in robotics, expert systems and natural language processing. Though these terms are used interchangeably, their objectives are different." }, { "code": null, "e": 19168, "s": 18871, "text": "The user input spoken at a microphone goes to sound card of the system. The converter turns the analog signal into equivalent digital signal for the speech processing. The database is used to compare the sound patterns to recognize the words. Finally, a reverse feedback is given to the database." }, { "code": null, "e": 19358, "s": 19168, "text": "This source-language text becomes input to the Translation Engine, which converts it to the target language text. They are supported with interactive GUI, large database of vocabulary, etc." }, { "code": null, "e": 19459, "s": 19358, "text": "There is a large array of applications where AI is serving common people in their day-to-day lives −" }, { "code": null, "e": 19474, "s": 19459, "text": "Expert Systems" }, { "code": null, "e": 19528, "s": 19474, "text": "Examples − Flight-tracking systems, Clinical systems." }, { "code": null, "e": 19556, "s": 19528, "text": "Natural Language Processing" }, { "code": null, "e": 19630, "s": 19556, "text": "Examples: Google Now feature, speech recognition, Automatic voice output." }, { "code": null, "e": 19646, "s": 19630, "text": "Neural Networks" }, { "code": null, "e": 19759, "s": 19646, "text": "Examples − Pattern recognition systems such as face recognition, character recognition, handwriting recognition." }, { "code": null, "e": 19768, "s": 19759, "text": "Robotics" }, { "code": null, "e": 19892, "s": 19768, "text": "Examples − Industrial robots for moving, spraying, painting, precision checking, drilling, cleaning, coating, carving, etc." }, { "code": null, "e": 19912, "s": 19892, "text": "Fuzzy Logic Systems" }, { "code": null, "e": 19963, "s": 19912, "text": "Examples − Consumer electronics, automobiles, etc." }, { "code": null, "e": 20046, "s": 19963, "text": "The domain of AI is classified into Formal tasks, Mundane tasks, and Expert tasks." }, { "code": null, "e": 20062, "s": 20046, "text": "Computer Vision" }, { "code": null, "e": 20076, "s": 20062, "text": "Speech, Voice" }, { "code": null, "e": 20088, "s": 20076, "text": "Mathematics" }, { "code": null, "e": 20097, "s": 20088, "text": "Geometry" }, { "code": null, "e": 20103, "s": 20097, "text": "Logic" }, { "code": null, "e": 20135, "s": 20103, "text": "Integration and Differentiation" }, { "code": null, "e": 20147, "s": 20135, "text": "Engineering" }, { "code": null, "e": 20161, "s": 20147, "text": "Fault Finding" }, { "code": null, "e": 20175, "s": 20161, "text": "Manufacturing" }, { "code": null, "e": 20186, "s": 20175, "text": "Monitoring" }, { "code": null, "e": 20200, "s": 20186, "text": "Understanding" }, { "code": null, "e": 20220, "s": 20200, "text": "Language Generation" }, { "code": null, "e": 20241, "s": 20220, "text": "Language Translation" }, { "code": null, "e": 20244, "s": 20241, "text": "Go" }, { "code": null, "e": 20262, "s": 20244, "text": "Chess (Deep Blue)" }, { "code": null, "e": 20271, "s": 20262, "text": "Ckeckers" }, { "code": null, "e": 20282, "s": 20271, "text": "Locomotive" }, { "code": null, "e": 20471, "s": 20282, "text": "Humans learn mundane (ordinary) tasks since their birth. They learn by perception, speaking, using language, and locomotives. They learn Formal Tasks and Expert Tasks later, in that order." }, { "code": null, "e": 20675, "s": 20471, "text": "For humans, the mundane tasks are easiest to learn. The same was considered true before trying to implement mundane tasks in machines. Earlier, all work of AI was concentrated in the mundane task domain." }, { "code": null, "e": 21025, "s": 20675, "text": "Later, it turned out that the machine requires more knowledge, complex knowledge representation, and complicated algorithms for handling mundane tasks. This is the reason why AI work is more prospering in the Expert Tasks domain now, as the expert task domain needs expert knowledge without common sense, which can be easier to represent and handle." }, { "code": null, "e": 21162, "s": 21025, "text": "An AI system is composed of an agent and its environment. The agents act in their environment. The environment may contain other agents." }, { "code": null, "e": 21283, "s": 21162, "text": "An agent is anything that can perceive its environment through sensors and acts upon that environment through effectors." }, { "code": null, "e": 21443, "s": 21283, "text": "A human agent has sensory organs such as eyes, ears, nose, tongue and skin parallel to the sensors, and other organs such as hands, legs, mouth, for effectors." }, { "code": null, "e": 21603, "s": 21443, "text": "A human agent has sensory organs such as eyes, ears, nose, tongue and skin parallel to the sensors, and other organs such as hands, legs, mouth, for effectors." }, { "code": null, "e": 21728, "s": 21603, "text": "A robotic agent replaces cameras and infrared range finders for the sensors, and various motors and actuators for effectors." }, { "code": null, "e": 21853, "s": 21728, "text": "A robotic agent replaces cameras and infrared range finders for the sensors, and various motors and actuators for effectors." }, { "code": null, "e": 21923, "s": 21853, "text": "A software agent has encoded bit strings as its programs and actions." }, { "code": null, "e": 21993, "s": 21923, "text": "A software agent has encoded bit strings as its programs and actions." }, { "code": null, "e": 22089, "s": 21993, "text": "Performance Measure of Agent − It is the criteria, which determines how successful an agent is." }, { "code": null, "e": 22185, "s": 22089, "text": "Performance Measure of Agent − It is the criteria, which determines how successful an agent is." }, { "code": null, "e": 22280, "s": 22185, "text": "Behavior of Agent − It is the action that agent performs after any given sequence of percepts." }, { "code": null, "e": 22375, "s": 22280, "text": "Behavior of Agent − It is the action that agent performs after any given sequence of percepts." }, { "code": null, "e": 22438, "s": 22375, "text": "Percept − It is agent’s perceptual inputs at a given instance." }, { "code": null, "e": 22501, "s": 22438, "text": "Percept − It is agent’s perceptual inputs at a given instance." }, { "code": null, "e": 22584, "s": 22501, "text": "Percept Sequence − It is the history of all that an agent has perceived till date." }, { "code": null, "e": 22667, "s": 22584, "text": "Percept Sequence − It is the history of all that an agent has perceived till date." }, { "code": null, "e": 22736, "s": 22667, "text": "Agent Function − It is a map from the precept sequence to an action." }, { "code": null, "e": 22805, "s": 22736, "text": "Agent Function − It is a map from the precept sequence to an action." }, { "code": null, "e": 22905, "s": 22805, "text": "Rationality is nothing but status of being reasonable, sensible, and having good sense of judgment." }, { "code": null, "e": 23110, "s": 22905, "text": "Rationality is concerned with expected actions and results depending upon what the agent has perceived. Performing actions with the aim of obtaining useful information is an important part of rationality." }, { "code": null, "e": 23244, "s": 23110, "text": "An ideal rational agent is the one, which is capable of doing expected actions to maximize its performance measure, on the basis of −" }, { "code": null, "e": 23265, "s": 23244, "text": "Its percept sequence" }, { "code": null, "e": 23293, "s": 23265, "text": "Its built-in knowledge base" }, { "code": null, "e": 23344, "s": 23293, "text": "Rationality of an agent depends on the following −" }, { "code": null, "e": 23409, "s": 23344, "text": "The performance measures, which determine the degree of success." }, { "code": null, "e": 23474, "s": 23409, "text": "The performance measures, which determine the degree of success." }, { "code": null, "e": 23509, "s": 23474, "text": "Agent’s Percept Sequence till now." }, { "code": null, "e": 23544, "s": 23509, "text": "Agent’s Percept Sequence till now." }, { "code": null, "e": 23595, "s": 23544, "text": "The agent’s prior knowledge about the environment." }, { "code": null, "e": 23646, "s": 23595, "text": "The agent’s prior knowledge about the environment." }, { "code": null, "e": 23688, "s": 23646, "text": "The actions that the agent can carry out." }, { "code": null, "e": 23730, "s": 23688, "text": "The actions that the agent can carry out." }, { "code": null, "e": 24006, "s": 23730, "text": "A rational agent always performs right action, where the right action means the action that causes the agent to be most successful in the given percept sequence. The problem the agent solves is characterized by Performance Measure, Environment, Actuators, and Sensors (PEAS)." }, { "code": null, "e": 24043, "s": 24006, "text": "Agent’s structure can be viewed as −" }, { "code": null, "e": 24080, "s": 24043, "text": "Agent = Architecture + Agent Program" }, { "code": null, "e": 24136, "s": 24080, "text": "Architecture = the machinery that an agent executes on." }, { "code": null, "e": 24192, "s": 24136, "text": "Agent Program = an implementation of an agent function." }, { "code": null, "e": 24247, "s": 24192, "text": "They choose actions only based on the current percept." }, { "code": null, "e": 24338, "s": 24247, "text": "They are rational only if a correct decision is made only on the basis of current precept." }, { "code": null, "e": 24382, "s": 24338, "text": "Their environment is completely observable." }, { "code": null, "e": 24463, "s": 24382, "text": "Condition-Action Rule − It is a rule that maps a state (condition) to an action." }, { "code": null, "e": 24551, "s": 24463, "text": "They use a model of the world to choose their actions. They maintain an internal state." }, { "code": null, "e": 24613, "s": 24551, "text": "Model − knowledge about “how the things happen in the world”." }, { "code": null, "e": 24722, "s": 24613, "text": "Internal State − It is a representation of unobserved aspects of current state depending on percept history." }, { "code": null, "e": 24774, "s": 24722, "text": "Updating the state requires the information about −" }, { "code": null, "e": 24797, "s": 24774, "text": "How the world evolves." }, { "code": null, "e": 24839, "s": 24797, "text": "How the agent’s actions affect the world." }, { "code": null, "e": 25048, "s": 24839, "text": "They choose their actions in order to achieve goals. Goal-based approach is more flexible than reflex agent since the knowledge supporting a decision is explicitly modeled, thereby allowing for modifications." }, { "code": null, "e": 25102, "s": 25048, "text": "Goal − It is the description of desirable situations." }, { "code": null, "e": 25170, "s": 25102, "text": "They choose actions based on a preference (utility) for each state." }, { "code": null, "e": 25198, "s": 25170, "text": "Goals are inadequate when −" }, { "code": null, "e": 25266, "s": 25198, "text": "There are conflicting goals, out of which only few can be achieved." }, { "code": null, "e": 25334, "s": 25266, "text": "There are conflicting goals, out of which only few can be achieved." }, { "code": null, "e": 25458, "s": 25334, "text": "Goals have some uncertainty of being achieved and you need to weigh likelihood of success against the importance of a goal." }, { "code": null, "e": 25582, "s": 25458, "text": "Goals have some uncertainty of being achieved and you need to weigh likelihood of success against the importance of a goal." }, { "code": null, "e": 25737, "s": 25582, "text": "Some programs operate in the entirely artificial environment confined to keyboard input, database, computer file systems and character output on a screen." }, { "code": null, "e": 26143, "s": 25737, "text": "In contrast, some software agents (software robots or softbots) exist in rich, unlimited softbots domains. The simulator has a very detailed, complex environment. The software agent needs to choose from a long array of actions in real time. A softbot designed to scan the online preferences of the customer and show interesting items to the customer works in the real as well as an artificial environment." }, { "code": null, "e": 26405, "s": 26143, "text": "The most famous artificial environment is the Turing Test environment, in which one real and other artificial agents are tested on equal ground. This is a very challenging environment as it is highly difficult for a software agent to perform as well as a human." }, { "code": null, "e": 26490, "s": 26405, "text": "The success of an intelligent behavior of a system can be measured with Turing Test." }, { "code": null, "e": 26831, "s": 26490, "text": "Two persons and a machine to be evaluated participate in the test. Out of the two persons, one plays the role of the tester. Each of them sits in different rooms. The tester is unaware of who is machine and who is a human. He interrogates the questions by typing and sending them to both intelligences, to which he receives typed responses." }, { "code": null, "e": 26990, "s": 26831, "text": "This test aims at fooling the tester. If the tester fails to determine machine’s response from the human response, then the machine is said to be intelligent." }, { "code": null, "e": 27033, "s": 26990, "text": "The environment has multifold properties −" }, { "code": null, "e": 27245, "s": 27033, "text": "Discrete / Continuous − If there are a limited number of distinct, clearly defined, states of the environment, the environment is discrete (For example, chess); otherwise it is continuous (For example, driving)." }, { "code": null, "e": 27457, "s": 27245, "text": "Discrete / Continuous − If there are a limited number of distinct, clearly defined, states of the environment, the environment is discrete (For example, chess); otherwise it is continuous (For example, driving)." }, { "code": null, "e": 27660, "s": 27457, "text": "Observable / Partially Observable − If it is possible to determine the complete state of the environment at each time point from the percepts it is observable; otherwise it is only partially observable." }, { "code": null, "e": 27863, "s": 27660, "text": "Observable / Partially Observable − If it is possible to determine the complete state of the environment at each time point from the percepts it is observable; otherwise it is only partially observable." }, { "code": null, "e": 27987, "s": 27863, "text": "Static / Dynamic − If the environment does not change while an agent is acting, then it is static; otherwise it is dynamic." }, { "code": null, "e": 28111, "s": 27987, "text": "Static / Dynamic − If the environment does not change while an agent is acting, then it is static; otherwise it is dynamic." }, { "code": null, "e": 28250, "s": 28111, "text": "Single agent / Multiple agents − The environment may contain other agents which may be of the same or different kind as that of the agent." }, { "code": null, "e": 28389, "s": 28250, "text": "Single agent / Multiple agents − The environment may contain other agents which may be of the same or different kind as that of the agent." }, { "code": null, "e": 28558, "s": 28389, "text": "Accessible / Inaccessible − If the agent’s sensory apparatus can have access to the complete state of the environment, then the environment is accessible to that agent." }, { "code": null, "e": 28727, "s": 28558, "text": "Accessible / Inaccessible − If the agent’s sensory apparatus can have access to the complete state of the environment, then the environment is accessible to that agent." }, { "code": null, "e": 28950, "s": 28727, "text": "Deterministic / Non-deterministic − If the next state of the environment is completely determined by the current state and the actions of the agent, then the environment is deterministic; otherwise it is non-deterministic." }, { "code": null, "e": 29173, "s": 28950, "text": "Deterministic / Non-deterministic − If the next state of the environment is completely determined by the current state and the actions of the agent, then the environment is deterministic; otherwise it is non-deterministic." }, { "code": null, "e": 29514, "s": 29173, "text": "Episodic / Non-episodic − In an episodic environment, each episode consists of the agent perceiving and then acting. The quality of its action depends just on the episode itself. Subsequent episodes do not depend on the actions in the previous episodes. Episodic environments are much simpler because the agent does not need to think ahead." }, { "code": null, "e": 29855, "s": 29514, "text": "Episodic / Non-episodic − In an episodic environment, each episode consists of the agent perceiving and then acting. The quality of its action depends just on the episode itself. Subsequent episodes do not depend on the actions in the previous episodes. Episodic environments are much simpler because the agent does not need to think ahead." }, { "code": null, "e": 30079, "s": 29855, "text": "Searching is the universal technique of problem solving in AI. There are some single-player games such as tile games, Sudoku, crossword, etc. The search algorithms help you to search for a particular position in such games." }, { "code": null, "e": 30420, "s": 30079, "text": "The games such as 3X3 eight-tile, 4X4 fifteen-tile, and 5X5 twenty four tile puzzles are single-agent-path-finding challenges. They consist of a matrix of tiles with a blank tile. The player is required to arrange the tiles by sliding a tile either vertically or horizontally into a blank space with the aim of accomplishing some objective." }, { "code": null, "e": 30544, "s": 30420, "text": "The other examples of single agent pathfinding problems are Travelling Salesman Problem, Rubik’s Cube, and Theorem Proving." }, { "code": null, "e": 30677, "s": 30544, "text": "Problem Space − It is the environment in which the search takes place. (A set of states and set of operators to change those states)" }, { "code": null, "e": 30810, "s": 30677, "text": "Problem Space − It is the environment in which the search takes place. (A set of states and set of operators to change those states)" }, { "code": null, "e": 30863, "s": 30810, "text": "Problem Instance − It is Initial state + Goal state." }, { "code": null, "e": 30916, "s": 30863, "text": "Problem Instance − It is Initial state + Goal state." }, { "code": null, "e": 31027, "s": 30916, "text": "Problem Space Graph − It represents problem state. States are shown by nodes and operators are shown by edges." }, { "code": null, "e": 31138, "s": 31027, "text": "Problem Space Graph − It represents problem state. States are shown by nodes and operators are shown by edges." }, { "code": null, "e": 31253, "s": 31138, "text": "Depth of a problem − Length of a shortest path or shortest sequence of operators from Initial State to goal state." }, { "code": null, "e": 31368, "s": 31253, "text": "Depth of a problem − Length of a shortest path or shortest sequence of operators from Initial State to goal state." }, { "code": null, "e": 31442, "s": 31368, "text": "Space Complexity − The maximum number of nodes that are stored in memory." }, { "code": null, "e": 31516, "s": 31442, "text": "Space Complexity − The maximum number of nodes that are stored in memory." }, { "code": null, "e": 31580, "s": 31516, "text": "Time Complexity − The maximum number of nodes that are created." }, { "code": null, "e": 31644, "s": 31580, "text": "Time Complexity − The maximum number of nodes that are created." }, { "code": null, "e": 31723, "s": 31644, "text": "Admissibility − A property of an algorithm to always find an optimal solution." }, { "code": null, "e": 31802, "s": 31723, "text": "Admissibility − A property of an algorithm to always find an optimal solution." }, { "code": null, "e": 31883, "s": 31802, "text": "Branching Factor − The average number of child nodes in the problem space graph." }, { "code": null, "e": 31964, "s": 31883, "text": "Branching Factor − The average number of child nodes in the problem space graph." }, { "code": null, "e": 32034, "s": 31964, "text": "Depth − Length of the shortest path from initial state to goal state." }, { "code": null, "e": 32104, "s": 32034, "text": "Depth − Length of the shortest path from initial state to goal state." }, { "code": null, "e": 32230, "s": 32104, "text": "They are most simple, as they do not need any domain-specific knowledge. They work fine with small number of possible states." }, { "code": null, "e": 32245, "s": 32230, "text": "Requirements −" }, { "code": null, "e": 32263, "s": 32245, "text": "State description" }, { "code": null, "e": 32288, "s": 32263, "text": "A set of valid operators" }, { "code": null, "e": 32302, "s": 32288, "text": "Initial state" }, { "code": null, "e": 32325, "s": 32302, "text": "Goal state description" }, { "code": null, "e": 32604, "s": 32325, "text": "It starts from the root node, explores the neighboring nodes first and moves towards the next level neighbors. It generates one tree at a time until the solution is found. It can be implemented using FIFO queue data structure. This method provides shortest path to the solution." }, { "code": null, "e": 32730, "s": 32604, "text": "If branching factor (average number of child nodes for a given node) = b and depth = d, then number of nodes at level d = bd." }, { "code": null, "e": 32801, "s": 32730, "text": "The total no of nodes created in worst case is b + b2 + b3 + ... + bd." }, { "code": null, "e": 32958, "s": 32801, "text": "Disadvantage − Since each level of nodes is saved for creating next one, it consumes a lot of memory space. Space requirement to store nodes is exponential." }, { "code": null, "e": 33035, "s": 32958, "text": "Its complexity depends on the number of nodes. It can check duplicate nodes." }, { "code": null, "e": 33185, "s": 33035, "text": "It is implemented in recursion with LIFO stack data structure. It creates the same set of nodes as Breadth-First method, only in the different order." }, { "code": null, "e": 33383, "s": 33185, "text": "As the nodes on the single path are stored in each iteration from root to leaf node, the space requirement to store nodes is linear. With branching factor b and depth as m, the storage space is bm." }, { "code": null, "e": 33684, "s": 33383, "text": "Disadvantage − This algorithm may not terminate and go on infinitely on one path. The solution to this issue is to choose a cut-off depth. If the ideal cut-off is d, and if chosen cut-off is lesser than d, then this algorithm may fail. If chosen cut-off is more than d, then execution time increases." }, { "code": null, "e": 33764, "s": 33684, "text": "Its complexity depends on the number of paths. It cannot check duplicate nodes." }, { "code": null, "e": 33875, "s": 33764, "text": "It searches forward from initial state and backward from goal state till both meet to identify a common state." }, { "code": null, "e": 34017, "s": 33875, "text": "The path from initial state is concatenated with the inverse path from the goal state. Each search is done only up to half of the total path." }, { "code": null, "e": 34192, "s": 34017, "text": "Sorting is done in increasing cost of the path to a node. It always expands the least cost node. It is identical to Breadth First search if each transition has the same cost." }, { "code": null, "e": 34243, "s": 34192, "text": "It explores paths in the increasing order of cost." }, { "code": null, "e": 34354, "s": 34243, "text": "Disadvantage − There can be multiple long paths with the cost ≤ C*. Uniform Cost search must explore them all." }, { "code": null, "e": 34515, "s": 34354, "text": "It performs depth-first search to level 1, starts over, executes a complete depth-first search to level 2, and continues in such way till the solution is found." }, { "code": null, "e": 34735, "s": 34515, "text": "It never creates a node until all lower nodes are generated. It only saves a stack of nodes. The algorithm ends when it finds a solution at depth d. The number of nodes created at depth d is bd and at depth d-1 is bd-1." }, { "code": null, "e": 34804, "s": 34735, "text": "Let us see the performance of algorithms based on various criteria −" }, { "code": null, "e": 34960, "s": 34804, "text": "To solve large problems with large number of possible states, problem-specific knowledge needs to be added to increase the efficiency of search algorithms." }, { "code": null, "e": 35194, "s": 34960, "text": "They calculate the cost of optimal path between two states. A heuristic function for sliding-tiles games is computed by counting number of moves that each tile makes from its goal state and adding these number of moves for all tiles." }, { "code": null, "e": 35373, "s": 35194, "text": "It expands nodes in the order of their heuristic values. It creates two lists, a closed list for the already expanded nodes and an open list for the created but unexpanded nodes." }, { "code": null, "e": 35700, "s": 35373, "text": "In each iteration, a node with a minimum heuristic value is expanded, all its child nodes are created and placed in the closed list. Then, the heuristic function is applied to the child nodes and they are placed in the open list according to their heuristic value. The shorter paths are saved and the longer ones are disposed." }, { "code": null, "e": 35838, "s": 35700, "text": "It is best-known form of Best First search. It avoids expanding paths that are already expensive, but expands most promising paths first." }, { "code": null, "e": 35864, "s": 35838, "text": "f(n) = g(n) + h(n), where" }, { "code": null, "e": 35905, "s": 35864, "text": "g(n) the cost (so far) to reach the node" }, { "code": null, "e": 35958, "s": 35905, "text": "h(n) estimated cost to get from the node to the goal" }, { "code": null, "e": 36070, "s": 35958, "text": "f(n) estimated total cost of path through n to goal. It is implemented using priority queue by increasing f(n)." }, { "code": null, "e": 36210, "s": 36070, "text": "It expands the node that is estimated to be closest to goal. It expands nodes based on f(n) = h(n). It is implemented using priority queue." }, { "code": null, "e": 36271, "s": 36210, "text": "Disadvantage − It can get stuck in loops. It is not optimal." }, { "code": null, "e": 36439, "s": 36271, "text": "They start from a prospective solution and then move to a neighboring solution. They can return a valid solution even if it is interrupted at any time before they end." }, { "code": null, "e": 36777, "s": 36439, "text": "It is an iterative algorithm that starts with an arbitrary solution to a problem and attempts to find a better solution by changing a single element of the solution incrementally. If the change produces a better solution, an incremental change is taken as a new solution. This process is repeated until there are no further improvements." }, { "code": null, "e": 36852, "s": 36777, "text": "function Hill-Climbing (problem), returns a state that is a local maximum." }, { "code": null, "e": 37165, "s": 36852, "text": "inputs: problem, a problem\nlocal variables: current, a node\n neighbor, a node\ncurrent <-Make_Node(Initial-State[problem])\nloop\n do neighbor <- a highest_valued successor of current\n if Value[neighbor] ≤ Value[current] then\n return State[current]\n current <- neighbor\t\t\t\t \n\t\nend\n" }, { "code": null, "e": 37229, "s": 37165, "text": "Disadvantage − This algorithm is neither complete, nor optimal." }, { "code": null, "e": 37530, "s": 37229, "text": "In this algorithm, it holds k number of states at any given time. At the start, these states are generated randomly. The successors of these k states are computed with the help of objective function. If any of these successors is the maximum value of the objective function, then the algorithm stops." }, { "code": null, "e": 37789, "s": 37530, "text": "Otherwise the (initial k states and k number of successors of the states = 2k) states are placed in a pool. The pool is then sorted numerically. The highest k states are selected as new initial states. This process continues until a maximum value is reached." }, { "code": null, "e": 37849, "s": 37789, "text": "function BeamSearch( problem, k), returns a solution state." }, { "code": null, "e": 38036, "s": 37849, "text": "start with k randomly generated states\nloop\n generate all successors of all k states\n if any of the states = solution, then return the state\n else select the k best successors\nend\n" }, { "code": null, "e": 38334, "s": 38036, "text": "Annealing is the process of heating and cooling a metal to change its internal structure for modifying its physical properties. When the metal cools, its new structure is seized, and the metal retains its newly obtained properties. In simulated annealing process, the temperature is kept variable." }, { "code": null, "e": 38536, "s": 38334, "text": "We initially set the temperature high and then allow it to ‘cool' slowly as the algorithm proceeds. When the temperature is high, the algorithm is allowed to accept worse solutions with high frequency." }, { "code": null, "e": 38542, "s": 38536, "text": "Start" }, { "code": null, "e": 38593, "s": 38542, "text": "Initialize k = 0; L = integer number of variables;" }, { "code": null, "e": 38642, "s": 38593, "text": "From i → j, search the performance difference Δ." }, { "code": null, "e": 38712, "s": 38642, "text": "If Δ <= 0 then accept else if exp(-Δ/T(k)) > random(0,1) then accept;" }, { "code": null, "e": 38749, "s": 38712, "text": "Repeat steps 1 and 2 for L(k) steps." }, { "code": null, "e": 38760, "s": 38749, "text": "k = k + 1;" }, { "code": null, "e": 38811, "s": 38760, "text": "Repeat steps 1 through 4 till the criteria is met." }, { "code": null, "e": 38815, "s": 38811, "text": "End" }, { "code": null, "e": 38976, "s": 38815, "text": "In this algorithm, the objective is to find a low-cost tour that starts from a city, visits all cities en-route exactly once and ends at the same starting city." }, { "code": null, "e": 39208, "s": 38976, "text": "Start\n Find out all (n -1)! Possible solutions, where n is the total number of cities.\n Determine the minimum cost by finding out the cost of each of these (n -1)! solutions.\n Finally, keep the one with the minimum cost.\nend\n" }, { "code": null, "e": 39351, "s": 39208, "text": "Fuzzy Logic Systems (FLS) produce acceptable but definite output in response to incomplete, ambiguous, distorted, or inaccurate (fuzzy) input." }, { "code": null, "e": 39570, "s": 39351, "text": "Fuzzy Logic (FL) is a method of reasoning that resembles human reasoning. The approach of FL imitates the way of decision making in humans that involves all intermediate possibilities between digital values YES and NO." }, { "code": null, "e": 39741, "s": 39570, "text": "The conventional logic block that a computer can understand takes precise input and produces a definite output as TRUE or FALSE, which is equivalent to human’s YES or NO." }, { "code": null, "e": 39905, "s": 39741, "text": "The inventor of fuzzy logic, Lotfi Zadeh, observed that unlike computers, the human decision making includes a range of possibilities between YES and NO, such as −" }, { "code": null, "e": 39999, "s": 39905, "text": "The fuzzy logic works on the levels of possibilities of input to achieve the definite output." }, { "code": null, "e": 40161, "s": 39999, "text": "It can be implemented in systems with various sizes and capabilities ranging from small micro-controllers to large, networked, workstation-based control systems." }, { "code": null, "e": 40323, "s": 40161, "text": "It can be implemented in systems with various sizes and capabilities ranging from small micro-controllers to large, networked, workstation-based control systems." }, { "code": null, "e": 40394, "s": 40323, "text": "It can be implemented in hardware, software, or a combination of both." }, { "code": null, "e": 40465, "s": 40394, "text": "It can be implemented in hardware, software, or a combination of both." }, { "code": null, "e": 40526, "s": 40465, "text": "Fuzzy logic is useful for commercial and practical purposes." }, { "code": null, "e": 40573, "s": 40526, "text": "It can control machines and consumer products." }, { "code": null, "e": 40635, "s": 40573, "text": "It may not give accurate reasoning, but acceptable reasoning." }, { "code": null, "e": 40698, "s": 40635, "text": "Fuzzy logic helps to deal with the uncertainty in engineering." }, { "code": null, "e": 40732, "s": 40698, "text": "It has four main parts as shown −" }, { "code": null, "e": 40883, "s": 40732, "text": "Fuzzification Module − It transforms the system inputs, which are crisp numbers, into fuzzy sets. It splits the input signal into five steps such as −" }, { "code": null, "e": 41034, "s": 40883, "text": "Fuzzification Module − It transforms the system inputs, which are crisp numbers, into fuzzy sets. It splits the input signal into five steps such as −" }, { "code": null, "e": 41096, "s": 41034, "text": "Knowledge Base − It stores IF-THEN rules provided by experts." }, { "code": null, "e": 41158, "s": 41096, "text": "Knowledge Base − It stores IF-THEN rules provided by experts." }, { "code": null, "e": 41277, "s": 41158, "text": "Inference Engine − It simulates the human reasoning process by making fuzzy inference on the inputs and IF-THEN rules." }, { "code": null, "e": 41396, "s": 41277, "text": "Inference Engine − It simulates the human reasoning process by making fuzzy inference on the inputs and IF-THEN rules." }, { "code": null, "e": 41502, "s": 41396, "text": "Defuzzification Module − It transforms the fuzzy set obtained by the inference engine into a crisp value." }, { "code": null, "e": 41608, "s": 41502, "text": "Defuzzification Module − It transforms the fuzzy set obtained by the inference engine into a crisp value." }, { "code": null, "e": 41666, "s": 41608, "text": "The membership functions work on fuzzy sets of variables." }, { "code": null, "e": 41863, "s": 41666, "text": "Membership functions allow you to quantify linguistic term and represent a fuzzy set graphically. A membership function for a fuzzy set A on the universe of discourse X is defined as μA:X → [0,1]." }, { "code": null, "e": 42059, "s": 41863, "text": "Here, each element of X is mapped to a value between 0 and 1. It is called membership value or degree of membership. It quantifies the degree of membership of the element in X to the fuzzy set A." }, { "code": null, "e": 42104, "s": 42059, "text": "x axis represents the universe of discourse." }, { "code": null, "e": 42172, "s": 42104, "text": "y axis represents the degrees of membership in the [0, 1] interval." }, { "code": null, "e": 42364, "s": 42172, "text": "There can be multiple membership functions applicable to fuzzify a numerical value. Simple membership functions are used as use of complex functions does not add more precision in the output." }, { "code": null, "e": 42436, "s": 42364, "text": "All membership functions for LP, MP, S, MN, and LN are shown as below −" }, { "code": null, "e": 42587, "s": 42436, "text": "The triangular membership function shapes are most common among various other membership function shapes such as trapezoidal, singleton, and Gaussian." }, { "code": null, "e": 42705, "s": 42587, "text": "Here, the input to 5-level fuzzifier varies from -10 volts to +10 volts. Hence the corresponding output also changes." }, { "code": null, "e": 42904, "s": 42705, "text": "Let us consider an air conditioning system with 5-level fuzzy logic system. This system adjusts the temperature of air conditioner by comparing the room temperature and the target temperature value." }, { "code": null, "e": 42950, "s": 42904, "text": "Define linguistic Variables and terms (start)" }, { "code": null, "e": 42999, "s": 42950, "text": "Construct membership functions for them. (start)" }, { "code": null, "e": 43041, "s": 42999, "text": "Construct knowledge base of rules (start)" }, { "code": null, "e": 43125, "s": 43041, "text": "Convert crisp data into fuzzy data sets using membership functions. (fuzzification)" }, { "code": null, "e": 43177, "s": 43125, "text": "Evaluate rules in the rule base. (Inference Engine)" }, { "code": null, "e": 43228, "s": 43177, "text": "Combine results from each rule. (Inference Engine)" }, { "code": null, "e": 43289, "s": 43228, "text": "Convert output data into non-fuzzy values. (defuzzification)" }, { "code": null, "e": 43336, "s": 43289, "text": "Step 1 − Define linguistic variables and terms" }, { "code": null, "e": 43497, "s": 43336, "text": "Linguistic variables are input and output variables in the form of simple words or sentences. For room temperature, cold, warm, hot, etc., are linguistic terms." }, { "code": null, "e": 43555, "s": 43497, "text": "Temperature (t) = {very-cold, cold, warm, very-warm, hot}" }, { "code": null, "e": 43662, "s": 43555, "text": "Every member of this set is a linguistic term and it can cover some portion of overall temperature values." }, { "code": null, "e": 43711, "s": 43662, "text": "Step 2 − Construct membership functions for them" }, { "code": null, "e": 43775, "s": 43711, "text": "The membership functions of temperature variable are as shown −" }, { "code": null, "e": 43814, "s": 43775, "text": "Step3 − Construct knowledge base rules" }, { "code": null, "e": 43946, "s": 43814, "text": "Create a matrix of room temperature values versus target temperature values that an air conditioning system is expected to provide." }, { "code": null, "e": 44031, "s": 43946, "text": "Build a set of rules into the knowledge base in the form of IF-THEN-ELSE structures." }, { "code": null, "e": 44059, "s": 44031, "text": "Step 4 − Obtain fuzzy value" }, { "code": null, "e": 44262, "s": 44059, "text": "Fuzzy set operations perform evaluation of rules. The operations used for OR and AND are Max and Min respectively. Combine all results of evaluation to form a final result. This result is a fuzzy value." }, { "code": null, "e": 44295, "s": 44262, "text": "Step 5 − Perform defuzzification" }, { "code": null, "e": 44383, "s": 44295, "text": "Defuzzification is then performed according to membership function for output variable." }, { "code": null, "e": 44439, "s": 44383, "text": "The key application areas of fuzzy logic are as given −" }, { "code": null, "e": 44458, "s": 44439, "text": "Automotive Systems" }, { "code": null, "e": 44478, "s": 44458, "text": "Automatic Gearboxes" }, { "code": null, "e": 44498, "s": 44478, "text": "Four-Wheel Steering" }, { "code": null, "e": 44526, "s": 44498, "text": "Vehicle environment control" }, { "code": null, "e": 44552, "s": 44526, "text": "Consumer Electronic Goods" }, { "code": null, "e": 44566, "s": 44552, "text": "Hi-Fi Systems" }, { "code": null, "e": 44579, "s": 44566, "text": "Photocopiers" }, { "code": null, "e": 44603, "s": 44579, "text": "Still and Video Cameras" }, { "code": null, "e": 44614, "s": 44603, "text": "Television" }, { "code": null, "e": 44629, "s": 44614, "text": "Domestic Goods" }, { "code": null, "e": 44645, "s": 44629, "text": "Microwave Ovens" }, { "code": null, "e": 44659, "s": 44645, "text": "Refrigerators" }, { "code": null, "e": 44668, "s": 44659, "text": "Toasters" }, { "code": null, "e": 44684, "s": 44668, "text": "Vacuum Cleaners" }, { "code": null, "e": 44701, "s": 44684, "text": "Washing Machines" }, { "code": null, "e": 44721, "s": 44701, "text": "Environment Control" }, { "code": null, "e": 44753, "s": 44721, "text": "Air Conditioners/Dryers/Heaters" }, { "code": null, "e": 44765, "s": 44753, "text": "Humidifiers" }, { "code": null, "e": 44827, "s": 44765, "text": "Mathematical concepts within fuzzy reasoning are very simple." }, { "code": null, "e": 44889, "s": 44827, "text": "Mathematical concepts within fuzzy reasoning are very simple." }, { "code": null, "e": 44978, "s": 44889, "text": "You can modify a FLS by just adding or deleting rules due to flexibility of fuzzy logic." }, { "code": null, "e": 45067, "s": 44978, "text": "You can modify a FLS by just adding or deleting rules due to flexibility of fuzzy logic." }, { "code": null, "e": 45143, "s": 45067, "text": "Fuzzy logic Systems can take imprecise, distorted, noisy input information." }, { "code": null, "e": 45219, "s": 45143, "text": "Fuzzy logic Systems can take imprecise, distorted, noisy input information." }, { "code": null, "e": 45262, "s": 45219, "text": "FLSs are easy to construct and understand." }, { "code": null, "e": 45305, "s": 45262, "text": "FLSs are easy to construct and understand." }, { "code": null, "e": 45447, "s": 45305, "text": "Fuzzy logic is a solution to complex problems in all fields of life, including medicine, as it resembles human reasoning and decision making." }, { "code": null, "e": 45589, "s": 45447, "text": "Fuzzy logic is a solution to complex problems in all fields of life, including medicine, as it resembles human reasoning and decision making." }, { "code": null, "e": 45648, "s": 45589, "text": "There is no systematic approach to fuzzy system designing." }, { "code": null, "e": 45690, "s": 45648, "text": "They are understandable only when simple." }, { "code": null, "e": 45758, "s": 45690, "text": "They are suitable for the problems which do not need high accuracy." }, { "code": null, "e": 45899, "s": 45758, "text": "Natural Language Processing (NLP) refers to AI method of communicating with an intelligent systems using a natural language such as English." }, { "code": null, "e": 46108, "s": 45899, "text": "Processing of Natural Language is required when you want an intelligent system like robot to perform as per your instructions, when you want to hear decision from a dialogue based clinical expert system, etc." }, { "code": null, "e": 46261, "s": 46108, "text": "The field of NLP involves making computers to perform useful tasks with the natural languages humans use. The input and output of an NLP system can be −" }, { "code": null, "e": 46268, "s": 46261, "text": "Speech" }, { "code": null, "e": 46281, "s": 46268, "text": "Written Text" }, { "code": null, "e": 46324, "s": 46281, "text": "There are two components of NLP as given −" }, { "code": null, "e": 46369, "s": 46324, "text": "Understanding involves the following tasks −" }, { "code": null, "e": 46442, "s": 46369, "text": "Mapping the given input in natural language into useful representations." }, { "code": null, "e": 46487, "s": 46442, "text": "Analyzing different aspects of the language." }, { "code": null, "e": 46618, "s": 46487, "text": "It is the process of producing meaningful phrases and sentences in the form of natural language from some internal representation." }, { "code": null, "e": 46632, "s": 46618, "text": "It involves −" }, { "code": null, "e": 46713, "s": 46632, "text": "Text planning − It includes retrieving the relevant content from knowledge base." }, { "code": null, "e": 46794, "s": 46713, "text": "Text planning − It includes retrieving the relevant content from knowledge base." }, { "code": null, "e": 46909, "s": 46794, "text": "Sentence planning − It includes choosing required words, forming meaningful phrases, setting tone of the sentence." }, { "code": null, "e": 47024, "s": 46909, "text": "Sentence planning − It includes choosing required words, forming meaningful phrases, setting tone of the sentence." }, { "code": null, "e": 47096, "s": 47024, "text": "Text Realization − It is mapping sentence plan into sentence structure." }, { "code": null, "e": 47168, "s": 47096, "text": "Text Realization − It is mapping sentence plan into sentence structure." }, { "code": null, "e": 47196, "s": 47168, "text": "The NLU is harder than NLG." }, { "code": null, "e": 47241, "s": 47196, "text": "NL has an extremely rich form and structure." }, { "code": null, "e": 47308, "s": 47241, "text": "It is very ambiguous. There can be different levels of ambiguity −" }, { "code": null, "e": 47378, "s": 47308, "text": "Lexical ambiguity − It is at very primitive level such as word-level." }, { "code": null, "e": 47448, "s": 47378, "text": "Lexical ambiguity − It is at very primitive level such as word-level." }, { "code": null, "e": 47504, "s": 47448, "text": "For example, treating the word “board” as noun or verb?" }, { "code": null, "e": 47560, "s": 47504, "text": "For example, treating the word “board” as noun or verb?" }, { "code": null, "e": 47629, "s": 47560, "text": "Syntax Level ambiguity − A sentence can be parsed in different ways." }, { "code": null, "e": 47698, "s": 47629, "text": "Syntax Level ambiguity − A sentence can be parsed in different ways." }, { "code": null, "e": 47824, "s": 47698, "text": "For example, “He lifted the beetle with red cap.” − Did he use cap to lift the beetle or he lifted a beetle that had red cap?" }, { "code": null, "e": 47950, "s": 47824, "text": "For example, “He lifted the beetle with red cap.” − Did he use cap to lift the beetle or he lifted a beetle that had red cap?" }, { "code": null, "e": 48094, "s": 47950, "text": "Referential ambiguity − Referring to something using pronouns. For example, Rima went to Gauri. She said, “I am tired.” − Exactly who is tired?" }, { "code": null, "e": 48238, "s": 48094, "text": "Referential ambiguity − Referring to something using pronouns. For example, Rima went to Gauri. She said, “I am tired.” − Exactly who is tired?" }, { "code": null, "e": 48277, "s": 48238, "text": "One input can mean different meanings." }, { "code": null, "e": 48316, "s": 48277, "text": "One input can mean different meanings." }, { "code": null, "e": 48353, "s": 48316, "text": "Many inputs can mean the same thing." }, { "code": null, "e": 48390, "s": 48353, "text": "Many inputs can mean the same thing." }, { "code": null, "e": 48450, "s": 48390, "text": "Phonology − It is study of organizing sound systematically." }, { "code": null, "e": 48510, "s": 48450, "text": "Phonology − It is study of organizing sound systematically." }, { "code": null, "e": 48595, "s": 48510, "text": "Morphology − It is a study of construction of words from primitive meaningful units." }, { "code": null, "e": 48680, "s": 48595, "text": "Morphology − It is a study of construction of words from primitive meaningful units." }, { "code": null, "e": 48738, "s": 48680, "text": "Morpheme − It is primitive unit of meaning in a language." }, { "code": null, "e": 48796, "s": 48738, "text": "Morpheme − It is primitive unit of meaning in a language." }, { "code": null, "e": 48944, "s": 48796, "text": "Syntax − It refers to arranging words to make a sentence. It also involves determining the structural role of words in the sentence and in phrases." }, { "code": null, "e": 49092, "s": 48944, "text": "Syntax − It refers to arranging words to make a sentence. It also involves determining the structural role of words in the sentence and in phrases." }, { "code": null, "e": 49210, "s": 49092, "text": "Semantics − It is concerned with the meaning of words and how to combine words into meaningful phrases and sentences." }, { "code": null, "e": 49328, "s": 49210, "text": "Semantics − It is concerned with the meaning of words and how to combine words into meaningful phrases and sentences." }, { "code": null, "e": 49469, "s": 49328, "text": "Pragmatics − It deals with using and understanding sentences in different situations and how the interpretation of the sentence is affected." }, { "code": null, "e": 49610, "s": 49469, "text": "Pragmatics − It deals with using and understanding sentences in different situations and how the interpretation of the sentence is affected." }, { "code": null, "e": 49727, "s": 49610, "text": "Discourse − It deals with how the immediately preceding sentence can affect the interpretation of the next sentence." }, { "code": null, "e": 49844, "s": 49727, "text": "Discourse − It deals with how the immediately preceding sentence can affect the interpretation of the next sentence." }, { "code": null, "e": 49913, "s": 49844, "text": "World Knowledge − It includes the general knowledge about the world." }, { "code": null, "e": 49982, "s": 49913, "text": "World Knowledge − It includes the general knowledge about the world." }, { "code": null, "e": 50013, "s": 49982, "text": "There are general five steps −" }, { "code": null, "e": 50264, "s": 50013, "text": "Lexical Analysis − It involves identifying and analyzing the structure of words. Lexicon of a language means the collection of words and phrases in a language. Lexical analysis is dividing the whole chunk of txt into paragraphs, sentences, and words." }, { "code": null, "e": 50515, "s": 50264, "text": "Lexical Analysis − It involves identifying and analyzing the structure of words. Lexicon of a language means the collection of words and phrases in a language. Lexical analysis is dividing the whole chunk of txt into paragraphs, sentences, and words." }, { "code": null, "e": 50770, "s": 50515, "text": "Syntactic Analysis (Parsing) − It involves analysis of words in the sentence for grammar and arranging words in a manner that shows the relationship among the words. The sentence such as “The school goes to boy” is rejected by English syntactic analyzer." }, { "code": null, "e": 51025, "s": 50770, "text": "Syntactic Analysis (Parsing) − It involves analysis of words in the sentence for grammar and arranging words in a manner that shows the relationship among the words. The sentence such as “The school goes to boy” is rejected by English syntactic analyzer." }, { "code": null, "e": 51295, "s": 51025, "text": "Semantic Analysis − It draws the exact meaning or the dictionary meaning from the text. The text is checked for meaningfulness. It is done by mapping syntactic structures and objects in the task domain. The semantic analyzer disregards sentence such as “hot ice-cream”." }, { "code": null, "e": 51565, "s": 51295, "text": "Semantic Analysis − It draws the exact meaning or the dictionary meaning from the text. The text is checked for meaningfulness. It is done by mapping syntactic structures and objects in the task domain. The semantic analyzer disregards sentence such as “hot ice-cream”." }, { "code": null, "e": 51756, "s": 51565, "text": "Discourse Integration − The meaning of any sentence depends upon the meaning of the sentence just before it. In addition, it also brings about the meaning of immediately succeeding sentence." }, { "code": null, "e": 51947, "s": 51756, "text": "Discourse Integration − The meaning of any sentence depends upon the meaning of the sentence just before it. In addition, it also brings about the meaning of immediately succeeding sentence." }, { "code": null, "e": 52123, "s": 51947, "text": "Pragmatic Analysis − During this, what was said is re-interpreted on what it actually meant. It involves deriving those aspects of language which require real world knowledge." }, { "code": null, "e": 52299, "s": 52123, "text": "Pragmatic Analysis − During this, what was said is re-interpreted on what it actually meant. It involves deriving those aspects of language which require real world knowledge." }, { "code": null, "e": 52435, "s": 52299, "text": "There are a number of algorithms researchers have developed for syntactic analysis, but we consider only the following simple methods −" }, { "code": null, "e": 52456, "s": 52435, "text": "Context-Free Grammar" }, { "code": null, "e": 52472, "s": 52456, "text": "Top-Down Parser" }, { "code": null, "e": 52500, "s": 52472, "text": "Let us see them in detail −" }, { "code": null, "e": 52647, "s": 52500, "text": "It is the grammar that consists rules with a single symbol on the left-hand side of the rewrite rules. Let us create grammar to parse a sentence −" }, { "code": null, "e": 52675, "s": 52647, "text": "“The bird pecks the grains”" }, { "code": null, "e": 52705, "s": 52675, "text": "Articles (DET) − a | an | the" }, { "code": null, "e": 52743, "s": 52705, "text": "Nouns − bird | birds | grain | grains" }, { "code": null, "e": 52806, "s": 52743, "text": "Noun Phrase (NP) − Article + Noun | Article + Adjective + Noun" }, { "code": null, "e": 52826, "s": 52806, "text": "= DET N | DET ADJ N" }, { "code": null, "e": 52859, "s": 52826, "text": "Verbs − pecks | pecking | pecked" }, { "code": null, "e": 52890, "s": 52859, "text": "Verb Phrase (VP) − NP V | V NP" }, { "code": null, "e": 52938, "s": 52890, "text": "Adjectives (ADJ) − beautiful | small | chirping" }, { "code": null, "e": 53219, "s": 52938, "text": "The parse tree breaks down the sentence into structured parts so that the computer can easily understand and process it. In order for the parsing algorithm to construct this parse tree, a set of rewrite rules, which describe what tree structures are legal, need to be constructed." }, { "code": null, "e": 53531, "s": 53219, "text": "These rules say that a certain symbol may be expanded in the tree by a sequence of other symbols. According to first order logic rule, if there are two strings Noun Phrase (NP) and Verb Phrase (VP), then the string combined by NP followed by VP is a sentence. The rewrite rules for the sentence are as follows −" }, { "code": null, "e": 53541, "s": 53531, "text": "S → NP VP" }, { "code": null, "e": 53564, "s": 53541, "text": "NP → DET N | DET ADJ N" }, { "code": null, "e": 53574, "s": 53564, "text": "VP → V NP" }, { "code": null, "e": 53584, "s": 53574, "text": "Lexocon −" }, { "code": null, "e": 53598, "s": 53584, "text": "DET → a | the" }, { "code": null, "e": 53625, "s": 53598, "text": "ADJ → beautiful | perching" }, { "code": null, "e": 53659, "s": 53625, "text": "N → bird | birds | grain | grains" }, { "code": null, "e": 53686, "s": 53659, "text": "V → peck | pecks | pecking" }, { "code": null, "e": 53727, "s": 53686, "text": "The parse tree can be created as shown −" }, { "code": null, "e": 53951, "s": 53727, "text": "Now consider the above rewrite rules. Since V can be replaced by both, \"peck\" or \"pecks\",\nsentences such as \"The bird peck the grains\" can be wrongly permitted. i. e. the subject-verb\nagreement error is approved as correct." }, { "code": null, "e": 54017, "s": 53951, "text": "Merit − The simplest style of grammar, therefore widely used one." }, { "code": null, "e": 54028, "s": 54017, "text": "Demerits −" }, { "code": null, "e": 54216, "s": 54028, "text": "They are not highly precise. For example, “The grains peck the bird”, is a syntactically correct according to parser, but even if it makes no sense, parser takes it as a correct sentence." }, { "code": null, "e": 54404, "s": 54216, "text": "They are not highly precise. For example, “The grains peck the bird”, is a syntactically correct according to parser, but even if it makes no sense, parser takes it as a correct sentence." }, { "code": null, "e": 54671, "s": 54404, "text": "To bring out high precision, multiple sets of grammar need to be prepared. It may require a completely different sets of rules for parsing singular and plural variations, passive sentences, etc., which can lead to creation of huge set of rules that are unmanageable." }, { "code": null, "e": 54938, "s": 54671, "text": "To bring out high precision, multiple sets of grammar need to be prepared. It may require a completely different sets of rules for parsing singular and plural variations, passive sentences, etc., which can lead to creation of huge set of rules that are unmanageable." }, { "code": null, "e": 55151, "s": 54938, "text": "Here, the parser starts with the S symbol and attempts to rewrite it into a sequence of terminal symbols that matches the classes of the words in the input sentence until it consists entirely of terminal symbols." }, { "code": null, "e": 55388, "s": 55151, "text": "These are then checked with the input sentence to see if it matched. If not, the process is started over again with a different set of rules. This is repeated until a specific rule is found which describes the structure of the sentence." }, { "code": null, "e": 55423, "s": 55388, "text": "Merit − It is simple to implement." }, { "code": null, "e": 55434, "s": 55423, "text": "Demerits −" }, { "code": null, "e": 55514, "s": 55434, "text": "It is inefficient, as the search process has to be repeated if an error occurs." }, { "code": null, "e": 55537, "s": 55514, "text": "Slow speed of working." }, { "code": null, "e": 55695, "s": 55537, "text": "Expert systems (ES) are one of the prominent research domains of AI. It is introduced by the researchers at Stanford University, Computer Science Department." }, { "code": null, "e": 55869, "s": 55695, "text": "The expert systems are the computer applications developed to solve complex problems in a particular domain, at the level of extra-ordinary human intelligence and expertise." }, { "code": null, "e": 55886, "s": 55869, "text": "High performance" }, { "code": null, "e": 55901, "s": 55886, "text": "Understandable" }, { "code": null, "e": 55910, "s": 55901, "text": "Reliable" }, { "code": null, "e": 55928, "s": 55910, "text": "Highly responsive" }, { "code": null, "e": 55964, "s": 55928, "text": "The expert systems are capable of −" }, { "code": null, "e": 55973, "s": 55964, "text": "Advising" }, { "code": null, "e": 56024, "s": 55973, "text": "Instructing and assisting human in decision making" }, { "code": null, "e": 56038, "s": 56024, "text": "Demonstrating" }, { "code": null, "e": 56058, "s": 56038, "text": "Deriving a solution" }, { "code": null, "e": 56069, "s": 56058, "text": "Diagnosing" }, { "code": null, "e": 56081, "s": 56069, "text": "Explaining " }, { "code": null, "e": 56100, "s": 56081, "text": "Interpreting input" }, { "code": null, "e": 56119, "s": 56100, "text": "Predicting results" }, { "code": null, "e": 56145, "s": 56119, "text": "Justifying the conclusion" }, { "code": null, "e": 56189, "s": 56145, "text": "Suggesting alternative options to a problem" }, { "code": null, "e": 56213, "s": 56189, "text": "They are incapable of −" }, { "code": null, "e": 56248, "s": 56213, "text": "Substituting human decision makers" }, { "code": null, "e": 56278, "s": 56248, "text": "Possessing human capabilities" }, { "code": null, "e": 56334, "s": 56278, "text": "Producing accurate output for inadequate knowledge base" }, { "code": null, "e": 56363, "s": 56334, "text": "Refining their own knowledge" }, { "code": null, "e": 56394, "s": 56363, "text": "The components of ES include −" }, { "code": null, "e": 56409, "s": 56394, "text": "Knowledge Base" }, { "code": null, "e": 56426, "s": 56409, "text": "Inference Engine" }, { "code": null, "e": 56441, "s": 56426, "text": "User Interface" }, { "code": null, "e": 56478, "s": 56441, "text": "Let us see them one by one briefly −" }, { "code": null, "e": 56534, "s": 56478, "text": "It contains domain-specific and high-quality knowledge." }, { "code": null, "e": 56681, "s": 56534, "text": "Knowledge is required to exhibit intelligence. The success of any ES majorly depends upon the collection of highly accurate and precise knowledge." }, { "code": null, "e": 56867, "s": 56681, "text": "The data is collection of facts. The information is organized as data and facts about the task domain. Data, information, and past experience combined together are termed as knowledge. " }, { "code": null, "e": 56948, "s": 56867, "text": "The knowledge base of an ES is a store of both, factual and heuristic knowledge." }, { "code": null, "e": 57066, "s": 56948, "text": "Factual Knowledge − It is the information widely accepted by the Knowledge Engineers and scholars in the task domain." }, { "code": null, "e": 57184, "s": 57066, "text": "Factual Knowledge − It is the information widely accepted by the Knowledge Engineers and scholars in the task domain." }, { "code": null, "e": 57291, "s": 57184, "text": "Heuristic Knowledge − It is about practice, accurate judgement, one’s ability of evaluation, and guessing." }, { "code": null, "e": 57398, "s": 57291, "text": "Heuristic Knowledge − It is about practice, accurate judgement, one’s ability of evaluation, and guessing." }, { "code": null, "e": 57524, "s": 57398, "text": "It is the method used to organize and formalize the knowledge in the knowledge base. It is in the form of IF-THEN-ELSE rules." }, { "code": null, "e": 57665, "s": 57524, "text": "The success of any expert system majorly depends on the quality, completeness, and accuracy of the information stored in the knowledge base." }, { "code": null, "e": 57876, "s": 57665, "text": "The knowledge base is formed by readings from various experts, scholars, and the Knowledge Engineers. The knowledge engineer is a person with the qualities of empathy, quick learning, and case analyzing skills." }, { "code": null, "e": 58186, "s": 57876, "text": "He acquires information from subject expert by recording, interviewing, and observing him at work, etc. He then categorizes and organizes the information in a meaningful way, in the form of IF-THEN-ELSE rules, to be used by interference machine. The knowledge engineer also monitors the development of the ES." }, { "code": null, "e": 58304, "s": 58186, "text": "Use of efficient procedures and rules by the Inference Engine is essential in deducting a correct, flawless solution." }, { "code": null, "e": 58455, "s": 58304, "text": "In case of knowledge-based ES, the Inference Engine acquires and manipulates the knowledge from the knowledge base to arrive at a particular solution." }, { "code": null, "e": 58486, "s": 58455, "text": "In case of rule based ES, it −" }, { "code": null, "e": 58575, "s": 58486, "text": "Applies rules repeatedly to the facts, which are obtained from earlier rule application." }, { "code": null, "e": 58664, "s": 58575, "text": "Applies rules repeatedly to the facts, which are obtained from earlier rule application." }, { "code": null, "e": 58720, "s": 58664, "text": "Adds new knowledge into the knowledge base if required." }, { "code": null, "e": 58776, "s": 58720, "text": "Adds new knowledge into the knowledge base if required." }, { "code": null, "e": 58857, "s": 58776, "text": "Resolves rules conflict when multiple rules are applicable to a particular case." }, { "code": null, "e": 58938, "s": 58857, "text": "Resolves rules conflict when multiple rules are applicable to a particular case." }, { "code": null, "e": 59016, "s": 58938, "text": "To recommend a solution, the Inference Engine uses the following strategies −" }, { "code": null, "e": 59033, "s": 59016, "text": "Forward Chaining" }, { "code": null, "e": 59051, "s": 59033, "text": "Backward Chaining" }, { "code": null, "e": 59136, "s": 59051, "text": "It is a strategy of an expert system to answer the question, “What can happen next?”" }, { "code": null, "e": 59330, "s": 59136, "text": "Here, the Inference Engine follows the chain of conditions and derivations and finally deduces the outcome. It considers all the facts and rules, and sorts them before concluding to a solution." }, { "code": null, "e": 59492, "s": 59330, "text": "This strategy is followed for working on conclusion, result, or effect. For example, prediction of share market status as an effect of changes in interest rates." }, { "code": null, "e": 59588, "s": 59492, "text": "With this strategy, an expert system finds out the answer to the question, “Why this happened?”" }, { "code": null, "e": 59845, "s": 59588, "text": "On the basis of what has already happened, the Inference Engine tries to find out which conditions could have happened in the past for this result. This strategy is followed for finding out cause or reason. For example, diagnosis of blood cancer in humans." }, { "code": null, "e": 60116, "s": 59845, "text": "User interface provides interaction between user of the ES and the ES itself. It is generally Natural Language Processing so as to be used by the user who is well-versed in the task domain. The user of the ES need not be necessarily an expert in Artificial Intelligence." }, { "code": null, "e": 60235, "s": 60116, "text": "It explains how the ES has arrived at a particular recommendation. The explanation may appear in the following forms −" }, { "code": null, "e": 60273, "s": 60235, "text": "Natural language displayed on screen." }, { "code": null, "e": 60312, "s": 60273, "text": "Verbal narrations in natural language." }, { "code": null, "e": 60361, "s": 60312, "text": "Listing of rule numbers displayed on the screen." }, { "code": null, "e": 60438, "s": 60361, "text": "The user interface makes it easy to trace the credibility of the deductions." }, { "code": null, "e": 60511, "s": 60438, "text": "It should help users to accomplish their goals in shortest possible way." }, { "code": null, "e": 60584, "s": 60511, "text": "It should help users to accomplish their goals in shortest possible way." }, { "code": null, "e": 60661, "s": 60584, "text": "It should be designed to work for user’s existing or desired work practices." }, { "code": null, "e": 60738, "s": 60661, "text": "It should be designed to work for user’s existing or desired work practices." }, { "code": null, "e": 60822, "s": 60738, "text": "Its technology should be adaptable to user’s requirements; not the other way round." }, { "code": null, "e": 60906, "s": 60822, "text": "Its technology should be adaptable to user’s requirements; not the other way round." }, { "code": null, "e": 60950, "s": 60906, "text": "It should make efficient use of user input." }, { "code": null, "e": 60994, "s": 60950, "text": "It should make efficient use of user input." }, { "code": null, "e": 61177, "s": 60994, "text": "No technology can offer easy and complete solution. Large systems are costly, require significant development time, and computer resources. ESs have their limitations which include −" }, { "code": null, "e": 61207, "s": 61177, "text": "Limitations of the technology" }, { "code": null, "e": 61239, "s": 61207, "text": "Difficult knowledge acquisition" }, { "code": null, "e": 61268, "s": 61239, "text": "ES are difficult to maintain" }, { "code": null, "e": 61291, "s": 61268, "text": "High development costs" }, { "code": null, "e": 61342, "s": 61291, "text": "The following table shows where ES can be applied." }, { "code": null, "e": 61435, "s": 61342, "text": "There are several levels of ES technologies available. Expert systems technologies include −" }, { "code": null, "e": 61720, "s": 61435, "text": "Expert System Development Environment − The ES development environment includes hardware and tools. They are −\n\nWorkstations, minicomputers, mainframes.\nHigh level Symbolic Programming Languages such as LISt Programming (LISP) and PROgrammation en LOGique (PROLOG).\nLarge databases.\n\n" }, { "code": null, "e": 61831, "s": 61720, "text": "Expert System Development Environment − The ES development environment includes hardware and tools. They are −" }, { "code": null, "e": 61872, "s": 61831, "text": "Workstations, minicomputers, mainframes." }, { "code": null, "e": 61913, "s": 61872, "text": "Workstations, minicomputers, mainframes." }, { "code": null, "e": 62026, "s": 61913, "text": "High level Symbolic Programming Languages such as LISt Programming (LISP) and PROgrammation en LOGique (PROLOG)." }, { "code": null, "e": 62139, "s": 62026, "text": "High level Symbolic Programming Languages such as LISt Programming (LISP) and PROgrammation en LOGique (PROLOG)." }, { "code": null, "e": 62156, "s": 62139, "text": "Large databases." }, { "code": null, "e": 62173, "s": 62156, "text": "Large databases." }, { "code": null, "e": 62444, "s": 62173, "text": "Tools − They reduce the effort and cost involved in developing an expert system to large extent.\n\nPowerful editors and debugging tools with multi-windows.\nThey provide rapid prototyping\nHave Inbuilt definitions of model, knowledge representation, and inference design.\n\n" }, { "code": null, "e": 62541, "s": 62444, "text": "Tools − They reduce the effort and cost involved in developing an expert system to large extent." }, { "code": null, "e": 62598, "s": 62541, "text": "Powerful editors and debugging tools with multi-windows." }, { "code": null, "e": 62655, "s": 62598, "text": "Powerful editors and debugging tools with multi-windows." }, { "code": null, "e": 62686, "s": 62655, "text": "They provide rapid prototyping" }, { "code": null, "e": 62717, "s": 62686, "text": "They provide rapid prototyping" }, { "code": null, "e": 62800, "s": 62717, "text": "Have Inbuilt definitions of model, knowledge representation, and inference design." }, { "code": null, "e": 62883, "s": 62800, "text": "Have Inbuilt definitions of model, knowledge representation, and inference design." }, { "code": null, "e": 63373, "s": 62883, "text": "Shells − A shell is nothing but an expert system without knowledge base. A shell provides the developers with knowledge acquisition, inference engine, user interface, and explanation facility. For example, few shells are given below −\n\nJava Expert System Shell (JESS) that provides fully developed Java API for creating an expert system.\nVidwan, a shell developed at the National Centre for Software Technology, Mumbai in 1993. It enables knowledge encoding in the form of IF-THEN rules.\n\n" }, { "code": null, "e": 63608, "s": 63373, "text": "Shells − A shell is nothing but an expert system without knowledge base. A shell provides the developers with knowledge acquisition, inference engine, user interface, and explanation facility. For example, few shells are given below −" }, { "code": null, "e": 63710, "s": 63608, "text": "Java Expert System Shell (JESS) that provides fully developed Java API for creating an expert system." }, { "code": null, "e": 63812, "s": 63710, "text": "Java Expert System Shell (JESS) that provides fully developed Java API for creating an expert system." }, { "code": null, "e": 63962, "s": 63812, "text": "Vidwan, a shell developed at the National Centre for Software Technology, Mumbai in 1993. It enables knowledge encoding in the form of IF-THEN rules." }, { "code": null, "e": 64112, "s": 63962, "text": "Vidwan, a shell developed at the National Centre for Software Technology, Mumbai in 1993. It enables knowledge encoding in the form of IF-THEN rules." }, { "code": null, "e": 64193, "s": 64112, "text": "The process of ES development is iterative. Steps in developing the ES include −" }, { "code": null, "e": 64256, "s": 64193, "text": "The problem must be suitable for an expert system to solve it." }, { "code": null, "e": 64308, "s": 64256, "text": "Find the experts in task domain for the ES project." }, { "code": null, "e": 64352, "s": 64308, "text": "Establish cost-effectiveness of the system." }, { "code": null, "e": 64379, "s": 64352, "text": "Identify the ES Technology" }, { "code": null, "e": 64406, "s": 64379, "text": "Identify the ES Technology" }, { "code": null, "e": 64489, "s": 64406, "text": "Know and establish the degree of integration with the other systems and databases." }, { "code": null, "e": 64572, "s": 64489, "text": "Know and establish the degree of integration with the other systems and databases." }, { "code": null, "e": 64638, "s": 64572, "text": "Realize how the concepts can represent the domain knowledge best." }, { "code": null, "e": 64704, "s": 64638, "text": "Realize how the concepts can represent the domain knowledge best." }, { "code": null, "e": 64759, "s": 64704, "text": "From Knowledge Base: The knowledge engineer works to −" }, { "code": null, "e": 64801, "s": 64759, "text": "Acquire domain knowledge from the expert." }, { "code": null, "e": 64849, "s": 64801, "text": "Represent it in the form of If-THEN-ELSE rules." }, { "code": null, "e": 64949, "s": 64849, "text": "The knowledge engineer uses sample cases to test the prototype for any deficiencies in performance." }, { "code": null, "e": 65049, "s": 64949, "text": "The knowledge engineer uses sample cases to test the prototype for any deficiencies in performance." }, { "code": null, "e": 65090, "s": 65049, "text": "End users test the prototypes of the ES." }, { "code": null, "e": 65131, "s": 65090, "text": "End users test the prototypes of the ES." }, { "code": null, "e": 65274, "s": 65131, "text": "Test and ensure the interaction of the ES with all elements of its environment, including end users, databases, and other information systems." }, { "code": null, "e": 65417, "s": 65274, "text": "Test and ensure the interaction of the ES with all elements of its environment, including end users, databases, and other information systems." }, { "code": null, "e": 65447, "s": 65417, "text": "Document the ES project well." }, { "code": null, "e": 65477, "s": 65447, "text": "Document the ES project well." }, { "code": null, "e": 65503, "s": 65477, "text": "Train the user to use ES." }, { "code": null, "e": 65529, "s": 65503, "text": "Train the user to use ES." }, { "code": null, "e": 65594, "s": 65529, "text": "Keep the knowledge base up-to-date by regular review and update." }, { "code": null, "e": 65659, "s": 65594, "text": "Keep the knowledge base up-to-date by regular review and update." }, { "code": null, "e": 65741, "s": 65659, "text": "Cater for new interfaces with other information systems, as those systems evolve." }, { "code": null, "e": 65823, "s": 65741, "text": "Cater for new interfaces with other information systems, as those systems evolve." }, { "code": null, "e": 65900, "s": 65823, "text": "Availability − They are easily available due to mass production of software." }, { "code": null, "e": 65977, "s": 65900, "text": "Availability − They are easily available due to mass production of software." }, { "code": null, "e": 66059, "s": 65977, "text": "Less Production Cost − Production cost is reasonable. This makes them affordable." }, { "code": null, "e": 66141, "s": 66059, "text": "Less Production Cost − Production cost is reasonable. This makes them affordable." }, { "code": null, "e": 66227, "s": 66141, "text": "Speed − They offer great speed. They reduce the amount of work an individual puts in." }, { "code": null, "e": 66313, "s": 66227, "text": "Speed − They offer great speed. They reduce the amount of work an individual puts in." }, { "code": null, "e": 66378, "s": 66313, "text": "Less Error Rate − Error rate is low as compared to human errors." }, { "code": null, "e": 66443, "s": 66378, "text": "Less Error Rate − Error rate is low as compared to human errors." }, { "code": null, "e": 66513, "s": 66443, "text": "Reducing Risk − They can work in the environment dangerous to humans." }, { "code": null, "e": 66583, "s": 66513, "text": "Reducing Risk − They can work in the environment dangerous to humans." }, { "code": null, "e": 66666, "s": 66583, "text": "Steady response − They work steadily without getting motional, tensed or fatigued." }, { "code": null, "e": 66749, "s": 66666, "text": "Steady response − They work steadily without getting motional, tensed or fatigued." }, { "code": null, "e": 66869, "s": 66749, "text": "Robotics is a domain in artificial intelligence that deals with the study of creating intelligent and efficient robots." }, { "code": null, "e": 66936, "s": 66869, "text": "Robots are the artificial agents acting in real world environment." }, { "code": null, "e": 67200, "s": 66936, "text": "Robots are aimed at manipulating the objects by perceiving, picking, moving, modifying the physical properties of object, destroying it, or to have an effect thereby freeing manpower from doing repetitive functions without getting bored, distracted, or exhausted." }, { "code": null, "e": 67374, "s": 67200, "text": "Robotics is a branch of AI, which is composed of Electrical Engineering, Mechanical Engineering, and Computer Science for designing, construction, and application of robots." }, { "code": null, "e": 67472, "s": 67374, "text": "The robots have mechanical construction, form, or shape designed to accomplish a particular task." }, { "code": null, "e": 67570, "s": 67472, "text": "The robots have mechanical construction, form, or shape designed to accomplish a particular task." }, { "code": null, "e": 67641, "s": 67570, "text": "They have electrical components which power and control the machinery." }, { "code": null, "e": 67712, "s": 67641, "text": "They have electrical components which power and control the machinery." }, { "code": null, "e": 67815, "s": 67712, "text": "They contain some level of computer program that determines what, when and how a robot does something." }, { "code": null, "e": 67918, "s": 67815, "text": "They contain some level of computer program that determines what, when and how a robot does something." }, { "code": null, "e": 67959, "s": 67918, "text": "Here is the difference between the two −" }, { "code": null, "e": 68085, "s": 67959, "text": "Locomotion is the mechanism that makes a robot capable of moving in its environment. There are various types of locomotions −" }, { "code": null, "e": 68092, "s": 68085, "text": "Legged" }, { "code": null, "e": 68100, "s": 68092, "text": "Wheeled" }, { "code": null, "e": 68145, "s": 68100, "text": "Combination of Legged and Wheeled Locomotion" }, { "code": null, "e": 68164, "s": 68145, "text": "Tracked slip/skid " }, { "code": null, "e": 68274, "s": 68164, "text": "This type of locomotion consumes more power while demonstrating walk, jump, trot, hop, climb up or down, etc." }, { "code": null, "e": 68384, "s": 68274, "text": "This type of locomotion consumes more power while demonstrating walk, jump, trot, hop, climb up or down, etc." }, { "code": null, "e": 68650, "s": 68384, "text": "It requires more number of motors to accomplish a movement. It is suited for rough as well as smooth terrain where irregular or too smooth surface makes it consume more power for a wheeled locomotion. It is little difficult to implement because of stability issues." }, { "code": null, "e": 68916, "s": 68650, "text": "It requires more number of motors to accomplish a movement. It is suited for rough as well as smooth terrain where irregular or too smooth surface makes it consume more power for a wheeled locomotion. It is little difficult to implement because of stability issues." }, { "code": null, "e": 69055, "s": 68916, "text": "It comes with the variety of one, two, four, and six legs. If a robot has multiple legs then leg coordination is necessary for locomotion." }, { "code": null, "e": 69194, "s": 69055, "text": "It comes with the variety of one, two, four, and six legs. If a robot has multiple legs then leg coordination is necessary for locomotion." }, { "code": null, "e": 69361, "s": 69194, "text": "The total number of possible gaits (a periodic sequence of lift and release events for each of the total legs) a robot can travel depends upon the number of its legs." }, { "code": null, "e": 69432, "s": 69361, "text": "If a robot has k legs, then the number of possible events N = (2k-1)!." }, { "code": null, "e": 69535, "s": 69432, "text": "In case of a two-legged robot (k=2), the number of possible events is N = (2k-1)! = (2*2-1)! = 3! = 6." }, { "code": null, "e": 69583, "s": 69535, "text": "Hence there are six possible different events −" }, { "code": null, "e": 69604, "s": 69583, "text": "Lifting the Left leg" }, { "code": null, "e": 69627, "s": 69604, "text": "Releasing the Left leg" }, { "code": null, "e": 69649, "s": 69627, "text": "Lifting the Right leg" }, { "code": null, "e": 69673, "s": 69649, "text": "Releasing the Right leg" }, { "code": null, "e": 69704, "s": 69673, "text": "Lifting both the legs together" }, { "code": null, "e": 69737, "s": 69704, "text": "Releasing both the legs together" }, { "code": null, "e": 69873, "s": 69737, "text": "In case of k=6 legs, there are 39916800 possible events. Hence the complexity of robots is directly proportional to the number of legs." }, { "code": null, "e": 70090, "s": 69873, "text": "It requires fewer number of motors to accomplish a movement. It is little easy to implement as there are less stability issues in case of more number of wheels. It is power efficient as compared to legged locomotion." }, { "code": null, "e": 70160, "s": 70090, "text": "Standard wheel − Rotates around the wheel axle and around the contact" }, { "code": null, "e": 70230, "s": 70160, "text": "Standard wheel − Rotates around the wheel axle and around the contact" }, { "code": null, "e": 70306, "s": 70230, "text": "Castor wheel − Rotates around the wheel axle and the offset steering joint." }, { "code": null, "e": 70382, "s": 70306, "text": "Castor wheel − Rotates around the wheel axle and the offset steering joint." }, { "code": null, "e": 70512, "s": 70382, "text": "Swedish 45o and Swedish 90o wheels − Omni-wheel, rotates around the contact point, around the wheel axle, and around the rollers." }, { "code": null, "e": 70642, "s": 70512, "text": "Swedish 45o and Swedish 90o wheels − Omni-wheel, rotates around the contact point, around the wheel axle, and around the rollers." }, { "code": null, "e": 70727, "s": 70642, "text": "Ball or spherical wheel − Omnidirectional wheel, technically difficult to implement." }, { "code": null, "e": 70812, "s": 70727, "text": "Ball or spherical wheel − Omnidirectional wheel, technically difficult to implement." }, { "code": null, "e": 71034, "s": 70812, "text": "In this type, the vehicles use tracks as in a tank. The robot is steered by moving the tracks with different speeds in the same or opposite direction. It offers stability because of large contact area of track and ground." }, { "code": null, "e": 71078, "s": 71034, "text": "Robots are constructed with the following −" }, { "code": null, "e": 71182, "s": 71078, "text": "Power Supply − The robots are powered by batteries, solar power, hydraulic, or pneumatic power sources." }, { "code": null, "e": 71286, "s": 71182, "text": "Power Supply − The robots are powered by batteries, solar power, hydraulic, or pneumatic power sources." }, { "code": null, "e": 71333, "s": 71286, "text": "Actuators − They convert energy into movement." }, { "code": null, "e": 71380, "s": 71333, "text": "Actuators − They convert energy into movement." }, { "code": null, "e": 71449, "s": 71380, "text": "Electric motors (AC/DC) − They are required for rotational movement." }, { "code": null, "e": 71518, "s": 71449, "text": "Electric motors (AC/DC) − They are required for rotational movement." }, { "code": null, "e": 71595, "s": 71518, "text": "Pneumatic Air Muscles − They contract almost 40% when air is sucked in them." }, { "code": null, "e": 71672, "s": 71595, "text": "Pneumatic Air Muscles − They contract almost 40% when air is sucked in them." }, { "code": null, "e": 71753, "s": 71672, "text": "Muscle Wires − They contract by 5% when electric current is passed through them." }, { "code": null, "e": 71834, "s": 71753, "text": "Muscle Wires − They contract by 5% when electric current is passed through them." }, { "code": null, "e": 71899, "s": 71834, "text": "Piezo Motors and Ultrasonic Motors − Best for industrial robots." }, { "code": null, "e": 71964, "s": 71899, "text": "Piezo Motors and Ultrasonic Motors − Best for industrial robots." }, { "code": null, "e": 72226, "s": 71964, "text": "Sensors − They provide knowledge of real time information on the task environment. Robots are equipped with vision sensors to be to compute the depth in the environment. A tactile sensor imitates the mechanical properties of touch receptors of human fingertips." }, { "code": null, "e": 72488, "s": 72226, "text": "Sensors − They provide knowledge of real time information on the task environment. Robots are equipped with vision sensors to be to compute the depth in the environment. A tactile sensor imitates the mechanical properties of touch receptors of human fingertips." }, { "code": null, "e": 72654, "s": 72488, "text": "This is a technology of AI with which the robots can see. The computer vision plays vital role in the domains of safety, security, health, access, and entertainment." }, { "code": null, "e": 72876, "s": 72654, "text": "Computer vision automatically extracts, analyzes, and comprehends useful information from a single image or an array of images. This process involves development of algorithms to accomplish automatic visual comprehension." }, { "code": null, "e": 72892, "s": 72876, "text": "This involves −" }, { "code": null, "e": 72905, "s": 72892, "text": "Power supply" }, { "code": null, "e": 72945, "s": 72905, "text": "Image acquisition device such as camera" }, { "code": null, "e": 72958, "s": 72945, "text": "A processor " }, { "code": null, "e": 72969, "s": 72958, "text": "A software" }, { "code": null, "e": 73012, "s": 72969, "text": "A display device for monitoring the system" }, { "code": null, "e": 73070, "s": 73012, "text": "Accessories such as camera stands, cables, and connectors" }, { "code": null, "e": 73219, "s": 73070, "text": "OCR − In the domain of computers, Optical Character Reader, a software to convert scanned documents into editable text, which accompanies a scanner." }, { "code": null, "e": 73368, "s": 73219, "text": "OCR − In the domain of computers, Optical Character Reader, a software to convert scanned documents into editable text, which accompanies a scanner." }, { "code": null, "e": 73582, "s": 73368, "text": "Face Detection − Many state-of-the-art cameras come with this feature, which enables to read the face and take the picture of that perfect expression. It is used to let a user access the software on correct match." }, { "code": null, "e": 73796, "s": 73582, "text": "Face Detection − Many state-of-the-art cameras come with this feature, which enables to read the face and take the picture of that perfect expression. It is used to let a user access the software on correct match." }, { "code": null, "e": 73904, "s": 73796, "text": "Object Recognition − They are installed in supermarkets, cameras, high-end cars such as BMW, GM, and Volvo." }, { "code": null, "e": 74012, "s": 73904, "text": "Object Recognition − They are installed in supermarkets, cameras, high-end cars such as BMW, GM, and Volvo." }, { "code": null, "e": 74137, "s": 74012, "text": "Estimating Position − It is estimating position of an object with respect to camera as in position of tumor in human’s body." }, { "code": null, "e": 74262, "s": 74137, "text": "Estimating Position − It is estimating position of an object with respect to camera as in position of tumor in human’s body." }, { "code": null, "e": 74274, "s": 74262, "text": "Agriculture" }, { "code": null, "e": 74294, "s": 74274, "text": "Autonomous vehicles" }, { "code": null, "e": 74305, "s": 74294, "text": "Biometrics" }, { "code": null, "e": 74327, "s": 74305, "text": "Character recognition" }, { "code": null, "e": 74365, "s": 74327, "text": "Forensics, security, and surveillance" }, { "code": null, "e": 74395, "s": 74365, "text": "Industrial quality inspection" }, { "code": null, "e": 74412, "s": 74395, "text": "Face recognition" }, { "code": null, "e": 74429, "s": 74412, "text": "Gesture analysis" }, { "code": null, "e": 74440, "s": 74429, "text": "Geoscience" }, { "code": null, "e": 74456, "s": 74440, "text": "Medical imagery" }, { "code": null, "e": 74477, "s": 74456, "text": "Pollution monitoring" }, { "code": null, "e": 74494, "s": 74477, "text": "Process control " }, { "code": null, "e": 74509, "s": 74494, "text": "Remote sensing" }, { "code": null, "e": 74518, "s": 74509, "text": "Robotics" }, { "code": null, "e": 74528, "s": 74518, "text": "Transport" }, { "code": null, "e": 74596, "s": 74528, "text": "The robotics has been instrumental in the various domains such as −" }, { "code": null, "e": 74707, "s": 74596, "text": "Industries − Robots are used for handling material, cutting, welding, color coating, drilling, polishing, etc." }, { "code": null, "e": 74818, "s": 74707, "text": "Industries − Robots are used for handling material, cutting, welding, color coating, drilling, polishing, etc." }, { "code": null, "e": 75049, "s": 74818, "text": "Military − Autonomous robots can reach inaccessible and hazardous zones during war. A robot named Daksh, developed by Defense Research and Development Organization (DRDO), is in function to destroy life-threatening objects safely." }, { "code": null, "e": 75280, "s": 75049, "text": "Military − Autonomous robots can reach inaccessible and hazardous zones during war. A robot named Daksh, developed by Defense Research and Development Organization (DRDO), is in function to destroy life-threatening objects safely." }, { "code": null, "e": 75472, "s": 75280, "text": "Medicine − The robots are capable of carrying out hundreds of clinical tests simultaneously, rehabilitating permanently disabled people, and performing complex surgeries such as brain tumors." }, { "code": null, "e": 75664, "s": 75472, "text": "Medicine − The robots are capable of carrying out hundreds of clinical tests simultaneously, rehabilitating permanently disabled people, and performing complex surgeries such as brain tumors." }, { "code": null, "e": 75794, "s": 75664, "text": "Exploration − The robot rock climbers used for space exploration, underwater drones used for ocean exploration are to name a few." }, { "code": null, "e": 75924, "s": 75794, "text": "Exploration − The robot rock climbers used for space exploration, underwater drones used for ocean exploration are to name a few." }, { "code": null, "e": 76009, "s": 75924, "text": "Entertainment − Disney’s engineers have created hundreds of robots for movie making." }, { "code": null, "e": 76094, "s": 76009, "text": "Entertainment − Disney’s engineers have created hundreds of robots for movie making." }, { "code": null, "e": 76213, "s": 76094, "text": "Yet another research area in AI, neural networks, is inspired from the natural neural network of human nervous system." }, { "code": null, "e": 76310, "s": 76213, "text": "The inventor of the first neurocomputer, Dr. Robert Hecht-Nielsen, defines a neural network as −" }, { "code": null, "e": 76484, "s": 76310, "text": "The idea of ANNs is based on the belief that working of human brain by making the right connections, can be imitated using silicon and wires as living neurons and dendrites." }, { "code": null, "e": 76886, "s": 76484, "text": "The human brain is composed of 86 billion nerve cells called neurons. They are connected to other thousand cells by Axons. Stimuli from external environment or inputs from sensory organs are accepted by dendrites. These inputs create electric impulses, which quickly travel through the neural network. A neuron can then send the message to other neuron to handle the issue or does not send it forward." }, { "code": null, "e": 77238, "s": 76886, "text": "ANNs are composed of multiple nodes, which imitate biological neurons of human brain. The neurons are connected by links and they interact with each other. The nodes can take input data and perform simple operations on the data. The result of these operations is passed to other neurons. The output at each node is called its activation or node value." }, { "code": null, "e": 77398, "s": 77238, "text": "Each link is associated with weight. ANNs are capable of learning, which takes place by altering weight values. The following illustration shows a simple ANN −" }, { "code": null, "e": 77477, "s": 77398, "text": "There are two Artificial Neural Network topologies − FeedForward and Feedback." }, { "code": null, "e": 77746, "s": 77477, "text": "In this ANN, the information flow is unidirectional. A unit sends information to other unit from which it does not receive any information. There are no feedback loops. They are used in\npattern generation/recognition/classification. They have fixed inputs and outputs." }, { "code": null, "e": 77827, "s": 77746, "text": "Here, feedback loops are allowed. They are used in content addressable memories." }, { "code": null, "e": 78067, "s": 77827, "text": "In the topology diagrams shown, each arrow represents a connection between two neurons and indicates the pathway for the flow of information. Each connection has a weight, an integer number that controls the signal between the two neurons." }, { "code": null, "e": 78311, "s": 78067, "text": "If the network generates a “good or desired” output, there is no need to adjust the weights. However, if the network generates a “poor or undesired” output or an error, then the system alters the weights in order to improve subsequent results." }, { "code": null, "e": 78409, "s": 78311, "text": "ANNs are capable of learning and they need to be trained. There are several learning strategies −" }, { "code": null, "e": 78842, "s": 78409, "text": "Supervised Learning − It involves a teacher that is scholar than the ANN itself. For example, the teacher feeds some example data about which the teacher already knows the answers.\nFor example, pattern recognizing. The ANN comes up with guesses while recognizing. Then the teacher provides the ANN with the answers. The network then compares it guesses with the teacher’s “correct” answers and makes adjustments according to errors." }, { "code": null, "e": 79023, "s": 78842, "text": "Supervised Learning − It involves a teacher that is scholar than the ANN itself. For example, the teacher feeds some example data about which the teacher already knows the answers." }, { "code": null, "e": 79275, "s": 79023, "text": "For example, pattern recognizing. The ANN comes up with guesses while recognizing. Then the teacher provides the ANN with the answers. The network then compares it guesses with the teacher’s “correct” answers and makes adjustments according to errors." }, { "code": null, "e": 79572, "s": 79275, "text": "Unsupervised Learning − It is required when there is no example data set with known answers. For example, searching for a hidden pattern. In this case, clustering i.e. dividing a set of elements into groups according to some unknown pattern is carried out based on the existing data sets present." }, { "code": null, "e": 79869, "s": 79572, "text": "Unsupervised Learning − It is required when there is no example data set with known answers. For example, searching for a hidden pattern. In this case, clustering i.e. dividing a set of elements into groups according to some unknown pattern is carried out based on the existing data sets present." }, { "code": null, "e": 80113, "s": 79869, "text": "Reinforcement Learning − This strategy built on observation. The ANN makes a decision by observing its environment. If the observation is negative, the network adjusts its weights to be able to make a different required decision the next time." }, { "code": null, "e": 80357, "s": 80113, "text": "Reinforcement Learning − This strategy built on observation. The ANN makes a decision by observing its environment. If the observation is negative, the network adjusts its weights to be able to make a different required decision the next time." }, { "code": null, "e": 80621, "s": 80357, "text": "It is the training or learning algorithm. It learns by example. If you submit to the algorithm the example of what you want the network to do, it changes the network’s weights so that it can produce desired output for a particular input on finishing the training." }, { "code": null, "e": 80707, "s": 80621, "text": "Back Propagation networks are ideal for simple Pattern Recognition and Mapping Tasks." }, { "code": null, "e": 80924, "s": 80707, "text": "These are the graphical structures used to represent the probabilistic relationship among a set of random variables. Bayesian networks are also called Belief Networks or Bayes Nets. BNs reason about uncertain domain." }, { "code": null, "e": 81124, "s": 80924, "text": "In these networks, each node represents a random variable with specific propositions. For example, in a medical diagnosis domain, the node Cancer represents the proposition that a patient has cancer." }, { "code": null, "e": 81451, "s": 81124, "text": "The edges connecting the nodes represent probabilistic dependencies among those random variables. If out of two nodes, one is affecting the other then they must be directly connected in the directions of the effect. The strength of the relationship between variables is quantified by the probability associated with each node." }, { "code": null, "e": 81624, "s": 81451, "text": "There is an only constraint on the arcs in a BN that you cannot return to a node simply by following directed arcs. Hence the BNs are called Directed Acyclic Graphs (DAGs)." }, { "code": null, "e": 81740, "s": 81624, "text": "BNs are capable of handling multivalued variables simultaneously. The BN variables are composed of two dimensions −" }, { "code": null, "e": 81762, "s": 81740, "text": "Range of prepositions" }, { "code": null, "e": 81812, "s": 81762, "text": "Probability assigned to each of the prepositions." }, { "code": null, "e": 82125, "s": 81812, "text": "Consider a finite set X = {X1, X2, ...,Xn} of discrete random variables, where each variable Xi may take values from a finite set, denoted by Val(Xi). If there is a directed link from variable Xi to variable, Xj, then variable Xi will be a parent of variable Xj showing direct dependencies between the variables." }, { "code": null, "e": 82351, "s": 82125, "text": "The structure of BN is ideal for combining prior knowledge and observed data. BN can be used to learn the causal relationships and understand various problem domains and to predict future events, even in case of missing data." }, { "code": null, "e": 82486, "s": 82351, "text": "A knowledge engineer can build a Bayesian network. There are a number of steps the knowledge engineer needs to take while building it." }, { "code": null, "e": 82765, "s": 82486, "text": "Example problem − Lung cancer. A patient has been suffering from breathlessness. He visits the doctor, suspecting he has lung cancer. The doctor knows that barring lung cancer, there are various other possible diseases the patient might have such as tuberculosis and bronchitis." }, { "code": null, "e": 82804, "s": 82765, "text": "Gather Relevant Information of Problem" }, { "code": null, "e": 82881, "s": 82804, "text": "Is the patient a smoker? If yes, then high chances of cancer and bronchitis." }, { "code": null, "e": 82958, "s": 82881, "text": "Is the patient exposed to air pollution? If yes, what sort of air pollution?" }, { "code": null, "e": 83028, "s": 82958, "text": "Take an X-Ray positive X-ray would indicate either TB or lung cancer." }, { "code": null, "e": 83059, "s": 83028, "text": "Identify Interesting Variables" }, { "code": null, "e": 83114, "s": 83059, "text": "The knowledge engineer tries to answer the questions −" }, { "code": null, "e": 83140, "s": 83114, "text": "Which nodes to represent?" }, { "code": null, "e": 83195, "s": 83140, "text": "What values can they take? In which state can they be?" }, { "code": null, "e": 83318, "s": 83195, "text": "For now let us consider nodes, with only discrete values. The variable must take on exactly one of these values at a time." }, { "code": null, "e": 83355, "s": 83318, "text": "Common types of discrete nodes are −" }, { "code": null, "e": 83445, "s": 83355, "text": "Boolean nodes − They represent propositions, taking binary values TRUE (T) and FALSE (F)." }, { "code": null, "e": 83535, "s": 83445, "text": "Boolean nodes − They represent propositions, taking binary values TRUE (T) and FALSE (F)." }, { "code": null, "e": 83682, "s": 83535, "text": "Ordered values − A node Pollution might represent and take values from {low, medium, high} describing degree of a patient’s exposure to pollution." }, { "code": null, "e": 83829, "s": 83682, "text": "Ordered values − A node Pollution might represent and take values from {low, medium, high} describing degree of a patient’s exposure to pollution." }, { "code": null, "e": 83990, "s": 83829, "text": "Integral values − A node called Age might represent patient’s age with possible values from 1 to 120. Even at this early stage, modeling choices are being made." }, { "code": null, "e": 84151, "s": 83990, "text": "Integral values − A node called Age might represent patient’s age with possible values from 1 to 120. Even at this early stage, modeling choices are being made." }, { "code": null, "e": 84207, "s": 84151, "text": "Possible nodes and values for the lung cancer example −" }, { "code": null, "e": 84233, "s": 84207, "text": "Create Arcs between Nodes" }, { "code": null, "e": 84317, "s": 84233, "text": "Topology of the network should capture qualitative relationships between variables." }, { "code": null, "e": 84469, "s": 84317, "text": "For example, what causes a patient to have lung cancer? - Pollution and smoking. Then add arcs from node Pollution and node Smoker to node Lung-Cancer." }, { "code": null, "e": 84594, "s": 84469, "text": "Similarly if patient has lung cancer, then X-ray result will be positive. Then add arcs from node Lung-Cancer to node X-Ray." }, { "code": null, "e": 84611, "s": 84594, "text": "Specify Topology" }, { "code": null, "e": 84747, "s": 84611, "text": "Conventionally, BNs are laid out so that the arcs point from top to bottom. The set of parent nodes of a node X is given by Parents(X)." }, { "code": null, "e": 84993, "s": 84747, "text": "The Lung-Cancer node has two parents (reasons or causes): Pollution and Smoker, while node Smoker is an ancestor of node X-Ray. Similarly, X-Ray is a child (consequence or effects) of node Lung-Cancer and successor of nodes Smoker and Pollution." }, { "code": null, "e": 85019, "s": 84993, "text": "Conditional Probabilities" }, { "code": null, "e": 85266, "s": 85019, "text": "Now quantify the relationships between connected nodes: this is done by specifying a conditional probability distribution for each node. As only discrete variables are considered here, this takes the form of a Conditional Probability Table (CPT)." }, { "code": null, "e": 85554, "s": 85266, "text": "First, for each node we need to look at all the possible combinations of values of those parent nodes. Each such combination is called an instantiation of the parent set. For each distinct instantiation of parent node values, we need to specify the probability that the child will take. " }, { "code": null, "e": 85800, "s": 85554, "text": "For example, the Lung-Cancer node’s parents are Pollution and Smoking. They take the possible values = { (H,T), ( H,F), (L,T), (L,F)}. The CPT specifies the probability of cancer for each of these cases as <0.05, 0.02, 0.03, 0.001> respectively." }, { "code": null, "e": 85868, "s": 85800, "text": "Each node will have conditional probability associated as follows −" }, { "code": null, "e": 85947, "s": 85868, "text": "They can perform tasks that are easy for a human but difficult for a machine −" }, { "code": null, "e": 86006, "s": 85947, "text": "Aerospace − Autopilot aircrafts, aircraft fault detection." }, { "code": null, "e": 86065, "s": 86006, "text": "Aerospace − Autopilot aircrafts, aircraft fault detection." }, { "code": null, "e": 86107, "s": 86065, "text": "Automotive − Automobile guidance systems." }, { "code": null, "e": 86149, "s": 86107, "text": "Automotive − Automobile guidance systems." }, { "code": null, "e": 86282, "s": 86149, "text": "Military − Weapon orientation and steering, target tracking, object discrimination, facial recognition, signal/image identification." }, { "code": null, "e": 86415, "s": 86282, "text": "Military − Weapon orientation and steering, target tracking, object discrimination, facial recognition, signal/image identification." }, { "code": null, "e": 86527, "s": 86415, "text": "Electronics − Code sequence prediction, IC chip layout, chip failure analysis, machine vision, voice synthesis." }, { "code": null, "e": 86639, "s": 86527, "text": "Electronics − Code sequence prediction, IC chip layout, chip failure analysis, machine vision, voice synthesis." }, { "code": null, "e": 86864, "s": 86639, "text": "Financial − Real estate appraisal, loan advisor, mortgage screening, corporate bond rating, portfolio trading program, corporate financial analysis, currency value prediction, document readers, credit application evaluators." }, { "code": null, "e": 87089, "s": 86864, "text": "Financial − Real estate appraisal, loan advisor, mortgage screening, corporate bond rating, portfolio trading program, corporate financial analysis, currency value prediction, document readers, credit application evaluators." }, { "code": null, "e": 87396, "s": 87089, "text": "Industrial − Manufacturing process control, product design and analysis, quality inspection systems, welding quality analysis, paper quality prediction, chemical product design analysis, dynamic modeling of chemical process systems, machine maintenance analysis, project bidding, planning, and management." }, { "code": null, "e": 87703, "s": 87396, "text": "Industrial − Manufacturing process control, product design and analysis, quality inspection systems, welding quality analysis, paper quality prediction, chemical product design analysis, dynamic modeling of chemical process systems, machine maintenance analysis, project bidding, planning, and management." }, { "code": null, "e": 87803, "s": 87703, "text": "Medical − Cancer cell analysis, EEG and ECG analysis, prosthetic design, transplant time optimizer." }, { "code": null, "e": 87903, "s": 87803, "text": "Medical − Cancer cell analysis, EEG and ECG analysis, prosthetic design, transplant time optimizer." }, { "code": null, "e": 87982, "s": 87903, "text": "Speech − Speech recognition, speech classification, text to speech conversion." }, { "code": null, "e": 88061, "s": 87982, "text": "Speech − Speech recognition, speech classification, text to speech conversion." }, { "code": null, "e": 88181, "s": 88061, "text": "Telecommunications − Image and data compression, automated information services, real-time spoken language translation." }, { "code": null, "e": 88301, "s": 88181, "text": "Telecommunications − Image and data compression, automated information services, real-time spoken language translation." }, { "code": null, "e": 88385, "s": 88301, "text": "Transportation − Truck Brake system diagnosis, vehicle scheduling, routing systems." }, { "code": null, "e": 88469, "s": 88385, "text": "Transportation − Truck Brake system diagnosis, vehicle scheduling, routing systems." }, { "code": null, "e": 88559, "s": 88469, "text": "Software − Pattern Recognition in facial recognition, optical character recognition, etc." }, { "code": null, "e": 88649, "s": 88559, "text": "Software − Pattern Recognition in facial recognition, optical character recognition, etc." }, { "code": null, "e": 88742, "s": 88649, "text": "Time Series Prediction − ANNs are used to make predictions on stocks and natural calamities." }, { "code": null, "e": 88835, "s": 88742, "text": "Time Series Prediction − ANNs are used to make predictions on stocks and natural calamities." }, { "code": null, "e": 88962, "s": 88835, "text": "Signal Processing − Neural networks can be trained to process an audio signal and filter it appropriately in the hearing aids." }, { "code": null, "e": 89089, "s": 88962, "text": "Signal Processing − Neural networks can be trained to process an audio signal and filter it appropriately in the hearing aids." }, { "code": null, "e": 89168, "s": 89089, "text": "Control − ANNs are often used to make steering decisions of physical vehicles." }, { "code": null, "e": 89247, "s": 89168, "text": "Control − ANNs are often used to make steering decisions of physical vehicles." }, { "code": null, "e": 89414, "s": 89247, "text": "Anomaly Detection − As ANNs are expert at recognizing patterns, they can also be trained to generate an output when something unusual occurs that misfits the pattern." }, { "code": null, "e": 89581, "s": 89414, "text": "Anomaly Detection − As ANNs are expert at recognizing patterns, they can also be trained to generate an output when something unusual occurs that misfits the pattern." }, { "code": null, "e": 89799, "s": 89581, "text": "AI is developing with such an incredible speed, sometimes it seems magical. There is an opinion among researchers and developers that AI could grow so immensely strong that it would be difficult for humans to control." }, { "code": null, "e": 89945, "s": 89799, "text": "Humans developed AI systems by introducing into them every possible intelligence they could, for which the humans themselves now seem threatened." }, { "code": null, "e": 90102, "s": 89945, "text": "An AI program that recognizes speech and understands natural language is theoretically capable of understanding each conversation on e-mails and telephones." }, { "code": null, "e": 90352, "s": 90102, "text": "AI systems have already started replacing the human beings in few industries. It should not replace people in the sectors where they are holding dignified positions which are pertaining to ethics such as nursing, surgeon, judge, police officer, etc." }, { "code": null, "e": 90523, "s": 90352, "text": "The self-improving AI systems can become so mighty than humans that could be very difficult to stop from achieving their goals, which may lead to unintended consequences." }, { "code": null, "e": 90587, "s": 90523, "text": "Here is the list of frequently used terms in the domain of AI −" }, { "code": null, "e": 90593, "s": 90587, "text": "Agent" }, { "code": null, "e": 90814, "s": 90593, "text": "Agents are systems or software programs capable of autonomous, purposeful and reasoning directed towards one or more goals. They are also called assistants, brokers, bots, droids, intelligent agents, and software agents." }, { "code": null, "e": 90831, "s": 90814, "text": "Autonomous Robot" }, { "code": null, "e": 90919, "s": 90831, "text": "Robot free from external control or influence and able to control itself independently." }, { "code": null, "e": 90937, "s": 90919, "text": "Backward Chaining" }, { "code": null, "e": 90997, "s": 90937, "text": "Strategy of working backward for Reason/Cause of a problem." }, { "code": null, "e": 91008, "s": 90997, "text": "Blackboard" }, { "code": null, "e": 91114, "s": 91008, "text": "It is the memory inside computer, which is used for communication between the cooperating expert systems." }, { "code": null, "e": 91126, "s": 91114, "text": "Environment" }, { "code": null, "e": 91196, "s": 91126, "text": "It is the part of real or computational world inhabited by the agent." }, { "code": null, "e": 91213, "s": 91196, "text": "Forward Chaining" }, { "code": null, "e": 91279, "s": 91213, "text": "Strategy of working forward for conclusion/solution of a problem." }, { "code": null, "e": 91290, "s": 91279, "text": "Heuristics" }, { "code": null, "e": 91370, "s": 91290, "text": "It is the knowledge based on Trial-and-error, evaluations, and experimentation." }, { "code": null, "e": 91392, "s": 91370, "text": "Knowledge Engineering" }, { "code": null, "e": 91452, "s": 91392, "text": "Acquiring knowledge from human experts and other resources." }, { "code": null, "e": 91461, "s": 91452, "text": "Percepts" }, { "code": null, "e": 91540, "s": 91461, "text": "It is the format in which the agent obtains information about the environment." }, { "code": null, "e": 91548, "s": 91540, "text": "Pruning" }, { "code": null, "e": 91616, "s": 91548, "text": "Overriding unnecessary and irrelevant considerations in AI systems." }, { "code": null, "e": 91621, "s": 91616, "text": "Rule" }, { "code": null, "e": 91720, "s": 91621, "text": "It is a format of representing knowledge base in Expert System. It is in the form of IF-THEN-ELSE." }, { "code": null, "e": 91726, "s": 91720, "text": "Shell" }, { "code": null, "e": 91846, "s": 91726, "text": "A shell is a software that helps in designing inference engine, knowledge base, and user interface of an expert system." }, { "code": null, "e": 91851, "s": 91846, "text": "Task" }, { "code": null, "e": 91900, "s": 91851, "text": "It is the goal the agent is tries to accomplish." }, { "code": null, "e": 91912, "s": 91900, "text": "Turing Test" }, { "code": null, "e": 92018, "s": 91912, "text": "A test developed by Allan Turing to test the intelligence of a machine as compared to human intelligence." }, { "code": null, "e": 92051, "s": 92018, "text": "\n 78 Lectures \n 7 hours \n" }, { "code": null, "e": 92070, "s": 92051, "text": " Arnab Chakraborty" }, { "code": null, "e": 92105, "s": 92070, "text": "\n 87 Lectures \n 9.5 hours \n" }, { "code": null, "e": 92136, "s": 92105, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 92169, "s": 92136, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 92188, "s": 92169, "text": " Nikoloz Sanakoevi" }, { "code": null, "e": 92220, "s": 92188, "text": "\n 15 Lectures \n 54 mins\n" }, { "code": null, "e": 92241, "s": 92220, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 92274, "s": 92241, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 92292, "s": 92274, "text": " Gilad James, PhD" }, { "code": null, "e": 92325, "s": 92292, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 92343, "s": 92325, "text": " Gilad James, PhD" }, { "code": null, "e": 92350, "s": 92343, "text": " Print" }, { "code": null, "e": 92361, "s": 92350, "text": " Add Notes" } ]
Automated Brute Forcing on web-based login - GeeksforGeeks
23 May, 2017 Brute force attacks work by calculating every possible combination that could make up a password and testing it to see if it is the correct password. As the password’s length increases, the amount of time, on average, to find the correct password increases exponentially. This means short passwords can usually be discovered quite quickly, but longer passwords may take decades [Source : Wiki] It may be feasible in some situations as computer hardwares are getting faster and faster. A simple brute-force attack would start with one-digit passwords, then two-digit passwords and so on, trying all possible combinations until one works. A better idea is “dictionary attack” that tries words in a dictionary — or a list of common passwords — instead of all possible passwords. This can be very effective, as many people use such weak and common passwords. We can use automated tool for Brute forcing web-based login form Using Hydra to dictionary-attack web-based login formsHydra is an online password cracking for dictionary-attacks. It tries lists of user-names and passwords until a successful login is found. It is multi-threaded and can try username/password combinations at a rate of thousands per minute [Source Hydra can be used to attack many different services including IMAP, SMB, HTTP, VNC, MS-SQL MySQL, SMTP, SSH, and many more This tool should not be used to attack websites or services where you do not have permission to do so. Use this for legitimate testing purposes only. An example attackThe Web Security Dojo has various vulnerable applications that you can use to test these techniques. So looking at an example the w3af testing framework has a test login at the following location http://192.168.1.69/w3af/bruteforce/form_login/ The important parts of the HTML form are: <form name="input" action="dataReceptor.php" method="post">Username:<input type="text" name="user"> Password:<input type="password" name="pass"> If we put in one wrong username and password combination we get: Bad login, stop bruteforcing me!Bad u/p combination for user: aSo, now we have the information we need to attack this login form, we can use this info to construct a Hydra brute-force attack as follows: hydra 192.168.1.69 http-form-post "/w3af/bruteforce/form_login/dataReceptor.php:user=^USER^&pass=^PASS^:Bad login" -L users.txt -P pass.txt -t 10 -w 30 -o hydra-http-post-attack.txt If we break this up Host = 192.168.1.69 Method = http-form-post URL = /w3af/bruteforce/form_login/dataReceptor.php Form parameters = user=^USER^&pass=^PASS^ Failure response = Bad login Users file = users.txt Password file = pass.txt Threads = -t 10 Wait for timeout = -w 30 Output file = -o hydra-http-post-attack.txt Hydra basically iterates through all the username/password combinations, until it gets a response that does not contain the text “Bad login”. When we run this attack we get: Hydra basically iterates through all the username/password combinations, until it gets a response that does not contain the text "Bad login". When we run this attack we get: Hydra v6.5 (c) 2011 by van Hauser / THC and David Maciejak - use allowed only for legal purposes.Hydra (http://www.thc.org/thc-hydra) starting at 2011-08-22 13:11:03 [DATA] 5 tasks, 1 servers, 5 login tries (l:5/p:1), ~1 tries per task [DATA] attacking service http-post-form on port 80 [STATUS] attack finished for 192.168.1.69 (waiting for children to finish) [80][www-form] host: 192.168.1.69 login: admin password: 1234 Hydra (http://www.thc.org/thc-hydra) finished at 2011-08-22 13:11:07 As you can see, this was successful and found the user "admin" with password "1234". Prevention The first is to implement an account lockout policy. For example, after three failed login attempts, the account is locked out until an administrator unlocks it.We should use a challenge-response test to prevent automated submissions of the login page. Tools such as the free reCAPTCHA can be used to require the user to enter a word or solve a simple math problem to ensure the user is, in fact, a person.Any Web application should enforce the use of strong passwords. At a minimum, requiring users to choose passwords of eight letters or more with some complexity (letters and numbers, or requiring one special character) is an excellent defense against brute force attacks. The first is to implement an account lockout policy. For example, after three failed login attempts, the account is locked out until an administrator unlocks it. We should use a challenge-response test to prevent automated submissions of the login page. Tools such as the free reCAPTCHA can be used to require the user to enter a word or solve a simple math problem to ensure the user is, in fact, a person. Any Web application should enforce the use of strong passwords. At a minimum, requiring users to choose passwords of eight letters or more with some complexity (letters and numbers, or requiring one special character) is an excellent defense against brute force attacks. Sourceshttp://searchsecurity.techtarget.com/definition/brute-force-crackinghttps://en.wikipedia.org/wiki/Brute-force_attackhttps://hackertarget.com/brute-forcing-passwords-with-ncrack-hydra-and-medusa/https://sourceforge.net/projects/websecuritydojo/ This article is contributed by Akash Sharan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. secure-coding Advanced Computer Subject GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Copying Files to and from Docker Containers Fuzzy Logic | Introduction Basics of API Testing Using Postman Principal Component Analysis with Python How to create a REST API using Java Spring Boot Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Socket Programming in C/C++ DSA Sheet by Love Babbar GET and POST requests using Python Must Do Coding Questions for Product Based Companies
[ { "code": null, "e": 24350, "s": 24322, "text": "\n23 May, 2017" }, { "code": null, "e": 24744, "s": 24350, "text": "Brute force attacks work by calculating every possible combination that could make up a password and testing it to see if it is the correct password. As the password’s length increases, the amount of time, on average, to find the correct password increases exponentially. This means short passwords can usually be discovered quite quickly, but longer passwords may take decades [Source : Wiki]" }, { "code": null, "e": 24987, "s": 24744, "text": "It may be feasible in some situations as computer hardwares are getting faster and faster. A simple brute-force attack would start with one-digit passwords, then two-digit passwords and so on, trying all possible combinations until one works." }, { "code": null, "e": 25205, "s": 24987, "text": "A better idea is “dictionary attack” that tries words in a dictionary — or a list of common passwords — instead of all possible passwords. This can be very effective, as many people use such weak and common passwords." }, { "code": null, "e": 25270, "s": 25205, "text": "We can use automated tool for Brute forcing web-based login form" }, { "code": null, "e": 25569, "s": 25270, "text": "Using Hydra to dictionary-attack web-based login formsHydra is an online password cracking for dictionary-attacks. It tries lists of user-names and passwords until a successful login is found. It is multi-threaded and can try username/password combinations at a rate of thousands per minute [Source" }, { "code": null, "e": 25692, "s": 25569, "text": "Hydra can be used to attack many different services including IMAP, SMB, HTTP, VNC, MS-SQL MySQL, SMTP, SSH, and many more" }, { "code": null, "e": 25842, "s": 25692, "text": "This tool should not be used to attack websites or services where you do not have permission to do so. Use this for legitimate testing purposes only." }, { "code": null, "e": 26055, "s": 25842, "text": "An example attackThe Web Security Dojo has various vulnerable applications that you can use to test these techniques. So looking at an example the w3af testing framework has a test login at the following location" }, { "code": null, "e": 26103, "s": 26055, "text": "http://192.168.1.69/w3af/bruteforce/form_login/" }, { "code": null, "e": 26145, "s": 26103, "text": "The important parts of the HTML form are:" }, { "code": "<form name=\"input\" action=\"dataReceptor.php\" method=\"post\">Username:<input type=\"text\" name=\"user\"> Password:<input type=\"password\" name=\"pass\">", "e": 26291, "s": 26145, "text": null }, { "code": null, "e": 26356, "s": 26291, "text": "If we put in one wrong username and password combination we get:" }, { "code": null, "e": 26559, "s": 26356, "text": "Bad login, stop bruteforcing me!Bad u/p combination for user: aSo, now we have the information we need to attack this login form, we can use this info to construct a Hydra brute-force attack as follows:" }, { "code": null, "e": 26742, "s": 26559, "text": "hydra 192.168.1.69 http-form-post \"/w3af/bruteforce/form_login/dataReceptor.php:user=^USER^&pass=^PASS^:Bad login\" -L users.txt -P pass.txt -t 10 -w 30 -o hydra-http-post-attack.txt\n" }, { "code": null, "e": 26762, "s": 26742, "text": "If we break this up" }, { "code": null, "e": 27062, "s": 26762, "text": "Host = 192.168.1.69\nMethod = http-form-post\nURL = /w3af/bruteforce/form_login/dataReceptor.php\nForm parameters = user=^USER^&pass=^PASS^\nFailure response = Bad login\nUsers file = users.txt\nPassword file = pass.txt\nThreads = -t 10\nWait for timeout = -w 30\nOutput file = -o hydra-http-post-attack.txt\n" }, { "code": null, "e": 27236, "s": 27062, "text": "Hydra basically iterates through all the username/password combinations, until it gets a response that does not contain the text “Bad login”. When we run this attack we get:" }, { "code": null, "e": 27997, "s": 27236, "text": "Hydra basically iterates through all the username/password combinations, until it gets a response that does not contain the text \"Bad login\". When we run this attack we get:\n\n\n\nHydra v6.5 (c) 2011 by van Hauser / THC and David Maciejak - use allowed only for legal purposes.Hydra (http://www.thc.org/thc-hydra) starting at 2011-08-22 13:11:03\n[DATA] 5 tasks, 1 servers, 5 login tries (l:5/p:1), ~1 tries per task\n[DATA] attacking service http-post-form on port 80\n[STATUS] attack finished for 192.168.1.69 (waiting for children to finish)\n[80][www-form] host: 192.168.1.69 login: admin password: 1234\nHydra (http://www.thc.org/thc-hydra) finished at 2011-08-22 13:11:07\n\nAs you can see, this was successful and found the user \"admin\" with password \"1234\".\n" }, { "code": null, "e": 28008, "s": 27997, "text": "Prevention" }, { "code": null, "e": 28685, "s": 28008, "text": "The first is to implement an account lockout policy. For example, after three failed login attempts, the account is locked out until an administrator unlocks it.We should use a challenge-response test to prevent automated submissions of the login page. Tools such as the free reCAPTCHA can be used to require the user to enter a word or solve a simple math problem to ensure the user is, in fact, a person.Any Web application should enforce the use of strong passwords. At a minimum, requiring users to choose passwords of eight letters or more with some complexity (letters and numbers, or requiring one special character) is an excellent defense against brute force attacks." }, { "code": null, "e": 28847, "s": 28685, "text": "The first is to implement an account lockout policy. For example, after three failed login attempts, the account is locked out until an administrator unlocks it." }, { "code": null, "e": 29093, "s": 28847, "text": "We should use a challenge-response test to prevent automated submissions of the login page. Tools such as the free reCAPTCHA can be used to require the user to enter a word or solve a simple math problem to ensure the user is, in fact, a person." }, { "code": null, "e": 29364, "s": 29093, "text": "Any Web application should enforce the use of strong passwords. At a minimum, requiring users to choose passwords of eight letters or more with some complexity (letters and numbers, or requiring one special character) is an excellent defense against brute force attacks." }, { "code": null, "e": 29615, "s": 29364, "text": "Sourceshttp://searchsecurity.techtarget.com/definition/brute-force-crackinghttps://en.wikipedia.org/wiki/Brute-force_attackhttps://hackertarget.com/brute-forcing-passwords-with-ncrack-hydra-and-medusa/https://sourceforge.net/projects/websecuritydojo/" }, { "code": null, "e": 29915, "s": 29615, "text": "This article is contributed by Akash Sharan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 30040, "s": 29915, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 30054, "s": 30040, "text": "secure-coding" }, { "code": null, "e": 30080, "s": 30054, "text": "Advanced Computer Subject" }, { "code": null, "e": 30086, "s": 30080, "text": "GBlog" }, { "code": null, "e": 30184, "s": 30086, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30228, "s": 30184, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 30255, "s": 30228, "text": "Fuzzy Logic | Introduction" }, { "code": null, "e": 30291, "s": 30255, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 30332, "s": 30291, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 30380, "s": 30332, "text": "How to create a REST API using Java Spring Boot" }, { "code": null, "e": 30454, "s": 30380, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 30482, "s": 30454, "text": "Socket Programming in C/C++" }, { "code": null, "e": 30507, "s": 30482, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 30542, "s": 30507, "text": "GET and POST requests using Python" } ]
java.util.regex.Matcher.group() Method
The java.time.Matcher.group(int group) method returns the input subsequence captured by the given group during the previous match operation. Following is the declaration for java.time.Matcher.group(int group) method. public String group(int group) group − The index of a capturing group in this matcher's pattern. group − The index of a capturing group in this matcher's pattern. The (possibly empty) subsequence captured by the group during the previous match, or null if the group failed to match part of the input. IllegalStateException − If no match has yet been attempted, or if the previous match operation failed. IllegalStateException − If no match has yet been attempted, or if the previous match operation failed. IndexOutOfBoundsException − If there is no capturing group in the pattern with the given index. IndexOutOfBoundsException − If there is no capturing group in the pattern with the given index. The following example shows the usage of java.time.Matcher.group(int group) method. package com.tutorialspoint; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatcherDemo { private static String REGEX = "(a*b)(foo)"; private static String INPUT = "aabfooaabfooabfoob"; private static String REPLACE = "-"; public static void main(String[] args) { Pattern pattern = Pattern.compile(REGEX); // get a matcher object Matcher matcher = pattern.matcher(INPUT); if(matcher.find()) { //Prints the offset after the last character matched. System.out.println("Second Capturing Group : "+matcher.group(1)); } } } Let us compile and run the above program, this will produce the following result − Second Capturing Group : aab Print Add Notes Bookmark this page
[ { "code": null, "e": 2265, "s": 2124, "text": "The java.time.Matcher.group(int group) method returns the input subsequence captured by the given group during the previous match operation." }, { "code": null, "e": 2341, "s": 2265, "text": "Following is the declaration for java.time.Matcher.group(int group) method." }, { "code": null, "e": 2373, "s": 2341, "text": "public String group(int group)\n" }, { "code": null, "e": 2439, "s": 2373, "text": "group − The index of a capturing group in this matcher's pattern." }, { "code": null, "e": 2505, "s": 2439, "text": "group − The index of a capturing group in this matcher's pattern." }, { "code": null, "e": 2643, "s": 2505, "text": "The (possibly empty) subsequence captured by the group during the previous match, or null if the group failed to match part of the input." }, { "code": null, "e": 2746, "s": 2643, "text": "IllegalStateException − If no match has yet been attempted, or if the previous match operation failed." }, { "code": null, "e": 2849, "s": 2746, "text": "IllegalStateException − If no match has yet been attempted, or if the previous match operation failed." }, { "code": null, "e": 2945, "s": 2849, "text": "IndexOutOfBoundsException − If there is no capturing group in the pattern with the given index." }, { "code": null, "e": 3041, "s": 2945, "text": "IndexOutOfBoundsException − If there is no capturing group in the pattern with the given index." }, { "code": null, "e": 3125, "s": 3041, "text": "The following example shows the usage of java.time.Matcher.group(int group) method." }, { "code": null, "e": 3762, "s": 3125, "text": "package com.tutorialspoint;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class MatcherDemo {\n private static String REGEX = \"(a*b)(foo)\";\n private static String INPUT = \"aabfooaabfooabfoob\";\n private static String REPLACE = \"-\";\n \n public static void main(String[] args) {\n Pattern pattern = Pattern.compile(REGEX);\n \n // get a matcher object\n Matcher matcher = pattern.matcher(INPUT);\n \n if(matcher.find()) {\n //Prints the offset after the last character matched.\n System.out.println(\"Second Capturing Group : \"+matcher.group(1));\n } \n }\n}" }, { "code": null, "e": 3845, "s": 3762, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3875, "s": 3845, "text": "Second Capturing Group : aab\n" }, { "code": null, "e": 3882, "s": 3875, "text": " Print" }, { "code": null, "e": 3893, "s": 3882, "text": " Add Notes" } ]
How to create editText accepts Alphabets only in Android?
This example demonstrates how do I create edittext accepts alphabets only 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"?> <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" tools:context=".MainActivity"> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:hint="Enter text here" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.InputFilter; import android.text.Spanned; import android.widget.EditText; public class MainActivity extends AppCompatActivity { EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = findViewById(R.id.editText); editText.setFilters(new InputFilter[] new InputFilter() { @Override public CharSequence filter(CharSequence charSequence, int start, int end, Spanned dest, int etStart, int etEnd) { if (charSequence.equals("")) { return charSequence; } if (charSequence.toString().matches("[a-zA-Z ]+")) { return charSequence; } return ""; } } }); } 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.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from 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": 1148, "s": 1062, "text": "This example demonstrates how do I create edittext accepts alphabets only in android." }, { "code": null, "e": 1277, "s": 1148, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1342, "s": 1277, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1851, "s": 1342, "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 tools:context=\".MainActivity\">\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 text here\" />\n</RelativeLayout>" }, { "code": null, "e": 1908, "s": 1851, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2830, "s": 1908, "text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.text.InputFilter;\nimport android.text.Spanned;\nimport android.widget.EditText;\npublic class MainActivity extends AppCompatActivity {\n EditText editText;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n editText = findViewById(R.id.editText);\n editText.setFilters(new InputFilter[] new InputFilter() {\n @Override\n public CharSequence filter(CharSequence charSequence, int start, int end,\n Spanned dest, int etStart, int etEnd) {\n if (charSequence.equals(\"\")) {\n return charSequence;\n }\n if (charSequence.toString().matches(\"[a-zA-Z ]+\")) {\n return charSequence;\n }\n return \"\";\n }\n }\n });\n}" }, { "code": null, "e": 2885, "s": 2830, "text": "Step 4 - Add the following code to androidManifest.xml" }, { "code": null, "e": 3558, "s": 2885, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3905, "s": 3558, "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": 3946, "s": 3905, "text": "Click here to download the project code." } ]
Given a binary tree, print out all of its root-to-leaf paths one per line. - GeeksforGeeks
05 Jul, 2021 Given the roots of a tree. print out all of its root-to-leaf paths one per line.. Algorithm: initialize: pathlen = 0, path[1000] /*1000 is some max limit for paths, it can change*/ /*printPathsRecur traverses nodes of tree in preorder */ printPathsRecur(tree, path[], pathlen) 1) If node is not NULL then a) push data to path array: path[pathlen] = node->data. b) increment pathlen pathlen++ 2) If node is a leaf node then print the path array. 3) Else a) Call printPathsRecur for left subtree printPathsRecur(node->left, path, pathLen) b) Call printPathsRecur for right subtree. printPathsRecur(node->right, path, pathLen) Example: Output for the above example will be 1 2 4 1 2 5 1 3 Implementation: C++ C Java Python3 C# Javascript /* C++ program to print all of itsroot-to-leaf paths for a tree*/#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */class node{ public: int data; node* left; node* right;}; void printArray(int [], int);void printPathsRecur(node*, int [], int);node* newNode(int );void printPaths(node*); /* Given a binary tree, print outall of its root-to-leaf paths,one per line. Uses a recursive helperto do the work.*/void printPaths(node* node){ int path[1000]; printPathsRecur(node, path, 0);} /* Recursive helper function -- givena node, and an array containing thepath from the root node up to but notincluding this node, print out all theroot-leaf paths. */void printPathsRecur(node* node, int path[], int pathLen){ if (node == NULL) return; /* append this node to the path array */ path[pathLen] = node->data; pathLen++; /* it's a leaf, so print the path that led to here */ if (node->left == NULL && node->right == NULL) { printArray(path, pathLen); } else { /* otherwise try both subtrees */ printPathsRecur(node->left, path, pathLen); printPathsRecur(node->right, path, pathLen); }} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return(Node);} /* Utility that prints out an array on a line */void printArray(int ints[], int len){ int i; for (i = 0; i < len; i++) { cout << ints[i] << " "; } cout << endl;} /* Driver code */int main(){ node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); /* Print all root-to-leaf paths of the input tree */ printPaths(root); return 0;} // This code is contributed by rathbhupendra /*program to print all of its root-to-leaf paths for a tree*/#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; void printArray(int [], int);void printPathsRecur(struct node*, int [], int);struct node* newNode(int );void printPaths(struct node*); /* Given a binary tree, print out all of its root-to-leaf paths, one per line. Uses a recursive helper to do the work.*/ void printPaths(struct node* node){ int path[1000]; printPathsRecur(node, path, 0);} /* Recursive helper function -- given a node, and an array containing the path from the root node up to but not including this node, print out all the root-leaf paths. */void printPathsRecur(struct node* node, int path[], int pathLen){ if (node==NULL) return; /* append this node to the path array */ path[pathLen] = node->data; pathLen++; /* it's a leaf, so print the path that led to here */ if (node->left==NULL && node->right==NULL) { printArray(path, pathLen); } else { /* otherwise try both subtrees */ printPathsRecur(node->left, path, pathLen); printPathsRecur(node->right, path, pathLen); }} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Utility that prints out an array on a line */void printArray(int ints[], int len){ int i; for (i=0; i<len; i++) { printf("%d ", ints[i]); } printf("\n");} /* Driver program to test mirror() */int main(){ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); /* Print all root-to-leaf paths of the input tree */ printPaths(root); getchar(); return 0;} // Java program to print all root to leaf paths /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; /* Given a binary tree, print out all of its root-to-leaf paths, one per line. Uses a recursive helper to do the work.*/ void printPaths(Node node) { int path[] = new int[1000]; printPathsRecur(node, path, 0); } /* Recursive helper function -- given a node, and an array containing the path from the root node up to but not including this node, print out all the root-leaf paths. */ void printPathsRecur(Node node, int path[], int pathLen) { if (node == null) return; /* append this node to the path array */ path[pathLen] = node.data; pathLen++; /* it's a leaf, so print the path that led to here */ if (node.left == null && node.right == null) printArray(path, pathLen); else { /* otherwise try both subtrees */ printPathsRecur(node.left, path, pathLen); printPathsRecur(node.right, path, pathLen); } } /* Utility that prints out an array on a line */ void printArray(int ints[], int len) { int i; for (i = 0; i < len; i++) System.out.print(ints[i] + " "); System.out.println(""); } /* Driver program to test all above functions */ public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); /* Print all root-to-leaf paths of the input tree */ tree.printPaths(tree.root); }} # Python3 program to print all of its# root-to-leaf paths for a treeclass Node: # A binary tree node has data, # pointer to left child and a # pointer to right child def __init__(self, data): self.data = data self.right = None self.left = None def printRoute(stack, root): if root == None: return # append this node to the path array stack.append(root.data) if(root.left == None and root.right == None): # print out all of its # root - to - leaf print(' '.join([str(i) for i in stack])) # otherwise try both subtrees printRoute(stack, root.left) printRoute(stack, root.right) stack.pop() # Driver Coderoot = Node(1);root.left = Node(2);root.right = Node(3);root.left.left = Node(4);root.left.right = Node(5);printRoute([], root) # This code is contributed# by Farheen Nilofer using System; // C# program to print all root to leaf paths /* A binary tree node has data, pointer to left child and a pointer to right child */public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ public Node root; /* Given a binary tree, print out all of its root-to-leaf paths, one per line. Uses a recursive helper to do the work.*/ public virtual void printPaths(Node node) { int[] path = new int[1000]; printPathsRecur(node, path, 0); } /* Recursive helper function -- given a node, and an array containing the path from the root node up to but not including this node, print out all the root-leaf paths. */ public virtual void printPathsRecur(Node node, int[] path, int pathLen) { if (node == null) { return; } /* append this node to the path array */ path[pathLen] = node.data; pathLen++; /* it's a leaf, so print the path that led to here */ if (node.left == null && node.right == null) { printArray(path, pathLen); } else { /* otherwise try both subtrees */ printPathsRecur(node.left, path, pathLen); printPathsRecur(node.right, path, pathLen); } } /* Utility that prints out an array on a line */ public virtual void printArray(int[] ints, int len) { int i; for (i = 0; i < len; i++) { Console.Write(ints[i] + " "); } Console.WriteLine(""); } /* Driver program to test all above functions */ public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); /* Print all root-to-leaf paths of the input tree */ tree.printPaths(tree.root); }} // This code is contributed by Shrikant13 <script> // JavaScript program to print all root to leaf paths class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let root; /* Given a binary tree, print out all of its root-to-leaf paths, one per line. Uses a recursive helper to do the work.*/ function printPaths(node) { let path = new Array(1000); printPathsRecur(node, path, 0); } /* Recursive helper function -- given a node, and an array containing the path from the root node up to but not including this node, print out all the root-leaf paths. */ function printPathsRecur(node, path, pathLen) { if (node == null) return; /* append this node to the path array */ path[pathLen] = node.data; pathLen++; /* it's a leaf, so print the path that led to here */ if (node.left == null && node.right == null) printArray(path, pathLen); else { /* otherwise try both subtrees */ printPathsRecur(node.left, path, pathLen); printPathsRecur(node.right, path, pathLen); } } /* Utility that prints out an array on a line */ function printArray(ints, len) { let i; for (i = 0; i < len; i++) document.write(ints[i] + " "); document.write("</br>"); } root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); /* Print all root-to-leaf paths of the input tree */ printPaths(root); </script> Output: 1 2 4 1 2 5 1 3 YouTubeGeeksforGeeks507K subscribersPrint out all of root-to-leaf paths of a Binary Tree one per line | 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 / 5:14•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=JPspskkZn9E" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> References: http://cslibrary.stanford.edu/110/BinaryTrees.html Farheen Nilofer shrikanth13 rathbhupendra rameshtravel07 Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Tree Traversals (Inorder, Preorder and Postorder) AVL Tree | Set 1 (Insertion) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal Binary Tree | Set 3 (Types of Binary Tree) Inorder Tree Traversal without Recursion Binary Tree | Set 2 (Properties) Write a Program to Find the Maximum Depth or Height of a Tree Decision Tree A program to check if a binary tree is BST or not
[ { "code": null, "e": 37091, "s": 37063, "text": "\n05 Jul, 2021" }, { "code": null, "e": 37184, "s": 37091, "text": "Given the roots of a tree. print out all of its root-to-leaf paths one per line.. Algorithm:" }, { "code": null, "e": 37828, "s": 37184, "text": "initialize: pathlen = 0, path[1000] \n/*1000 is some max limit for paths, it can change*/\n\n/*printPathsRecur traverses nodes of tree in preorder */\nprintPathsRecur(tree, path[], pathlen)\n 1) If node is not NULL then \n a) push data to path array: \n path[pathlen] = node->data.\n b) increment pathlen \n pathlen++\n 2) If node is a leaf node then print the path array.\n 3) Else\n a) Call printPathsRecur for left subtree\n printPathsRecur(node->left, path, pathLen)\n b) Call printPathsRecur for right subtree.\n printPathsRecur(node->right, path, pathLen)" }, { "code": null, "e": 37839, "s": 37828, "text": "Example: " }, { "code": null, "e": 37878, "s": 37839, "text": "Output for the above example will be " }, { "code": null, "e": 37901, "s": 37878, "text": " 1 2 4\n 1 2 5\n 1 3 " }, { "code": null, "e": 37921, "s": 37903, "text": "Implementation: " }, { "code": null, "e": 37925, "s": 37921, "text": "C++" }, { "code": null, "e": 37927, "s": 37925, "text": "C" }, { "code": null, "e": 37932, "s": 37927, "text": "Java" }, { "code": null, "e": 37940, "s": 37932, "text": "Python3" }, { "code": null, "e": 37943, "s": 37940, "text": "C#" }, { "code": null, "e": 37954, "s": 37943, "text": "Javascript" }, { "code": "/* C++ program to print all of itsroot-to-leaf paths for a tree*/#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */class node{ public: int data; node* left; node* right;}; void printArray(int [], int);void printPathsRecur(node*, int [], int);node* newNode(int );void printPaths(node*); /* Given a binary tree, print outall of its root-to-leaf paths,one per line. Uses a recursive helperto do the work.*/void printPaths(node* node){ int path[1000]; printPathsRecur(node, path, 0);} /* Recursive helper function -- givena node, and an array containing thepath from the root node up to but notincluding this node, print out all theroot-leaf paths. */void printPathsRecur(node* node, int path[], int pathLen){ if (node == NULL) return; /* append this node to the path array */ path[pathLen] = node->data; pathLen++; /* it's a leaf, so print the path that led to here */ if (node->left == NULL && node->right == NULL) { printArray(path, pathLen); } else { /* otherwise try both subtrees */ printPathsRecur(node->left, path, pathLen); printPathsRecur(node->right, path, pathLen); }} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return(Node);} /* Utility that prints out an array on a line */void printArray(int ints[], int len){ int i; for (i = 0; i < len; i++) { cout << ints[i] << \" \"; } cout << endl;} /* Driver code */int main(){ node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); /* Print all root-to-leaf paths of the input tree */ printPaths(root); return 0;} // This code is contributed by rathbhupendra", "e": 39949, "s": 37954, "text": null }, { "code": "/*program to print all of its root-to-leaf paths for a tree*/#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; void printArray(int [], int);void printPathsRecur(struct node*, int [], int);struct node* newNode(int );void printPaths(struct node*); /* Given a binary tree, print out all of its root-to-leaf paths, one per line. Uses a recursive helper to do the work.*/ void printPaths(struct node* node){ int path[1000]; printPathsRecur(node, path, 0);} /* Recursive helper function -- given a node, and an array containing the path from the root node up to but not including this node, print out all the root-leaf paths. */void printPathsRecur(struct node* node, int path[], int pathLen){ if (node==NULL) return; /* append this node to the path array */ path[pathLen] = node->data; pathLen++; /* it's a leaf, so print the path that led to here */ if (node->left==NULL && node->right==NULL) { printArray(path, pathLen); } else { /* otherwise try both subtrees */ printPathsRecur(node->left, path, pathLen); printPathsRecur(node->right, path, pathLen); }} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Utility that prints out an array on a line */void printArray(int ints[], int len){ int i; for (i=0; i<len; i++) { printf(\"%d \", ints[i]); } printf(\"\\n\");} /* Driver program to test mirror() */int main(){ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); /* Print all root-to-leaf paths of the input tree */ printPaths(root); getchar(); return 0;}", "e": 41956, "s": 39949, "text": null }, { "code": "// Java program to print all root to leaf paths /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; /* Given a binary tree, print out all of its root-to-leaf paths, one per line. Uses a recursive helper to do the work.*/ void printPaths(Node node) { int path[] = new int[1000]; printPathsRecur(node, path, 0); } /* Recursive helper function -- given a node, and an array containing the path from the root node up to but not including this node, print out all the root-leaf paths. */ void printPathsRecur(Node node, int path[], int pathLen) { if (node == null) return; /* append this node to the path array */ path[pathLen] = node.data; pathLen++; /* it's a leaf, so print the path that led to here */ if (node.left == null && node.right == null) printArray(path, pathLen); else { /* otherwise try both subtrees */ printPathsRecur(node.left, path, pathLen); printPathsRecur(node.right, path, pathLen); } } /* Utility that prints out an array on a line */ void printArray(int ints[], int len) { int i; for (i = 0; i < len; i++) System.out.print(ints[i] + \" \"); System.out.println(\"\"); } /* Driver program to test all above functions */ public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); /* Print all root-to-leaf paths of the input tree */ tree.printPaths(tree.root); }}", "e": 43915, "s": 41956, "text": null }, { "code": "# Python3 program to print all of its# root-to-leaf paths for a treeclass Node: # A binary tree node has data, # pointer to left child and a # pointer to right child def __init__(self, data): self.data = data self.right = None self.left = None def printRoute(stack, root): if root == None: return # append this node to the path array stack.append(root.data) if(root.left == None and root.right == None): # print out all of its # root - to - leaf print(' '.join([str(i) for i in stack])) # otherwise try both subtrees printRoute(stack, root.left) printRoute(stack, root.right) stack.pop() # Driver Coderoot = Node(1);root.left = Node(2);root.right = Node(3);root.left.left = Node(4);root.left.right = Node(5);printRoute([], root) # This code is contributed# by Farheen Nilofer", "e": 44808, "s": 43915, "text": null }, { "code": "using System; // C# program to print all root to leaf paths /* A binary tree node has data, pointer to left child and a pointer to right child */public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ public Node root; /* Given a binary tree, print out all of its root-to-leaf paths, one per line. Uses a recursive helper to do the work.*/ public virtual void printPaths(Node node) { int[] path = new int[1000]; printPathsRecur(node, path, 0); } /* Recursive helper function -- given a node, and an array containing the path from the root node up to but not including this node, print out all the root-leaf paths. */ public virtual void printPathsRecur(Node node, int[] path, int pathLen) { if (node == null) { return; } /* append this node to the path array */ path[pathLen] = node.data; pathLen++; /* it's a leaf, so print the path that led to here */ if (node.left == null && node.right == null) { printArray(path, pathLen); } else { /* otherwise try both subtrees */ printPathsRecur(node.left, path, pathLen); printPathsRecur(node.right, path, pathLen); } } /* Utility that prints out an array on a line */ public virtual void printArray(int[] ints, int len) { int i; for (i = 0; i < len; i++) { Console.Write(ints[i] + \" \"); } Console.WriteLine(\"\"); } /* Driver program to test all above functions */ public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); /* Print all root-to-leaf paths of the input tree */ tree.printPaths(tree.root); }} // This code is contributed by Shrikant13", "e": 46938, "s": 44808, "text": null }, { "code": "<script> // JavaScript program to print all root to leaf paths class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let root; /* Given a binary tree, print out all of its root-to-leaf paths, one per line. Uses a recursive helper to do the work.*/ function printPaths(node) { let path = new Array(1000); printPathsRecur(node, path, 0); } /* Recursive helper function -- given a node, and an array containing the path from the root node up to but not including this node, print out all the root-leaf paths. */ function printPathsRecur(node, path, pathLen) { if (node == null) return; /* append this node to the path array */ path[pathLen] = node.data; pathLen++; /* it's a leaf, so print the path that led to here */ if (node.left == null && node.right == null) printArray(path, pathLen); else { /* otherwise try both subtrees */ printPathsRecur(node.left, path, pathLen); printPathsRecur(node.right, path, pathLen); } } /* Utility that prints out an array on a line */ function printArray(ints, len) { let i; for (i = 0; i < len; i++) document.write(ints[i] + \" \"); document.write(\"</br>\"); } root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); /* Print all root-to-leaf paths of the input tree */ printPaths(root); </script>", "e": 48637, "s": 46938, "text": null }, { "code": null, "e": 48647, "s": 48637, "text": "Output: " }, { "code": null, "e": 48663, "s": 48647, "text": "1 2 4\n1 2 5\n1 3" }, { "code": null, "e": 49529, "s": 48665, "text": "YouTubeGeeksforGeeks507K subscribersPrint out all of root-to-leaf paths of a Binary Tree one per line | 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 / 5:14•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=JPspskkZn9E\" 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": 49593, "s": 49529, "text": "References: http://cslibrary.stanford.edu/110/BinaryTrees.html " }, { "code": null, "e": 49609, "s": 49593, "text": "Farheen Nilofer" }, { "code": null, "e": 49621, "s": 49609, "text": "shrikanth13" }, { "code": null, "e": 49635, "s": 49621, "text": "rathbhupendra" }, { "code": null, "e": 49650, "s": 49635, "text": "rameshtravel07" }, { "code": null, "e": 49655, "s": 49650, "text": "Tree" }, { "code": null, "e": 49660, "s": 49655, "text": "Tree" }, { "code": null, "e": 49758, "s": 49660, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49808, "s": 49758, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 49837, "s": 49808, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 49872, "s": 49837, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 49906, "s": 49872, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 49949, "s": 49906, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 49990, "s": 49949, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 50023, "s": 49990, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 50085, "s": 50023, "text": "Write a Program to Find the Maximum Depth or Height of a Tree" }, { "code": null, "e": 50099, "s": 50085, "text": "Decision Tree" } ]
Python | Insert list in another list - GeeksforGeeks
26 Jan, 2019 The problem of inserting a number at any index is a quite common one. But sometimes we require to insert the whole list into another list. These kinds of problems occur in Machine Learning while playing with data. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using insert() + loopIn this method, we insert one element by 1 at a time using the insert function. This way we add all the list elements at the specified index in other list. # Python3 code to demonstrate # to insert one list in another# using insert() + loop # initializing lists test_list = [4, 5, 6, 3, 9]insert_list = [2, 3] # initializing positionpos = 2 # printing original listprint ("The original list is : " + str(test_list)) # printing insert list print ("The list to be inserted is : " + str(insert_list)) # using insert() + loop# to insert one list in anotherfor i in range(len(insert_list)): test_list.insert(i + pos, insert_list[i]) # printing result print ("The list after insertion is : " + str(test_list)) Output : The original list is : [4, 5, 6, 3, 9] The list to be inserted is : [2, 3] The list after insertion is : [4, 5, 2, 3, 6, 3, 9] Method #2 : Using list slicingThis is the most pythonic and elegant way to perform this particular task. In this method, we just slice the list where we need to add the element and assign the list to be inserted. # Python3 code to demonstrate # to insert one list in another# using list slicing # initializing lists test_list = [4, 5, 6, 3, 9]insert_list = [2, 3] # initializing positionpos = 2 # printing original listprint ("The original list is : " + str(test_list)) # printing insert list print ("The list to be inserted is : " + str(insert_list)) # using list slicing# to insert one list in anothertest_list[pos:pos] = insert_list # printing result print ("The list after insertion is : " + str(test_list)) Output : The original list is : [4, 5, 6, 3, 9] The list to be inserted is : [2, 3] The list after insertion is : [4, 5, 2, 3, 6, 3, 9] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? 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 Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25672, "s": 25644, "text": "\n26 Jan, 2019" }, { "code": null, "e": 25950, "s": 25672, "text": "The problem of inserting a number at any index is a quite common one. But sometimes we require to insert the whole list into another list. These kinds of problems occur in Machine Learning while playing with data. Let’s discuss certain ways in which this problem can be solved." }, { "code": null, "e": 26139, "s": 25950, "text": "Method #1 : Using insert() + loopIn this method, we insert one element by 1 at a time using the insert function. This way we add all the list elements at the specified index in other list." }, { "code": "# Python3 code to demonstrate # to insert one list in another# using insert() + loop # initializing lists test_list = [4, 5, 6, 3, 9]insert_list = [2, 3] # initializing positionpos = 2 # printing original listprint (\"The original list is : \" + str(test_list)) # printing insert list print (\"The list to be inserted is : \" + str(insert_list)) # using insert() + loop# to insert one list in anotherfor i in range(len(insert_list)): test_list.insert(i + pos, insert_list[i]) # printing result print (\"The list after insertion is : \" + str(test_list))", "e": 26697, "s": 26139, "text": null }, { "code": null, "e": 26706, "s": 26697, "text": "Output :" }, { "code": null, "e": 26834, "s": 26706, "text": "The original list is : [4, 5, 6, 3, 9]\nThe list to be inserted is : [2, 3]\nThe list after insertion is : [4, 5, 2, 3, 6, 3, 9]\n" }, { "code": null, "e": 27048, "s": 26834, "text": " Method #2 : Using list slicingThis is the most pythonic and elegant way to perform this particular task. In this method, we just slice the list where we need to add the element and assign the list to be inserted." }, { "code": "# Python3 code to demonstrate # to insert one list in another# using list slicing # initializing lists test_list = [4, 5, 6, 3, 9]insert_list = [2, 3] # initializing positionpos = 2 # printing original listprint (\"The original list is : \" + str(test_list)) # printing insert list print (\"The list to be inserted is : \" + str(insert_list)) # using list slicing# to insert one list in anothertest_list[pos:pos] = insert_list # printing result print (\"The list after insertion is : \" + str(test_list))", "e": 27554, "s": 27048, "text": null }, { "code": null, "e": 27563, "s": 27554, "text": "Output :" }, { "code": null, "e": 27691, "s": 27563, "text": "The original list is : [4, 5, 6, 3, 9]\nThe list to be inserted is : [2, 3]\nThe list after insertion is : [4, 5, 2, 3, 6, 3, 9]\n" }, { "code": null, "e": 27712, "s": 27691, "text": "Python list-programs" }, { "code": null, "e": 27719, "s": 27712, "text": "Python" }, { "code": null, "e": 27735, "s": 27719, "text": "Python Programs" }, { "code": null, "e": 27833, "s": 27735, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27865, "s": 27833, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27907, "s": 27865, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27949, "s": 27907, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28005, "s": 27949, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28032, "s": 28005, "text": "Python Classes and Objects" }, { "code": null, "e": 28054, "s": 28032, "text": "Defaultdict in Python" }, { "code": null, "e": 28093, "s": 28054, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28139, "s": 28093, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28177, "s": 28139, "text": "Python | Convert a list to dictionary" } ]
Lucene - Indexing Process
Indexing process is one of the core functionality provided by Lucene. Following diagram illustrates the indexing process and use of classes. IndexWriter is the most important and core component of the indexing process. We add Document(s) containing Field(s) to IndexWriter which analyzes the Document(s) using the Analyzer and then creates/open/edit indexes as required and store/update them in a Directory. IndexWriter is used to update or create indexes. It is not used to read indexes. Now we'll show you a step by step process to get a kick start in understanding of indexing process using a basic example. Create a method to get a lucene document from a text file. Create a method to get a lucene document from a text file. Create various types of fields which are key value pairs containing keys as names and values as contents to be indexed. Create various types of fields which are key value pairs containing keys as names and values as contents to be indexed. Set field to be analyzed or not. In our case, only contents is to be analyzed as it can contain data such as a, am, are, an etc. which are not required in search operations. Set field to be analyzed or not. In our case, only contents is to be analyzed as it can contain data such as a, am, are, an etc. which are not required in search operations. Add the newly created fields to the document object and return it to the caller method. Add the newly created fields to the document object and return it to the caller method. private Document getDocument(File file) throws IOException { Document document = new Document(); //index file contents Field contentField = new Field(LuceneConstants.CONTENTS, new FileReader(file)); //index file name Field fileNameField = new Field(LuceneConstants.FILE_NAME, file.getName(), Field.Store.YES,Field.Index.NOT_ANALYZED); //index file path Field filePathField = new Field(LuceneConstants.FILE_PATH, file.getCanonicalPath(), Field.Store.YES,Field.Index.NOT_ANALYZED); document.add(contentField); document.add(fileNameField); document.add(filePathField); return document; } IndexWriter class acts as a core component which creates/updates indexes during indexing process. Follow these steps to create a IndexWriter − Step 1 − Create object of IndexWriter. Step 2 − Create a Lucene directory which should point to location where indexes are to be stored. Step 3 − Initialize the IndexWriter object created with the index directory, a standard analyzer having version information and other required/optional parameters. private IndexWriter writer; public Indexer(String indexDirectoryPath) throws IOException { //this directory will contain the indexes Directory indexDirectory = FSDirectory.open(new File(indexDirectoryPath)); //create the indexer writer = new IndexWriter(indexDirectory, new StandardAnalyzer(Version.LUCENE_36),true, IndexWriter.MaxFieldLength.UNLIMITED); } The following program shows how to start an indexing process − private void indexFile(File file) throws IOException { System.out.println("Indexing "+file.getCanonicalPath()); Document document = getDocument(file); writer.addDocument(document); } To test the indexing process, we need to create a Lucene application test. Create a project with a name LuceneFirstApplication under a package com.tutorialspoint.lucene as explained in the Lucene - First Application chapter. You can also use the project created in Lucene - First Application chapter as such for this chapter to understand the indexing process. Create LuceneConstants.java,TextFileFilter.java and Indexer.java as explained in the Lucene - First Application chapter. Keep the rest of the files unchanged. Create LuceneTester.java as mentioned below. Clean and build the application to make sure the business logic is working as per the requirements. This class is used to provide various constants to be used across the sample application. package com.tutorialspoint.lucene; public class LuceneConstants { public static final String CONTENTS = "contents"; public static final String FILE_NAME = "filename"; public static final String FILE_PATH = "filepath"; public static final int MAX_SEARCH = 10; } This class is used as a .txt file filter. package com.tutorialspoint.lucene; import java.io.File; import java.io.FileFilter; public class TextFileFilter implements FileFilter { @Override public boolean accept(File pathname) { return pathname.getName().toLowerCase().endsWith(".txt"); } } This class is used to index the raw data so that we can make it searchable using the Lucene library. package com.tutorialspoint.lucene; import java.io.File; import java.io.FileFilter; import java.io.FileReader; import java.io.IOException; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; public class Indexer { private IndexWriter writer; public Indexer(String indexDirectoryPath) throws IOException { //this directory will contain the indexes Directory indexDirectory = FSDirectory.open(new File(indexDirectoryPath)); //create the indexer writer = new IndexWriter(indexDirectory, new StandardAnalyzer(Version.LUCENE_36),true, IndexWriter.MaxFieldLength.UNLIMITED); } public void close() throws CorruptIndexException, IOException { writer.close(); } private Document getDocument(File file) throws IOException { Document document = new Document(); //index file contents Field contentField = new Field(LuceneConstants.CONTENTS, new FileReader(file)); //index file name Field fileNameField = new Field(LuceneConstants.FILE_NAME, file.getName(), Field.Store.YES,Field.Index.NOT_ANALYZED); //index file path Field filePathField = new Field(LuceneConstants.FILE_PATH, file.getCanonicalPath(), Field.Store.YES,Field.Index.NOT_ANALYZED); document.add(contentField); document.add(fileNameField); document.add(filePathField); return document; } private void indexFile(File file) throws IOException { System.out.println("Indexing "+file.getCanonicalPath()); Document document = getDocument(file); writer.addDocument(document); } public int createIndex(String dataDirPath, FileFilter filter) throws IOException { //get all files in the data directory File[] files = new File(dataDirPath).listFiles(); for (File file : files) { if(!file.isDirectory() && !file.isHidden() && file.exists() && file.canRead() && filter.accept(file) ){ indexFile(file); } } return writer.numDocs(); } } This class is used to test the indexing capability of the Lucene library. package com.tutorialspoint.lucene; import java.io.IOException; public class LuceneTester { String indexDir = "E:\\Lucene\\Index"; String dataDir = "E:\\Lucene\\Data"; Indexer indexer; public static void main(String[] args) { LuceneTester tester; try { tester = new LuceneTester(); tester.createIndex(); } catch (IOException e) { e.printStackTrace(); } } private void createIndex() throws IOException { indexer = new Indexer(indexDir); int numIndexed; long startTime = System.currentTimeMillis(); numIndexed = indexer.createIndex(dataDir, new TextFileFilter()); long endTime = System.currentTimeMillis(); indexer.close(); System.out.println(numIndexed+" File indexed, time taken: " +(endTime-startTime)+" ms"); } } We have used 10 text files from record1.txt to record10.txt containing names and other details of the students and put them in the directory E:\Lucene\Data. Test Data. An index directory path should be created as E:\Lucene\Index. After running this program, you can see the list of index files created in that folder. Once you are done with the creation of the source, the raw data, the data directory and the index directory, you can proceed by compiling and running your program. To do this, keep the LuceneTester.Java file tab active and use either the Run option available in the Eclipse IDE or use Ctrl + F11 to compile and run your LuceneTester application. If your application runs successfully, it will print the following message in Eclipse IDE's console − Indexing E:\Lucene\Data\record1.txt Indexing E:\Lucene\Data\record10.txt Indexing E:\Lucene\Data\record2.txt Indexing E:\Lucene\Data\record3.txt Indexing E:\Lucene\Data\record4.txt Indexing E:\Lucene\Data\record5.txt Indexing E:\Lucene\Data\record6.txt Indexing E:\Lucene\Data\record7.txt Indexing E:\Lucene\Data\record8.txt Indexing E:\Lucene\Data\record9.txt 10 File indexed, time taken: 109 ms Once you've run the program successfully, you will have the following content in your index directory − Print Add Notes Bookmark this page
[ { "code": null, "e": 2062, "s": 1843, "text": "Indexing process is one of the core functionality provided by Lucene. Following diagram illustrates the indexing process and use of classes. IndexWriter is the most important and core component of the indexing process." }, { "code": null, "e": 2332, "s": 2062, "text": "We add Document(s) containing Field(s) to IndexWriter which analyzes the Document(s) using the Analyzer and then creates/open/edit indexes as required and store/update them in a Directory. IndexWriter is used to update or create indexes. It is not used to read indexes." }, { "code": null, "e": 2454, "s": 2332, "text": "Now we'll show you a step by step process to get a kick start in understanding of indexing process using a basic example." }, { "code": null, "e": 2513, "s": 2454, "text": "Create a method to get a lucene document from a text file." }, { "code": null, "e": 2572, "s": 2513, "text": "Create a method to get a lucene document from a text file." }, { "code": null, "e": 2692, "s": 2572, "text": "Create various types of fields which are key value pairs containing keys as names and values as contents to be indexed." }, { "code": null, "e": 2812, "s": 2692, "text": "Create various types of fields which are key value pairs containing keys as names and values as contents to be indexed." }, { "code": null, "e": 2988, "s": 2814, "text": "Set field to be analyzed or not. In our case, only contents is to be analyzed as it can contain data such as a, am, are, an etc. which are not required in search operations." }, { "code": null, "e": 3162, "s": 2988, "text": "Set field to be analyzed or not. In our case, only contents is to be analyzed as it can contain data such as a, am, are, an etc. which are not required in search operations." }, { "code": null, "e": 3252, "s": 3164, "text": "Add the newly created fields to the document object and return it to the caller method." }, { "code": null, "e": 3340, "s": 3252, "text": "Add the newly created fields to the document object and return it to the caller method." }, { "code": null, "e": 4006, "s": 3340, "text": "private Document getDocument(File file) throws IOException {\n Document document = new Document();\n \n //index file contents\n Field contentField = new Field(LuceneConstants.CONTENTS, \n new FileReader(file));\n \n //index file name\n Field fileNameField = new Field(LuceneConstants.FILE_NAME,\n file.getName(),\n Field.Store.YES,Field.Index.NOT_ANALYZED);\n \n //index file path\n Field filePathField = new Field(LuceneConstants.FILE_PATH,\n file.getCanonicalPath(),\n Field.Store.YES,Field.Index.NOT_ANALYZED);\n\n document.add(contentField);\n document.add(fileNameField);\n document.add(filePathField);\n\n return document;\n} " }, { "code": null, "e": 4149, "s": 4006, "text": "IndexWriter class acts as a core component which creates/updates indexes during indexing process. Follow these steps to create a IndexWriter −" }, { "code": null, "e": 4188, "s": 4149, "text": "Step 1 − Create object of IndexWriter." }, { "code": null, "e": 4286, "s": 4188, "text": "Step 2 − Create a Lucene directory which should point to location where indexes are to be stored." }, { "code": null, "e": 4450, "s": 4286, "text": "Step 3 − Initialize the IndexWriter object created with the index directory, a standard analyzer having version information and other required/optional parameters." }, { "code": null, "e": 4844, "s": 4450, "text": "private IndexWriter writer;\n\npublic Indexer(String indexDirectoryPath) throws IOException {\n //this directory will contain the indexes\n Directory indexDirectory = \n FSDirectory.open(new File(indexDirectoryPath));\n \n //create the indexer\n writer = new IndexWriter(indexDirectory, \n new StandardAnalyzer(Version.LUCENE_36),true,\n IndexWriter.MaxFieldLength.UNLIMITED);\n}" }, { "code": null, "e": 4907, "s": 4844, "text": "The following program shows how to start an indexing process −" }, { "code": null, "e": 5099, "s": 4907, "text": "private void indexFile(File file) throws IOException {\n System.out.println(\"Indexing \"+file.getCanonicalPath());\n Document document = getDocument(file);\n writer.addDocument(document);\n}" }, { "code": null, "e": 5174, "s": 5099, "text": "To test the indexing process, we need to create a Lucene application test." }, { "code": null, "e": 5460, "s": 5174, "text": "Create a project with a name LuceneFirstApplication under a package com.tutorialspoint.lucene as explained in the Lucene - First Application chapter. You can also use the project created in Lucene - First Application chapter as such for this chapter to understand the indexing process." }, { "code": null, "e": 5619, "s": 5460, "text": "Create LuceneConstants.java,TextFileFilter.java and Indexer.java as explained in the Lucene - First Application chapter. Keep the rest of the files unchanged." }, { "code": null, "e": 5664, "s": 5619, "text": "Create LuceneTester.java as mentioned below." }, { "code": null, "e": 5764, "s": 5664, "text": "Clean and build the application to make sure the business logic is working as per the requirements." }, { "code": null, "e": 5854, "s": 5764, "text": "This class is used to provide various constants to be used across the sample application." }, { "code": null, "e": 6128, "s": 5854, "text": "package com.tutorialspoint.lucene;\n\npublic class LuceneConstants {\n public static final String CONTENTS = \"contents\";\n public static final String FILE_NAME = \"filename\";\n public static final String FILE_PATH = \"filepath\";\n public static final int MAX_SEARCH = 10;\n}" }, { "code": null, "e": 6170, "s": 6128, "text": "This class is used as a .txt file filter." }, { "code": null, "e": 6434, "s": 6170, "text": "package com.tutorialspoint.lucene;\n\nimport java.io.File;\nimport java.io.FileFilter;\n\npublic class TextFileFilter implements FileFilter {\n\n @Override\n public boolean accept(File pathname) {\n return pathname.getName().toLowerCase().endsWith(\".txt\");\n }\n}" }, { "code": null, "e": 6535, "s": 6434, "text": "This class is used to index the raw data so that we can make it searchable using the Lucene library." }, { "code": null, "e": 9000, "s": 6535, "text": "package com.tutorialspoint.lucene;\n\nimport java.io.File;\nimport java.io.FileFilter;\nimport java.io.FileReader;\nimport java.io.IOException;\n\nimport org.apache.lucene.analysis.standard.StandardAnalyzer;\nimport org.apache.lucene.document.Document;\nimport org.apache.lucene.document.Field;\nimport org.apache.lucene.index.CorruptIndexException;\nimport org.apache.lucene.index.IndexWriter;\nimport org.apache.lucene.store.Directory;\nimport org.apache.lucene.store.FSDirectory;\nimport org.apache.lucene.util.Version;\n\npublic class Indexer {\n\n private IndexWriter writer;\n\n public Indexer(String indexDirectoryPath) throws IOException {\n //this directory will contain the indexes\n Directory indexDirectory = \n FSDirectory.open(new File(indexDirectoryPath));\n\n //create the indexer\n writer = new IndexWriter(indexDirectory, \n new StandardAnalyzer(Version.LUCENE_36),true,\n IndexWriter.MaxFieldLength.UNLIMITED);\n }\n\n public void close() throws CorruptIndexException, IOException {\n writer.close();\n }\n\n private Document getDocument(File file) throws IOException {\n Document document = new Document();\n\n //index file contents\n Field contentField = new Field(LuceneConstants.CONTENTS, \n new FileReader(file));\n \n //index file name\n Field fileNameField = new Field(LuceneConstants.FILE_NAME,\n file.getName(),\n Field.Store.YES,Field.Index.NOT_ANALYZED);\n \n //index file path\n Field filePathField = new Field(LuceneConstants.FILE_PATH,\n file.getCanonicalPath(),\n Field.Store.YES,Field.Index.NOT_ANALYZED);\n\n document.add(contentField);\n document.add(fileNameField);\n document.add(filePathField);\n\n return document;\n } \n\n private void indexFile(File file) throws IOException {\n System.out.println(\"Indexing \"+file.getCanonicalPath());\n Document document = getDocument(file);\n writer.addDocument(document);\n }\n\n public int createIndex(String dataDirPath, FileFilter filter) \n throws IOException {\n //get all files in the data directory\n File[] files = new File(dataDirPath).listFiles();\n\n for (File file : files) {\n if(!file.isDirectory()\n && !file.isHidden()\n && file.exists()\n && file.canRead()\n && filter.accept(file)\n ){\n indexFile(file);\n }\n }\n return writer.numDocs();\n }\n}" }, { "code": null, "e": 9074, "s": 9000, "text": "This class is used to test the indexing capability of the Lucene library." }, { "code": null, "e": 9924, "s": 9074, "text": "package com.tutorialspoint.lucene;\n\nimport java.io.IOException;\n\npublic class LuceneTester {\n\t\n String indexDir = \"E:\\\\Lucene\\\\Index\";\n String dataDir = \"E:\\\\Lucene\\\\Data\";\n Indexer indexer;\n \n public static void main(String[] args) {\n LuceneTester tester;\n try {\n tester = new LuceneTester();\n tester.createIndex();\n } catch (IOException e) {\n e.printStackTrace();\n } \n }\n\n private void createIndex() throws IOException {\n indexer = new Indexer(indexDir);\n int numIndexed;\n long startTime = System.currentTimeMillis();\t\n numIndexed = indexer.createIndex(dataDir, new TextFileFilter());\n long endTime = System.currentTimeMillis();\n indexer.close();\n System.out.println(numIndexed+\" File indexed, time taken: \"\n +(endTime-startTime)+\" ms\");\t\t\n }\n}" }, { "code": null, "e": 10242, "s": 9924, "text": "We have used 10 text files from record1.txt to record10.txt containing names and other details of the students and put them in the directory E:\\Lucene\\Data. Test Data. An index directory path should be created as E:\\Lucene\\Index. After running this program, you can see the list of index files created in that folder." }, { "code": null, "e": 10690, "s": 10242, "text": "Once you are done with the creation of the source, the raw data, the data directory and the index directory, you can proceed by compiling and running your program. To do this, keep the LuceneTester.Java file tab active and use either the Run option available in the Eclipse IDE or use Ctrl + F11 to compile and run your LuceneTester application. If your application runs successfully, it will print the following message in Eclipse IDE's console −" }, { "code": null, "e": 11088, "s": 10690, "text": "Indexing E:\\Lucene\\Data\\record1.txt\nIndexing E:\\Lucene\\Data\\record10.txt\nIndexing E:\\Lucene\\Data\\record2.txt\nIndexing E:\\Lucene\\Data\\record3.txt\nIndexing E:\\Lucene\\Data\\record4.txt\nIndexing E:\\Lucene\\Data\\record5.txt\nIndexing E:\\Lucene\\Data\\record6.txt\nIndexing E:\\Lucene\\Data\\record7.txt\nIndexing E:\\Lucene\\Data\\record8.txt\nIndexing E:\\Lucene\\Data\\record9.txt\n10 File indexed, time taken: 109 ms\n" }, { "code": null, "e": 11192, "s": 11088, "text": "Once you've run the program successfully, you will have the following content in your index directory −" }, { "code": null, "e": 11199, "s": 11192, "text": " Print" }, { "code": null, "e": 11210, "s": 11199, "text": " Add Notes" } ]
How to move a Tkinter button? - GeeksforGeeks
02 Jul, 2021 Prerequisite: Creating a button in tkinter Tkinter is the most commonly used library for developing GUI (Graphical User Interface) in Python. It is a standard Python interface to the Tk GUI toolkit shipped with Python. As Tk and Tkinter are available on most of the Unix platforms as well as on the Windows system, developing GUI applications with Tkinter becomes the fastest and easiest. This module does not come built-in with Python. To install this module type the below pip command in the terminal. pip install tkintertable Approach: Import the tkinter module # Tkinter in Python 2.x. (Note Capital T). Create main window (root = Tk()). Add a button to the window. Place the button. The button in the Tkinter module can be placed or move to any position in two ways: By using the place method. And by using the pack method. Method 1: Using the place method This method is used to place a button at an absolute defined position. Syntax : button1.place(x=some_value, y=some_value) Parameters : x : It defines the x-coordinate of the button’s position. y : It defines the y-coordinate of the button’s position. Below is the implementation of the approach shown above: Python3 # Importing tkinter modulefrom tkinter import * # Creating a tkinter windowroot = Tk() # Initialize tkinter window with dimensions 300 x 250 root.geometry('300x250') # Creating a Buttonbtn = Button(root, text = 'Click me !', command = root.destroy) # Set the position of button to coordinate (100, 20)btn.place(x=100, y=20) root.mainloop() Output: Method 2: Using the pack method This method is used to place a button at a relative position. Syntax : button1.pack(side=some_side, padx=some_value, pady=some_value) Parameters : side : It defines the side where the button will be placed. padx : It defines the padding on x-axis from the defined side. pady : It defines the padding on y-axis from the defines side. Below is the implementation of the approach shown above: Python3 # Importing tkinter modulefrom tkinter import * # Creating a tkinter windowroot = Tk() # Initialize tkinter window with dimensions 300 x 250 root.geometry('300x250') # Creating a Buttonbtn = Button(root, text = 'Click me !', command = root.destroy) # Set a relative position of buttonbtn.pack(side=RIGHT, padx=15, pady=20) root.mainloop() Output: Method 3: Using the grid method This method is used to grid a button at a relative position. Syntax : button.widget.grid( grid_options ) Parameters : column − The column to place widget in; default 0 (leftmost column). columnspan − How many columns widgetoccupies; default 1. ipadx, ipady − How many pixels to pad widget, horizontally and vertically, inside widget’s borders. padx, pady − How many pixels to pad widget, horizontally and vertically, outside v’s borders. row − The row to put widget in; default the first row that is still empty. rowspan − How many rowswidget occupies; default 1. sticky − What to try to to if the cell is larger than widget. By default, with sticky=”, widget is centered in its cell. sticky may be the string concatenation of zero or more of N, E, S, W, NE, NW, SE, and SW, compass directions indicating the sides and corners of the cell to which widget sticks. Below is the implementation of the approach shown above: Python3 # Importing tkinter modulefrom tkinter import * # Creating a tkinter windowroot = Tk() # Initialize tkinter window# with dimensions 300 x 250 root.geometry('300x250') # Creating a Buttonbtn1 = Button(root, text = 'btn1 !', command = root.destroy)btn1.grid(row = 0, column = 0) # Creating a Buttonbtn2 = Button(root, text = 'btn2 !', command = root.destroy)btn2.grid(row = 1, column = 1) # Creating a Buttonbtn3 = Button(root, text = 'btn3 !', command = root.destroy)btn3.grid(row = 2, column = 2) # Creating a Buttonbtn3 = Button(root, text = 'btn4 !', command = root.destroy)btn3.grid(row = 4, column = 4) root.mainloop() Output: Below is a simple Application to showcase making button movement randomly in a tkinter GUI: Python3 # Importing tkinter modulefrom tkinter import *# Importing random moduleimport random # Creating a tkinter windowroot = Tk() # Initialize tkinter window with dimensions 300 x 250root.geometry('300x250') # Creating a Buttonbtn = Button(root, text = 'Click me !')btn.pack() # Defining method on clickdef Clicked(event): x = random.randint(50,250) y = random.randint(50,200) btn.place(x=x, y=y) # bind buttonbtn.bind("<Button-1>" ,Clicked)btn.pack() root.mainloop() Output: sweetyty Picked Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25743, "s": 25715, "text": "\n02 Jul, 2021" }, { "code": null, "e": 25786, "s": 25743, "text": "Prerequisite: Creating a button in tkinter" }, { "code": null, "e": 26132, "s": 25786, "text": "Tkinter is the most commonly used library for developing GUI (Graphical User Interface) in Python. It is a standard Python interface to the Tk GUI toolkit shipped with Python. As Tk and Tkinter are available on most of the Unix platforms as well as on the Windows system, developing GUI applications with Tkinter becomes the fastest and easiest." }, { "code": null, "e": 26247, "s": 26132, "text": "This module does not come built-in with Python. To install this module type the below pip command in the terminal." }, { "code": null, "e": 26272, "s": 26247, "text": "pip install tkintertable" }, { "code": null, "e": 26282, "s": 26272, "text": "Approach:" }, { "code": null, "e": 26351, "s": 26282, "text": "Import the tkinter module # Tkinter in Python 2.x. (Note Capital T)." }, { "code": null, "e": 26385, "s": 26351, "text": "Create main window (root = Tk())." }, { "code": null, "e": 26413, "s": 26385, "text": "Add a button to the window." }, { "code": null, "e": 26431, "s": 26413, "text": "Place the button." }, { "code": null, "e": 26515, "s": 26431, "text": "The button in the Tkinter module can be placed or move to any position in two ways:" }, { "code": null, "e": 26542, "s": 26515, "text": "By using the place method." }, { "code": null, "e": 26572, "s": 26542, "text": "And by using the pack method." }, { "code": null, "e": 26605, "s": 26572, "text": "Method 1: Using the place method" }, { "code": null, "e": 26676, "s": 26605, "text": "This method is used to place a button at an absolute defined position." }, { "code": null, "e": 26728, "s": 26676, "text": "Syntax : button1.place(x=some_value, y=some_value) " }, { "code": null, "e": 26741, "s": 26728, "text": "Parameters :" }, { "code": null, "e": 26799, "s": 26741, "text": "x : It defines the x-coordinate of the button’s position." }, { "code": null, "e": 26857, "s": 26799, "text": "y : It defines the y-coordinate of the button’s position." }, { "code": null, "e": 26914, "s": 26857, "text": "Below is the implementation of the approach shown above:" }, { "code": null, "e": 26922, "s": 26914, "text": "Python3" }, { "code": "# Importing tkinter modulefrom tkinter import * # Creating a tkinter windowroot = Tk() # Initialize tkinter window with dimensions 300 x 250 root.geometry('300x250') # Creating a Buttonbtn = Button(root, text = 'Click me !', command = root.destroy) # Set the position of button to coordinate (100, 20)btn.place(x=100, y=20) root.mainloop()", "e": 27284, "s": 26922, "text": null }, { "code": null, "e": 27292, "s": 27284, "text": "Output:" }, { "code": null, "e": 27324, "s": 27292, "text": "Method 2: Using the pack method" }, { "code": null, "e": 27386, "s": 27324, "text": "This method is used to place a button at a relative position." }, { "code": null, "e": 27458, "s": 27386, "text": "Syntax : button1.pack(side=some_side, padx=some_value, pady=some_value)" }, { "code": null, "e": 27472, "s": 27458, "text": "Parameters : " }, { "code": null, "e": 27532, "s": 27472, "text": "side : It defines the side where the button will be placed." }, { "code": null, "e": 27595, "s": 27532, "text": "padx : It defines the padding on x-axis from the defined side." }, { "code": null, "e": 27658, "s": 27595, "text": "pady : It defines the padding on y-axis from the defines side." }, { "code": null, "e": 27715, "s": 27658, "text": "Below is the implementation of the approach shown above:" }, { "code": null, "e": 27723, "s": 27715, "text": "Python3" }, { "code": "# Importing tkinter modulefrom tkinter import * # Creating a tkinter windowroot = Tk() # Initialize tkinter window with dimensions 300 x 250 root.geometry('300x250') # Creating a Buttonbtn = Button(root, text = 'Click me !', command = root.destroy) # Set a relative position of buttonbtn.pack(side=RIGHT, padx=15, pady=20) root.mainloop()", "e": 28084, "s": 27723, "text": null }, { "code": null, "e": 28092, "s": 28084, "text": "Output:" }, { "code": null, "e": 28124, "s": 28092, "text": "Method 3: Using the grid method" }, { "code": null, "e": 28185, "s": 28124, "text": "This method is used to grid a button at a relative position." }, { "code": null, "e": 28229, "s": 28185, "text": "Syntax : button.widget.grid( grid_options )" }, { "code": null, "e": 28243, "s": 28229, "text": "Parameters : " }, { "code": null, "e": 28312, "s": 28243, "text": "column − The column to place widget in; default 0 (leftmost column)." }, { "code": null, "e": 28369, "s": 28312, "text": "columnspan − How many columns widgetoccupies; default 1." }, { "code": null, "e": 28469, "s": 28369, "text": "ipadx, ipady − How many pixels to pad widget, horizontally and vertically, inside widget’s borders." }, { "code": null, "e": 28563, "s": 28469, "text": "padx, pady − How many pixels to pad widget, horizontally and vertically, outside v’s borders." }, { "code": null, "e": 28638, "s": 28563, "text": "row − The row to put widget in; default the first row that is still empty." }, { "code": null, "e": 28689, "s": 28638, "text": "rowspan − How many rowswidget occupies; default 1." }, { "code": null, "e": 28988, "s": 28689, "text": "sticky − What to try to to if the cell is larger than widget. By default, with sticky=”, widget is centered in its cell. sticky may be the string concatenation of zero or more of N, E, S, W, NE, NW, SE, and SW, compass directions indicating the sides and corners of the cell to which widget sticks." }, { "code": null, "e": 29045, "s": 28988, "text": "Below is the implementation of the approach shown above:" }, { "code": null, "e": 29053, "s": 29045, "text": "Python3" }, { "code": "# Importing tkinter modulefrom tkinter import * # Creating a tkinter windowroot = Tk() # Initialize tkinter window# with dimensions 300 x 250 root.geometry('300x250') # Creating a Buttonbtn1 = Button(root, text = 'btn1 !', command = root.destroy)btn1.grid(row = 0, column = 0) # Creating a Buttonbtn2 = Button(root, text = 'btn2 !', command = root.destroy)btn2.grid(row = 1, column = 1) # Creating a Buttonbtn3 = Button(root, text = 'btn3 !', command = root.destroy)btn3.grid(row = 2, column = 2) # Creating a Buttonbtn3 = Button(root, text = 'btn4 !', command = root.destroy)btn3.grid(row = 4, column = 4) root.mainloop()", "e": 29711, "s": 29053, "text": null }, { "code": null, "e": 29719, "s": 29711, "text": "Output:" }, { "code": null, "e": 29811, "s": 29719, "text": "Below is a simple Application to showcase making button movement randomly in a tkinter GUI:" }, { "code": null, "e": 29819, "s": 29811, "text": "Python3" }, { "code": "# Importing tkinter modulefrom tkinter import *# Importing random moduleimport random # Creating a tkinter windowroot = Tk() # Initialize tkinter window with dimensions 300 x 250root.geometry('300x250') # Creating a Buttonbtn = Button(root, text = 'Click me !')btn.pack() # Defining method on clickdef Clicked(event): x = random.randint(50,250) y = random.randint(50,200) btn.place(x=x, y=y) # bind buttonbtn.bind(\"<Button-1>\" ,Clicked)btn.pack() root.mainloop()", "e": 30300, "s": 29819, "text": null }, { "code": null, "e": 30308, "s": 30300, "text": "Output:" }, { "code": null, "e": 30317, "s": 30308, "text": "sweetyty" }, { "code": null, "e": 30324, "s": 30317, "text": "Picked" }, { "code": null, "e": 30339, "s": 30324, "text": "Python-tkinter" }, { "code": null, "e": 30346, "s": 30339, "text": "Python" }, { "code": null, "e": 30444, "s": 30346, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30462, "s": 30444, "text": "Python Dictionary" }, { "code": null, "e": 30497, "s": 30462, "text": "Read a file line by line in Python" }, { "code": null, "e": 30529, "s": 30497, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30551, "s": 30529, "text": "Enumerate() in Python" }, { "code": null, "e": 30593, "s": 30551, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30623, "s": 30593, "text": "Iterate over a list in Python" }, { "code": null, "e": 30649, "s": 30623, "text": "Python String | replace()" }, { "code": null, "e": 30693, "s": 30649, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 30722, "s": 30693, "text": "*args and **kwargs in Python" } ]
Python MongoDB - insert_many Query - GeeksforGeeks
19 Jan, 2022 MongoDB is a cross-platform document-oriented and a non relational (i.e NoSQL) database program. It is an open-source document database, that stores the data in the form of key-value pairs. MongoDB is developed by MongoDB Inc. and initially released on 11 February 2009. It is written in C++, Go, JavaScript, Python languages. MongoDB offers high speed, high availability, and high scalability. This method is used to insert multiple entries in a collection or the database in MongoDB. The parameter of this method is a list that contains dictionaries of the data that we want to insert in the collection.This method returns an instance of class “~pymongo.results.InsertManyResult” which has a “_id” field that holds the id of the inserted documents. If the document does not specify an “_id” field, then MongoDB will add the “_id” field to all the data in the list and assign a unique object id for the documents before inserting. Syntax: collection.insert_many(documents, ordered=True, bypass_document_validation=False, session=None)Parameters: ‘documents’ : A iterable of documents to insert. ‘ordered’ (optional): If “True” (the default) documents will be inserted on the server serially, in the order provided. If an error occurs all remaining inserts are aborted. If “False”, documents will be inserted on the server in arbitrary order, possibly in parallel, and all document inserts will be attempted. ‘bypass_document_validation’ (optional) : If “True”, allows the write to opt-out of document level validation. Default is “False”. ‘session’ (optional): a class ‘~pymongo.client_session.ClientSession’. Example 1: In this example _id is provided. Python3 # importing Mongoclient from pymongofrom pymongo import MongoClient myclient = MongoClient("mongodb://localhost:27017/") # databasedb = myclient["GFG"] # Created or Switched to collection# names: GeeksForGeekscollection = db["Student"] # Creating a list of records which we# insert in the collection using the# update_many() method.mylist = [ { "_id": 1, "name": "Vishwash", "Roll No": "1001", "Branch":"CSE"}, { "_id": 2, "name": "Vishesh", "Roll No": "1002", "Branch":"IT"}, { "_id": 3, "name": "Shivam", "Roll No": "1003", "Branch":"ME"}, { "_id": 4, "name": "Yash", "Roll No": "1004", "Branch":"ECE"},] # In the above list _id field is provided so it inserted in# the collection as specified. # Inserting the entire list in the collectioncollection.insert_many(mylist) Output: Example 2: In this example _id is not provided, it is allocated automatically by MongoDB. Python3 # importing Mongoclient from pymongofrom pymongo import MongoClient myclient = MongoClient("mongodb://localhost:27017/") # databasedb = myclient["GFG"] # Created or Switched to collection# names: GeeksForGeekscollection = db["Geeks"] # Creating a list of records which we# insert in the collection using the# update_many() method.mylist = [ {"Manufacturer":"Honda", "Model":"City", "Color":"Black"}, {"Manufacturer":"Tata", "Model":"Altroz", "Color":"Golden"}, {"Manufacturer":"Honda", "Model":"Civic", "Color":"Red"}, {"Manufacturer":"Hyundai", "Model":"i20", "Color":"white"}, {"Manufacturer":"Maruti", "Model":"Swift", "Color":"Blue"},]# In the above list we do not specify the _id, the MongoDB assigns# a unique id to all the records in the collection by default. # Inserting the entire list in the collectioncollection.insert_many(mylist) Output : clintra Python-mongoDB Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python Enumerate() in Python Iterate over a list in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace()
[ { "code": null, "e": 41448, "s": 41420, "text": "\n19 Jan, 2022" }, { "code": null, "e": 41844, "s": 41448, "text": "MongoDB is a cross-platform document-oriented and a non relational (i.e NoSQL) database program. It is an open-source document database, that stores the data in the form of key-value pairs. MongoDB is developed by MongoDB Inc. and initially released on 11 February 2009. It is written in C++, Go, JavaScript, Python languages. MongoDB offers high speed, high availability, and high scalability. " }, { "code": null, "e": 42382, "s": 41844, "text": "This method is used to insert multiple entries in a collection or the database in MongoDB. The parameter of this method is a list that contains dictionaries of the data that we want to insert in the collection.This method returns an instance of class “~pymongo.results.InsertManyResult” which has a “_id” field that holds the id of the inserted documents. If the document does not specify an “_id” field, then MongoDB will add the “_id” field to all the data in the list and assign a unique object id for the documents before inserting. " }, { "code": null, "e": 42499, "s": 42382, "text": "Syntax: collection.insert_many(documents, ordered=True, bypass_document_validation=False, session=None)Parameters: " }, { "code": null, "e": 42548, "s": 42499, "text": "‘documents’ : A iterable of documents to insert." }, { "code": null, "e": 42861, "s": 42548, "text": "‘ordered’ (optional): If “True” (the default) documents will be inserted on the server serially, in the order provided. If an error occurs all remaining inserts are aborted. If “False”, documents will be inserted on the server in arbitrary order, possibly in parallel, and all document inserts will be attempted." }, { "code": null, "e": 42992, "s": 42861, "text": "‘bypass_document_validation’ (optional) : If “True”, allows the write to opt-out of document level validation. Default is “False”." }, { "code": null, "e": 43063, "s": 42992, "text": "‘session’ (optional): a class ‘~pymongo.client_session.ClientSession’." }, { "code": null, "e": 43111, "s": 43065, "text": "Example 1: In this example _id is provided. " }, { "code": null, "e": 43119, "s": 43111, "text": "Python3" }, { "code": "# importing Mongoclient from pymongofrom pymongo import MongoClient myclient = MongoClient(\"mongodb://localhost:27017/\") # databasedb = myclient[\"GFG\"] # Created or Switched to collection# names: GeeksForGeekscollection = db[\"Student\"] # Creating a list of records which we# insert in the collection using the# update_many() method.mylist = [ { \"_id\": 1, \"name\": \"Vishwash\", \"Roll No\": \"1001\", \"Branch\":\"CSE\"}, { \"_id\": 2, \"name\": \"Vishesh\", \"Roll No\": \"1002\", \"Branch\":\"IT\"}, { \"_id\": 3, \"name\": \"Shivam\", \"Roll No\": \"1003\", \"Branch\":\"ME\"}, { \"_id\": 4, \"name\": \"Yash\", \"Roll No\": \"1004\", \"Branch\":\"ECE\"},] # In the above list _id field is provided so it inserted in# the collection as specified. # Inserting the entire list in the collectioncollection.insert_many(mylist)", "e": 43897, "s": 43119, "text": null }, { "code": null, "e": 43906, "s": 43897, "text": "Output: " }, { "code": null, "e": 43998, "s": 43906, "text": "Example 2: In this example _id is not provided, it is allocated automatically by MongoDB. " }, { "code": null, "e": 44006, "s": 43998, "text": "Python3" }, { "code": "# importing Mongoclient from pymongofrom pymongo import MongoClient myclient = MongoClient(\"mongodb://localhost:27017/\") # databasedb = myclient[\"GFG\"] # Created or Switched to collection# names: GeeksForGeekscollection = db[\"Geeks\"] # Creating a list of records which we# insert in the collection using the# update_many() method.mylist = [ {\"Manufacturer\":\"Honda\", \"Model\":\"City\", \"Color\":\"Black\"}, {\"Manufacturer\":\"Tata\", \"Model\":\"Altroz\", \"Color\":\"Golden\"}, {\"Manufacturer\":\"Honda\", \"Model\":\"Civic\", \"Color\":\"Red\"}, {\"Manufacturer\":\"Hyundai\", \"Model\":\"i20\", \"Color\":\"white\"}, {\"Manufacturer\":\"Maruti\", \"Model\":\"Swift\", \"Color\":\"Blue\"},]# In the above list we do not specify the _id, the MongoDB assigns# a unique id to all the records in the collection by default. # Inserting the entire list in the collectioncollection.insert_many(mylist)", "e": 44856, "s": 44006, "text": null }, { "code": null, "e": 44866, "s": 44856, "text": "Output : " }, { "code": null, "e": 44876, "s": 44868, "text": "clintra" }, { "code": null, "e": 44891, "s": 44876, "text": "Python-mongoDB" }, { "code": null, "e": 44898, "s": 44891, "text": "Python" }, { "code": null, "e": 44996, "s": 44898, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45005, "s": 44996, "text": "Comments" }, { "code": null, "e": 45018, "s": 45005, "text": "Old Comments" }, { "code": null, "e": 45046, "s": 45018, "text": "Read JSON file using Python" }, { "code": null, "e": 45096, "s": 45046, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 45118, "s": 45096, "text": "Python map() function" }, { "code": null, "e": 45162, "s": 45118, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 45197, "s": 45162, "text": "Read a file line by line in Python" }, { "code": null, "e": 45219, "s": 45197, "text": "Enumerate() in Python" }, { "code": null, "e": 45249, "s": 45219, "text": "Iterate over a list in Python" }, { "code": null, "e": 45281, "s": 45249, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 45323, "s": 45281, "text": "Different ways to create Pandas Dataframe" } ]
8085 program to convert ASCII code into HEX code - GeeksforGeeks
14 Jun, 2018 Problem – Write an assembly level language program to convert ASCII code to its respective HEX Code. Examples: Input: DATA: 31H in memory location 2050 Output: DATA: 0BH in memory location 3050 Assume that starting address of program, input memory location, and output memory locations are 2000, 2050, and 3050 respectively. Algorithm – Input the content of 2050 in accumulator.Subtract 30H from accumulator.Compare the content of accumulator with 0AH.If content of accumulator is less than 0A then goto step 6 else goto step 5.Subtract 07H from accumulator.Store content of accumulator to memory location 3050.Terminate the program. Input the content of 2050 in accumulator. Subtract 30H from accumulator. Compare the content of accumulator with 0AH. If content of accumulator is less than 0A then goto step 6 else goto step 5. Subtract 07H from accumulator. Store content of accumulator to memory location 3050. Terminate the program. Program – Explanation – LDA 2050 load the content of memory location 2050 to accumulator.SUI 30H subtracts 30H immediately from accumulator.CPI 0AH compare immediately 0AH with the data of accumulator.JC 200D check for carry if yes then go to address 200D.SUI 07H subtracts 07H immediately from accumulator.STA 3050 store the content of accumulator to memory location 3050.HLT stops the execution of program. LDA 2050 load the content of memory location 2050 to accumulator. SUI 30H subtracts 30H immediately from accumulator. CPI 0AH compare immediately 0AH with the data of accumulator. JC 200D check for carry if yes then go to address 200D. SUI 07H subtracts 07H immediately from accumulator. STA 3050 store the content of accumulator to memory location 3050. HLT stops the execution of program. microprocessor system-programming Computer Organization & Architecture microprocessor Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Memory Hierarchy Design and its Characteristics Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput) Flag register of 8086 microprocessor Direct Access Media (DMA) Controller in Computer Architecture Interrupts I/O Interface (Interrupt and DMA Mode) Flag register in 8085 microprocessor Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard) Architecture of 8085 microprocessor Addressing modes in 8086 microprocessor
[ { "code": null, "e": 25100, "s": 25072, "text": "\n14 Jun, 2018" }, { "code": null, "e": 25201, "s": 25100, "text": "Problem – Write an assembly level language program to convert ASCII code to its respective HEX Code." }, { "code": null, "e": 25211, "s": 25201, "text": "Examples:" }, { "code": null, "e": 25296, "s": 25211, "text": "Input: \nDATA: 31H in memory location 2050\nOutput:\nDATA: 0BH in memory location 3050 " }, { "code": null, "e": 25427, "s": 25296, "text": "Assume that starting address of program, input memory location, and output memory locations are 2000, 2050, and 3050 respectively." }, { "code": null, "e": 25439, "s": 25427, "text": "Algorithm –" }, { "code": null, "e": 25736, "s": 25439, "text": "Input the content of 2050 in accumulator.Subtract 30H from accumulator.Compare the content of accumulator with 0AH.If content of accumulator is less than 0A then goto step 6 else goto step 5.Subtract 07H from accumulator.Store content of accumulator to memory location 3050.Terminate the program." }, { "code": null, "e": 25778, "s": 25736, "text": "Input the content of 2050 in accumulator." }, { "code": null, "e": 25809, "s": 25778, "text": "Subtract 30H from accumulator." }, { "code": null, "e": 25854, "s": 25809, "text": "Compare the content of accumulator with 0AH." }, { "code": null, "e": 25931, "s": 25854, "text": "If content of accumulator is less than 0A then goto step 6 else goto step 5." }, { "code": null, "e": 25962, "s": 25931, "text": "Subtract 07H from accumulator." }, { "code": null, "e": 26016, "s": 25962, "text": "Store content of accumulator to memory location 3050." }, { "code": null, "e": 26039, "s": 26016, "text": "Terminate the program." }, { "code": null, "e": 26049, "s": 26039, "text": "Program –" }, { "code": null, "e": 26063, "s": 26049, "text": "Explanation –" }, { "code": null, "e": 26448, "s": 26063, "text": "LDA 2050 load the content of memory location 2050 to accumulator.SUI 30H subtracts 30H immediately from accumulator.CPI 0AH compare immediately 0AH with the data of accumulator.JC 200D check for carry if yes then go to address 200D.SUI 07H subtracts 07H immediately from accumulator.STA 3050 store the content of accumulator to memory location 3050.HLT stops the execution of program." }, { "code": null, "e": 26514, "s": 26448, "text": "LDA 2050 load the content of memory location 2050 to accumulator." }, { "code": null, "e": 26566, "s": 26514, "text": "SUI 30H subtracts 30H immediately from accumulator." }, { "code": null, "e": 26628, "s": 26566, "text": "CPI 0AH compare immediately 0AH with the data of accumulator." }, { "code": null, "e": 26684, "s": 26628, "text": "JC 200D check for carry if yes then go to address 200D." }, { "code": null, "e": 26736, "s": 26684, "text": "SUI 07H subtracts 07H immediately from accumulator." }, { "code": null, "e": 26803, "s": 26736, "text": "STA 3050 store the content of accumulator to memory location 3050." }, { "code": null, "e": 26839, "s": 26803, "text": "HLT stops the execution of program." }, { "code": null, "e": 26854, "s": 26839, "text": "microprocessor" }, { "code": null, "e": 26873, "s": 26854, "text": "system-programming" }, { "code": null, "e": 26910, "s": 26873, "text": "Computer Organization & Architecture" }, { "code": null, "e": 26925, "s": 26910, "text": "microprocessor" }, { "code": null, "e": 27023, "s": 26925, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27071, "s": 27023, "text": "Memory Hierarchy Design and its Characteristics" }, { "code": null, "e": 27166, "s": 27071, "text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)" }, { "code": null, "e": 27203, "s": 27166, "text": "Flag register of 8086 microprocessor" }, { "code": null, "e": 27265, "s": 27203, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 27276, "s": 27265, "text": "Interrupts" }, { "code": null, "e": 27315, "s": 27276, "text": "I/O Interface (Interrupt and DMA Mode)" }, { "code": null, "e": 27352, "s": 27315, "text": "Flag register in 8085 microprocessor" }, { "code": null, "e": 27443, "s": 27352, "text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)" }, { "code": null, "e": 27479, "s": 27443, "text": "Architecture of 8085 microprocessor" } ]
C++ program to calculate GST from original and net prices
Given with the original cost and net price as an input and the task is to calculate the GST percentage and display the result GST stands for Goods and Service task. It is always included in the Net price of the product and before calculating the GST percentage we need to calculate GST amount and for that there are formulas available Netprice = originalcost + GSTAmount GSTAmount = Netprice – original_cost GST_Percentage = (GSTAmount * 100)/ originalcost GST % formula = (GSTAmount*100) / originalcost Input-: cost = 120.00 price = 150.00 Output-: GST amount is = 25.00 % Input-: price = 120.00 cost = 100.00 Output-: GST amount is = 20.00 % Approach used in the given program is as follows − Take the input as net price and original cost Apply the formula given to calculate GST percentage Display the result Start Step 1-> declare function to calculate GST float GST(float cost, float price) return (((price - cost) * 100) / cost) step 2-> In main() set float cost = 120 set float price = 150 call GST(cost, price) Stop Live Demo Using c++ #include <iostream> using namespace std; //function to calculate GST float GST(float cost, float price) { return (((price - cost) * 100) / cost); } int main() { float cost = 120.00; float price = 150.00; cout << "GST amount is = "<<GST(cost, price)<<" % "; return 0; } IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT GST amount is = 25.00 % Live Demo #include <stdio.h> //function to calculate GST float GST(float cost, float price) { return (((price - cost) * 100) / cost); } int main() { float cost = 120; float price = 150; float gst = GST(cost, price); printf("GST amount is : %.2f ",gst); return 0; } IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT GST amount is : 25.00
[ { "code": null, "e": 1188, "s": 1062, "text": "Given with the original cost and net price as an input and the task is to calculate the GST percentage and display the result" }, { "code": null, "e": 1397, "s": 1188, "text": "GST stands for Goods and Service task. It is always included in the Net price of the product and before calculating the GST percentage we need to calculate GST amount and for that there are formulas available" }, { "code": null, "e": 1433, "s": 1397, "text": "Netprice = originalcost + GSTAmount" }, { "code": null, "e": 1470, "s": 1433, "text": "GSTAmount = Netprice – original_cost" }, { "code": null, "e": 1519, "s": 1470, "text": "GST_Percentage = (GSTAmount * 100)/ originalcost" }, { "code": null, "e": 1566, "s": 1519, "text": "GST % formula = (GSTAmount*100) / originalcost" }, { "code": null, "e": 1712, "s": 1566, "text": "Input-: cost = 120.00\n price = 150.00\nOutput-: GST amount is = 25.00 %\nInput-: price = 120.00\n cost = 100.00\nOutput-: GST amount is = 20.00 %" }, { "code": null, "e": 1763, "s": 1712, "text": "Approach used in the given program is as follows −" }, { "code": null, "e": 1809, "s": 1763, "text": "Take the input as net price and original cost" }, { "code": null, "e": 1861, "s": 1809, "text": "Apply the formula given to calculate GST percentage" }, { "code": null, "e": 1880, "s": 1861, "text": "Display the result" }, { "code": null, "e": 2107, "s": 1880, "text": "Start\nStep 1-> declare function to calculate GST\n float GST(float cost, float price)\n return (((price - cost) * 100) / cost)\nstep 2-> In main()\n set float cost = 120\n set float price = 150\n call GST(cost, price)\nStop" }, { "code": null, "e": 2118, "s": 2107, "text": " Live Demo" }, { "code": null, "e": 2412, "s": 2118, "text": "Using c++\n#include <iostream>\nusing namespace std;\n//function to calculate GST\nfloat GST(float cost, float price) {\n return (((price - cost) * 100) / cost);\n}\nint main() {\n float cost = 120.00;\n float price = 150.00;\n cout << \"GST amount is = \"<<GST(cost, price)<<\" % \";\n return 0;\n}" }, { "code": null, "e": 2471, "s": 2412, "text": "IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT" }, { "code": null, "e": 2495, "s": 2471, "text": "GST amount is = 25.00 %" }, { "code": null, "e": 2506, "s": 2495, "text": " Live Demo" }, { "code": null, "e": 2779, "s": 2506, "text": "#include <stdio.h>\n//function to calculate GST\nfloat GST(float cost, float price) {\n return (((price - cost) * 100) / cost);\n}\nint main() {\n float cost = 120;\n float price = 150;\n float gst = GST(cost, price);\n printf(\"GST amount is : %.2f \",gst);\n return 0;\n}" }, { "code": null, "e": 2838, "s": 2779, "text": "IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT" }, { "code": null, "e": 2860, "s": 2838, "text": "GST amount is : 25.00" } ]
Tryit Editor v3.7
HTML file paths Tryit: relative url
[ { "code": null, "e": 26, "s": 10, "text": "HTML file paths" } ]
Disable a Bootstrap Button
When you disable a button, it will fade in color by 50%, and lose the gradient. Use disabled to disable any button. To disable a button, you can try to run the following code − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <p>The following are some buttons:</p> <button type = "button" class = "btn btn-default btn-lg "> Default Button </button> <button type = "button" class = "btn btn-default btn-lg active"> Active Button </button> <button type = "button" class = "btn btn-default btn-lg" disabled = "disabled"> Disabled Button </button> </body> </html>
[ { "code": null, "e": 1178, "s": 1062, "text": "When you disable a button, it will fade in color by 50%, and lose the gradient. Use disabled to disable any button." }, { "code": null, "e": 1239, "s": 1178, "text": "To disable a button, you can try to run the following code −" }, { "code": null, "e": 1249, "s": 1239, "text": "Live Demo" }, { "code": null, "e": 1940, "s": 1249, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <p>The following are some buttons:</p>\n <button type = \"button\" class = \"btn btn-default btn-lg \">\n Default Button\n </button>\n <button type = \"button\" class = \"btn btn-default btn-lg active\">\n Active Button\n </button>\n <button type = \"button\" class = \"btn btn-default btn-lg\" disabled = \"disabled\">\n Disabled Button\n </button>\n </body>\n</html>" } ]
Firebase - Arrays
This chapter will explain the Firebase representation of arrays. We will use the same data from the previous chapter. We could create this data by sending the following JSON tree to the player’s collection. ['john', 'amanda'] This is because Firebase does not support Arrays directly, but it creates a list of objects with integers as key names. The reason for not using arrays is because Firebase acts as a real time database and if a couple of users were to manipulate arrays at the same time, the result could be problematic since array indexes are constantly changing. The way Firebase handles it, the keys (indexes) will always stay the same. We could delete john and amanda would still have the key (index) 1. 60 Lectures 5 hours University Code 28 Lectures 2.5 hours Appeteria 85 Lectures 14.5 hours Appeteria 46 Lectures 2.5 hours Gautham Vijayan 13 Lectures 1.5 hours Nishant Kumar 85 Lectures 16.5 hours Rahul Agarwal Print Add Notes Bookmark this page
[ { "code": null, "e": 2284, "s": 2166, "text": "This chapter will explain the Firebase representation of arrays. We will use the same data from the previous chapter." }, { "code": null, "e": 2373, "s": 2284, "text": "We could create this data by sending the following JSON tree to the player’s collection." }, { "code": null, "e": 2393, "s": 2373, "text": "['john', 'amanda']\n" }, { "code": null, "e": 2513, "s": 2393, "text": "This is because Firebase does not support Arrays directly, but it creates a list of objects with integers as key names." }, { "code": null, "e": 2740, "s": 2513, "text": "The reason for not using arrays is because Firebase acts as a real time database and if a couple of users were to manipulate arrays at the same time, the result could be problematic since array indexes are constantly changing." }, { "code": null, "e": 2883, "s": 2740, "text": "The way Firebase handles it, the keys (indexes) will always stay the same. We could delete john and amanda would still have the key (index) 1." }, { "code": null, "e": 2916, "s": 2883, "text": "\n 60 Lectures \n 5 hours \n" }, { "code": null, "e": 2933, "s": 2916, "text": " University Code" }, { "code": null, "e": 2968, "s": 2933, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2979, "s": 2968, "text": " Appeteria" }, { "code": null, "e": 3015, "s": 2979, "text": "\n 85 Lectures \n 14.5 hours \n" }, { "code": null, "e": 3026, "s": 3015, "text": " Appeteria" }, { "code": null, "e": 3061, "s": 3026, "text": "\n 46 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3078, "s": 3061, "text": " Gautham Vijayan" }, { "code": null, "e": 3113, "s": 3078, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3128, "s": 3113, "text": " Nishant Kumar" }, { "code": null, "e": 3164, "s": 3128, "text": "\n 85 Lectures \n 16.5 hours \n" }, { "code": null, "e": 3179, "s": 3164, "text": " Rahul Agarwal" }, { "code": null, "e": 3186, "s": 3179, "text": " Print" }, { "code": null, "e": 3197, "s": 3186, "text": " Add Notes" } ]
PHP | Ternary Operator
02 Sep, 2021 If-else and Switch cases are used to evaluate conditions and decide the flow of a program. The ternary operator is a shortcut operator used for shortening the conditional statements. ternary operator: The ternary operator (?:) is a conditional operator used to perform a simple comparison or check on a condition having simple statements. It decreases the length of the code performing conditional operations. The order of operation of this operator is from left to right. It is called a ternary operator because it takes three operands- a condition, a result statement for true, and a result statement for false. The syntax for the ternary operator is as follows. Syntax: (Condition) ? (Statement1) : (Statement2); Condition: It is the expression to be evaluated and returns a boolean value. Statement 1: It is the statement to be executed if the condition results in a true state. Statement 2: It is the statement to be executed if the condition results in a false state. The result of this comparison can also be assigned to a variable using the assignment operator. The syntax is as follows: Variable = (Condition) ? (Statement1) : (Statement2); If the statement executed depending on the condition returns any value, it will be assigned to the variable. Advantages of Ternary Operator: Following are some advantages of ternary operator: The use of the ternary operator will make the code shorter in comparison to the IF ELSE statement. The code can be quick in length in comparison to the IF ELSE statement. The readability of the code will increase with the usage of conditional statements. The use of the ternary operator makes the code simpler. Example 1: In this example, if the value of $a is greater than 15, then 20 will be returned and will be assigned to $b, else 5 will be returned and assigned to $b. php <?php $a = 10; $b = $a > 15 ? 20 : 5; print ("Value of b is " . $b);?> Output: Value of b is 5 Example 2: In this example, if the value of $age is more than or equal to 18, “Adult” is passed to print function and printed, else “Not Adult” is passed and printed. php <?php $age = 20; print ($age >= 18) ? "Adult" : "Not Adult";?> Output: Adult When we use ternary operator: We use the ternary operator when we need to simplify the if-else statements that are simply assigning values to variables depending on a condition. An advantage of using a ternary operator is that it reduces the huge if-else block to a single line, improving the code readability and simplify it. Very useful while assigning variables after form submission. Example: Original Code: php <?phpif(isset($_POST['Name'])) $name = $_POST['Name'];else $name = null; if(isset($_POST['Age'])) $age = $_POST['Age'];else $age = null;?> Reduced to the following: Thus, the ternary operator successfully reduces the if-else block to a single line, hence serving its purpose. php <?php$name = isset($_POST['Name'])?$_POST['Name']:null;$age = isset($_POST['Age'])?$_POST['Age']:null;?> PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. itskawal2000 PHP-basics Picked PHP PHP Programs Web Technologies Web technologies Questions Write From Home PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Sep, 2021" }, { "code": null, "e": 211, "s": 28, "text": "If-else and Switch cases are used to evaluate conditions and decide the flow of a program. The ternary operator is a shortcut operator used for shortening the conditional statements." }, { "code": null, "e": 694, "s": 211, "text": "ternary operator: The ternary operator (?:) is a conditional operator used to perform a simple comparison or check on a condition having simple statements. It decreases the length of the code performing conditional operations. The order of operation of this operator is from left to right. It is called a ternary operator because it takes three operands- a condition, a result statement for true, and a result statement for false. The syntax for the ternary operator is as follows. " }, { "code": null, "e": 702, "s": 694, "text": "Syntax:" }, { "code": null, "e": 745, "s": 702, "text": "(Condition) ? (Statement1) : (Statement2);" }, { "code": null, "e": 822, "s": 745, "text": "Condition: It is the expression to be evaluated and returns a boolean value." }, { "code": null, "e": 912, "s": 822, "text": "Statement 1: It is the statement to be executed if the condition results in a true state." }, { "code": null, "e": 1003, "s": 912, "text": "Statement 2: It is the statement to be executed if the condition results in a false state." }, { "code": null, "e": 1127, "s": 1003, "text": "The result of this comparison can also be assigned to a variable using the assignment operator. The syntax is as follows: " }, { "code": null, "e": 1181, "s": 1127, "text": "Variable = (Condition) ? (Statement1) : (Statement2);" }, { "code": null, "e": 1290, "s": 1181, "text": "If the statement executed depending on the condition returns any value, it will be assigned to the variable." }, { "code": null, "e": 1373, "s": 1290, "text": "Advantages of Ternary Operator: Following are some advantages of ternary operator:" }, { "code": null, "e": 1472, "s": 1373, "text": "The use of the ternary operator will make the code shorter in comparison to the IF ELSE statement." }, { "code": null, "e": 1544, "s": 1472, "text": "The code can be quick in length in comparison to the IF ELSE statement." }, { "code": null, "e": 1628, "s": 1544, "text": "The readability of the code will increase with the usage of conditional statements." }, { "code": null, "e": 1684, "s": 1628, "text": "The use of the ternary operator makes the code simpler." }, { "code": null, "e": 1848, "s": 1684, "text": "Example 1: In this example, if the value of $a is greater than 15, then 20 will be returned and will be assigned to $b, else 5 will be returned and assigned to $b." }, { "code": null, "e": 1852, "s": 1848, "text": "php" }, { "code": "<?php $a = 10; $b = $a > 15 ? 20 : 5; print (\"Value of b is \" . $b);?>", "e": 1926, "s": 1852, "text": null }, { "code": null, "e": 1935, "s": 1926, "text": "Output: " }, { "code": null, "e": 1951, "s": 1935, "text": "Value of b is 5" }, { "code": null, "e": 2118, "s": 1951, "text": "Example 2: In this example, if the value of $age is more than or equal to 18, “Adult” is passed to print function and printed, else “Not Adult” is passed and printed." }, { "code": null, "e": 2122, "s": 2118, "text": "php" }, { "code": "<?php $age = 20; print ($age >= 18) ? \"Adult\" : \"Not Adult\";?>", "e": 2187, "s": 2122, "text": null }, { "code": null, "e": 2196, "s": 2187, "text": "Output: " }, { "code": null, "e": 2202, "s": 2196, "text": "Adult" }, { "code": null, "e": 2591, "s": 2202, "text": "When we use ternary operator: We use the ternary operator when we need to simplify the if-else statements that are simply assigning values to variables depending on a condition. An advantage of using a ternary operator is that it reduces the huge if-else block to a single line, improving the code readability and simplify it. Very useful while assigning variables after form submission. " }, { "code": null, "e": 2601, "s": 2591, "text": "Example: " }, { "code": null, "e": 2617, "s": 2601, "text": "Original Code: " }, { "code": null, "e": 2621, "s": 2617, "text": "php" }, { "code": "<?phpif(isset($_POST['Name'])) $name = $_POST['Name'];else $name = null; if(isset($_POST['Age'])) $age = $_POST['Age'];else $age = null;?>", "e": 2772, "s": 2621, "text": null }, { "code": null, "e": 2910, "s": 2772, "text": "Reduced to the following: Thus, the ternary operator successfully reduces the if-else block to a single line, hence serving its purpose. " }, { "code": null, "e": 2914, "s": 2910, "text": "php" }, { "code": "<?php$name = isset($_POST['Name'])?$_POST['Name']:null;$age = isset($_POST['Age'])?$_POST['Age']:null;?>", "e": 3019, "s": 2914, "text": null }, { "code": null, "e": 3188, "s": 3019, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 3201, "s": 3188, "text": "itskawal2000" }, { "code": null, "e": 3212, "s": 3201, "text": "PHP-basics" }, { "code": null, "e": 3219, "s": 3212, "text": "Picked" }, { "code": null, "e": 3223, "s": 3219, "text": "PHP" }, { "code": null, "e": 3236, "s": 3223, "text": "PHP Programs" }, { "code": null, "e": 3253, "s": 3236, "text": "Web Technologies" }, { "code": null, "e": 3280, "s": 3253, "text": "Web technologies Questions" }, { "code": null, "e": 3296, "s": 3280, "text": "Write From Home" }, { "code": null, "e": 3300, "s": 3296, "text": "PHP" } ]