title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How To Annotate Bars in Barplot with Matplotlib in Python? - GeeksforGeeks
25 Jan, 2022 Annotation means adding notes to a diagram stating what values do it represents. It often gets tiresome for the user to read the values from the graph when the graph is scaled down or is overly populated. In this article, we will discuss how to annotate the bar plots created in python using matplotlib library. Following are examples of annotated and non-annotated bar plots: Non-annotated Vs Annotated Barplot Let’s first plot simple graphs from a Pandas dataframe, so now we have the following dataframe ready: Python3 # Importing libraries for dataframe creation# and graph plottingimport numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # Creating our own dataframedata = {"Name": ["Alex", "Bob", "Clarein", "Dexter"], "Marks": [45, 23, 78, 65]} # Now convert this dictionary type data into a pandas dataframe# specifying what are the column namesdf = pd.DataFrame(data, columns=['Name', 'Marks']) Output: User generated pandas datafranme Let’s now start plotting the dataframe using the seaborn library. We get the following results. But it is not quite visible that what are the actual values in the bar plots. This condition can also arise when the values of neighboring plots are quite close to each other. Python3 # Defining the plotsizeplt.figure(figsize=(8, 6)) # Defining the x-axis, the y-axis and the data# from where the values are to be takenplots = sns.barplot(x="Name", y="Marks", data=df) # Setting the x-acis label and its sizeplt.xlabel("Students", size=15) # Setting the y-axis label and its sizeplt.ylabel("Marks Secured", size=15) # Finallt plotting the graphplt.show() Output: Raw barplot of the dataframe Adding the annotations. Our strategy here will be to iterate all over the bars and put a text over all of them that will point out the values of that particular bar. Here we will use the Matlpotlib’s function called annotate(). We can find various uses of this function in various scenarios, currently, we will be just showing the value of the respective bars at their top. Our steps will be: Iterate over the barsGet the x-axis position(x) and the width(w) of the bar this will help us to get the x coordinate of the text i.e. get_x()+get_width()/2.The y-coordinate(y) of the text can be found using the height of the bar i.e. get_height()So we have the coordinates of the annotation value i.e. get_x()+get_width()/2, get_height()But this will print the annotation exactly on the boundary of the bar so to get a more pleasing annotated plot we use the parameter xyplot=(0, 8). Here 8 denotes the pixels that will be left from the top of the bar. Therefore to go below the barline we can use xy=(0,-8).So we execute the following code to get the annotated graph: Iterate over the bars Get the x-axis position(x) and the width(w) of the bar this will help us to get the x coordinate of the text i.e. get_x()+get_width()/2. The y-coordinate(y) of the text can be found using the height of the bar i.e. get_height() So we have the coordinates of the annotation value i.e. get_x()+get_width()/2, get_height() But this will print the annotation exactly on the boundary of the bar so to get a more pleasing annotated plot we use the parameter xyplot=(0, 8). Here 8 denotes the pixels that will be left from the top of the bar. Therefore to go below the barline we can use xy=(0,-8). So we execute the following code to get the annotated graph: Python3 # Defining the plot sizeplt.figure(figsize=(8, 8)) # Defining the values for x-axis, y-axis# and from which dataframe the values are to be pickedplots = sns.barplot(x="Name", y="Marks", data=df) # Iterrating over the bars one-by-onefor bar in plots.patches: # Using Matplotlib's annotate function and # passing the coordinates where the annotation shall be done # x-coordinate: bar.get_x() + bar.get_width() / 2 # y-coordinate: bar.get_height() # free space to be left to make graph pleasing: (0, 8) # ha and va stand for the horizontal and vertical alignment plots.annotate(format(bar.get_height(), '.2f'), (bar.get_x() + bar.get_width() / 2, bar.get_height()), ha='center', va='center', size=15, xytext=(0, 8), textcoords='offset points') # Setting the label for x-axisplt.xlabel("Students", size=14) # Setting the label for y-axisplt.ylabel("Marks Secured", size=14) # Setting the title for the graphplt.title("This is an annotated barplot") # Finally showing the plotplt.show() Output: Bar plot annotated with the bar values Below is the complete program based on the above approach: Python3 # Importing libraries for dataframe creation# and graph plottingimport numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # Creating our own dataframedata = {"Name": ["Alex", "Bob", "Clarein", "Dexter"], "Marks": [45, 23, 78, 65]} # Now convert this dictionary type data into a pandas dataframe# specifying what are the column namesdf = pd.DataFrame(data, columns=['Name', 'Marks']) # Defining the plot sizeplt.figure(figsize=(8, 8)) # Defining the values for x-axis, y-axis# and from which dataframe the values are to be pickedplots = sns.barplot(x="Name", y="Marks", data=df) # Iterrating over the bars one-by-onefor bar in plots.patches: # Using Matplotlib's annotate function and # passing the coordinates where the annotation shall be done # x-coordinate: bar.get_x() + bar.get_width() / 2 # y-coordinate: bar.get_height() # free space to be left to make graph pleasing: (0, 8) # ha and va stand for the horizontal and vertical alignment plots.annotate(format(bar.get_height(), '.2f'), (bar.get_x() + bar.get_width() / 2, bar.get_height()), ha='center', va='center', size=15, xytext=(0, 8), textcoords='offset points') # Setting the label for x-axisplt.xlabel("Students", size=14) # Setting the label for y-axisplt.ylabel("Marks Secured", size=14) # Setting the title for the graphplt.title("This is an annotated barplot") # Finally showing the plotplt.show() Output: Bar plot annotated with the bar values Example 1: Python3 # Importing libraries for dataframe creation# and graph plottingimport numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # Creating our own dataframedata = {"Language": ["Python", "C++", "Java"], "Students": [75, 50, 25]} # Now convert this dictionary type data into a pandas dataframe# specifying what are the column namesdf = pd.DataFrame(data, columns=['Language', 'Students']) # Defining the plot sizeplt.figure(figsize=(5, 5)) # Defining the values for x-axis, y-axis# and from which dataframe the values are to be pickedplots = sns.barplot(x="Language", y="Students", data=df) # Iterrating over the bars one-by-onefor bar in plots.patches: # Using Matplotlib's annotate function and # passing the coordinates where the annotation shall be done plots.annotate(format(bar.get_height(), '.2f'), (bar.get_x() + bar.get_width() / 2, bar.get_height()), ha='center', va='center', size=15, xytext=(0, 5), textcoords='offset points') # Setting the title for the graphplt.title("Example 1") # Finally showing the plotplt.show() Output: Example 2: Python3 # Importing libraries for dataframe creation# and graph plottingimport numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # Creating our own dataframedata = {"Section": ["A", "B", "C", 'D', 'E'], "Students": [0, 10, 20, 30, 40]} # Now convert this dictionary type data into a pandas dataframe# specifying what are the column namesdf = pd.DataFrame(data, columns=['Section', 'Students']) # Defining the plot sizeplt.figure(figsize=(5, 5)) # Defining the values for x-axis, y-axis# and from which dataframe the values are to be pickedplots = sns.barplot(x="Section", y="Students", data=df) # Iterrating over the bars one-by-onefor bar in plots.patches: # Using Matplotlib's annotate function and # passing the coordinates where the annotation shall be done plots.annotate(format(bar.get_height(), '.2f'), (bar.get_x() + bar.get_width() / 2, bar.get_height()), ha='center', va='center', size=15, xytext=(0, 5), textcoords='offset points') # Setting the title for the graphplt.title("Example 2") # Finally showing the plotplt.show() Python3 # Importing libraries for dataframe creation# and graph plottingimport numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # Creating our own dataframedata = {"Section": ["A", "B", "C", 'D', 'E'], "Students": [0, 10, 20, 30, 40]} # Now convert this dictionary type data into a pandas dataframe# specifying what are the column namesdf = pd.DataFrame(data, columns=['Section', 'Students']) # Defining the plot sizeplt.figure(figsize=(5, 5)) # Defining the values for x-axis, y-axis# and from which dataframe the values are to be pickedplots = sns.barplot(x="Section", y="Students", data=df) # Iterrating over the bars one-by-onefor bar in plots.patches: # Using Matplotlib's annotate function and # passing the coordinates where the annotation shall be done plots.annotate(format(bar.get_height(), '.2f'), (bar.get_x() + bar.get_width() / 2, bar.get_height()), ha='center', va='center', size=15, xytext=(0, 5), textcoords='offset points') # Setting the title for the graphplt.title("Example 2") # Finally showing the plotplt.show() Output: rajeev0719singh sagartomar9927 varshagumber28 Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 29911, "s": 29883, "text": "\n25 Jan, 2022" }, { "code": null, "e": 30224, "s": 29911, "text": "Annotation means adding notes to a diagram stating what values do it represents. It often gets tiresome for the user to read the values from the graph when the graph is scaled down or is overly populated. In this article, we will discuss how to annotate the bar plots created in python using matplotlib library." }, { "code": null, "e": 30289, "s": 30224, "text": "Following are examples of annotated and non-annotated bar plots:" }, { "code": null, "e": 30324, "s": 30289, "text": "Non-annotated Vs Annotated Barplot" }, { "code": null, "e": 30426, "s": 30324, "text": "Let’s first plot simple graphs from a Pandas dataframe, so now we have the following dataframe ready:" }, { "code": null, "e": 30434, "s": 30426, "text": "Python3" }, { "code": "# Importing libraries for dataframe creation# and graph plottingimport numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # Creating our own dataframedata = {\"Name\": [\"Alex\", \"Bob\", \"Clarein\", \"Dexter\"], \"Marks\": [45, 23, 78, 65]} # Now convert this dictionary type data into a pandas dataframe# specifying what are the column namesdf = pd.DataFrame(data, columns=['Name', 'Marks'])", "e": 30856, "s": 30434, "text": null }, { "code": null, "e": 30864, "s": 30856, "text": "Output:" }, { "code": null, "e": 30897, "s": 30864, "text": "User generated pandas datafranme" }, { "code": null, "e": 31169, "s": 30897, "text": "Let’s now start plotting the dataframe using the seaborn library. We get the following results. But it is not quite visible that what are the actual values in the bar plots. This condition can also arise when the values of neighboring plots are quite close to each other." }, { "code": null, "e": 31177, "s": 31169, "text": "Python3" }, { "code": "# Defining the plotsizeplt.figure(figsize=(8, 6)) # Defining the x-axis, the y-axis and the data# from where the values are to be takenplots = sns.barplot(x=\"Name\", y=\"Marks\", data=df) # Setting the x-acis label and its sizeplt.xlabel(\"Students\", size=15) # Setting the y-axis label and its sizeplt.ylabel(\"Marks Secured\", size=15) # Finallt plotting the graphplt.show()", "e": 31548, "s": 31177, "text": null }, { "code": null, "e": 31556, "s": 31548, "text": "Output:" }, { "code": null, "e": 31585, "s": 31556, "text": "Raw barplot of the dataframe" }, { "code": null, "e": 31959, "s": 31585, "text": "Adding the annotations. Our strategy here will be to iterate all over the bars and put a text over all of them that will point out the values of that particular bar. Here we will use the Matlpotlib’s function called annotate(). We can find various uses of this function in various scenarios, currently, we will be just showing the value of the respective bars at their top." }, { "code": null, "e": 31978, "s": 31959, "text": "Our steps will be:" }, { "code": null, "e": 32648, "s": 31978, "text": "Iterate over the barsGet the x-axis position(x) and the width(w) of the bar this will help us to get the x coordinate of the text i.e. get_x()+get_width()/2.The y-coordinate(y) of the text can be found using the height of the bar i.e. get_height()So we have the coordinates of the annotation value i.e. get_x()+get_width()/2, get_height()But this will print the annotation exactly on the boundary of the bar so to get a more pleasing annotated plot we use the parameter xyplot=(0, 8). Here 8 denotes the pixels that will be left from the top of the bar. Therefore to go below the barline we can use xy=(0,-8).So we execute the following code to get the annotated graph:" }, { "code": null, "e": 32670, "s": 32648, "text": "Iterate over the bars" }, { "code": null, "e": 32807, "s": 32670, "text": "Get the x-axis position(x) and the width(w) of the bar this will help us to get the x coordinate of the text i.e. get_x()+get_width()/2." }, { "code": null, "e": 32898, "s": 32807, "text": "The y-coordinate(y) of the text can be found using the height of the bar i.e. get_height()" }, { "code": null, "e": 32990, "s": 32898, "text": "So we have the coordinates of the annotation value i.e. get_x()+get_width()/2, get_height()" }, { "code": null, "e": 33262, "s": 32990, "text": "But this will print the annotation exactly on the boundary of the bar so to get a more pleasing annotated plot we use the parameter xyplot=(0, 8). Here 8 denotes the pixels that will be left from the top of the bar. Therefore to go below the barline we can use xy=(0,-8)." }, { "code": null, "e": 33323, "s": 33262, "text": "So we execute the following code to get the annotated graph:" }, { "code": null, "e": 33331, "s": 33323, "text": "Python3" }, { "code": "# Defining the plot sizeplt.figure(figsize=(8, 8)) # Defining the values for x-axis, y-axis# and from which dataframe the values are to be pickedplots = sns.barplot(x=\"Name\", y=\"Marks\", data=df) # Iterrating over the bars one-by-onefor bar in plots.patches: # Using Matplotlib's annotate function and # passing the coordinates where the annotation shall be done # x-coordinate: bar.get_x() + bar.get_width() / 2 # y-coordinate: bar.get_height() # free space to be left to make graph pleasing: (0, 8) # ha and va stand for the horizontal and vertical alignment plots.annotate(format(bar.get_height(), '.2f'), (bar.get_x() + bar.get_width() / 2, bar.get_height()), ha='center', va='center', size=15, xytext=(0, 8), textcoords='offset points') # Setting the label for x-axisplt.xlabel(\"Students\", size=14) # Setting the label for y-axisplt.ylabel(\"Marks Secured\", size=14) # Setting the title for the graphplt.title(\"This is an annotated barplot\") # Finally showing the plotplt.show()", "e": 34398, "s": 33331, "text": null }, { "code": null, "e": 34406, "s": 34398, "text": "Output:" }, { "code": null, "e": 34445, "s": 34406, "text": "Bar plot annotated with the bar values" }, { "code": null, "e": 34504, "s": 34445, "text": "Below is the complete program based on the above approach:" }, { "code": null, "e": 34512, "s": 34504, "text": "Python3" }, { "code": "# Importing libraries for dataframe creation# and graph plottingimport numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # Creating our own dataframedata = {\"Name\": [\"Alex\", \"Bob\", \"Clarein\", \"Dexter\"], \"Marks\": [45, 23, 78, 65]} # Now convert this dictionary type data into a pandas dataframe# specifying what are the column namesdf = pd.DataFrame(data, columns=['Name', 'Marks']) # Defining the plot sizeplt.figure(figsize=(8, 8)) # Defining the values for x-axis, y-axis# and from which dataframe the values are to be pickedplots = sns.barplot(x=\"Name\", y=\"Marks\", data=df) # Iterrating over the bars one-by-onefor bar in plots.patches: # Using Matplotlib's annotate function and # passing the coordinates where the annotation shall be done # x-coordinate: bar.get_x() + bar.get_width() / 2 # y-coordinate: bar.get_height() # free space to be left to make graph pleasing: (0, 8) # ha and va stand for the horizontal and vertical alignment plots.annotate(format(bar.get_height(), '.2f'), (bar.get_x() + bar.get_width() / 2, bar.get_height()), ha='center', va='center', size=15, xytext=(0, 8), textcoords='offset points') # Setting the label for x-axisplt.xlabel(\"Students\", size=14) # Setting the label for y-axisplt.ylabel(\"Marks Secured\", size=14) # Setting the title for the graphplt.title(\"This is an annotated barplot\") # Finally showing the plotplt.show()", "e": 36000, "s": 34512, "text": null }, { "code": null, "e": 36008, "s": 36000, "text": "Output:" }, { "code": null, "e": 36047, "s": 36008, "text": "Bar plot annotated with the bar values" }, { "code": null, "e": 36058, "s": 36047, "text": "Example 1:" }, { "code": null, "e": 36066, "s": 36058, "text": "Python3" }, { "code": "# Importing libraries for dataframe creation# and graph plottingimport numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # Creating our own dataframedata = {\"Language\": [\"Python\", \"C++\", \"Java\"], \"Students\": [75, 50, 25]} # Now convert this dictionary type data into a pandas dataframe# specifying what are the column namesdf = pd.DataFrame(data, columns=['Language', 'Students']) # Defining the plot sizeplt.figure(figsize=(5, 5)) # Defining the values for x-axis, y-axis# and from which dataframe the values are to be pickedplots = sns.barplot(x=\"Language\", y=\"Students\", data=df) # Iterrating over the bars one-by-onefor bar in plots.patches: # Using Matplotlib's annotate function and # passing the coordinates where the annotation shall be done plots.annotate(format(bar.get_height(), '.2f'), (bar.get_x() + bar.get_width() / 2, bar.get_height()), ha='center', va='center', size=15, xytext=(0, 5), textcoords='offset points') # Setting the title for the graphplt.title(\"Example 1\") # Finally showing the plotplt.show()", "e": 37217, "s": 36066, "text": null }, { "code": null, "e": 37225, "s": 37217, "text": "Output:" }, { "code": null, "e": 37236, "s": 37225, "text": "Example 2:" }, { "code": null, "e": 37244, "s": 37236, "text": "Python3" }, { "code": "# Importing libraries for dataframe creation# and graph plottingimport numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # Creating our own dataframedata = {\"Section\": [\"A\", \"B\", \"C\", 'D', 'E'], \"Students\": [0, 10, 20, 30, 40]} # Now convert this dictionary type data into a pandas dataframe# specifying what are the column namesdf = pd.DataFrame(data, columns=['Section', 'Students']) # Defining the plot sizeplt.figure(figsize=(5, 5)) # Defining the values for x-axis, y-axis# and from which dataframe the values are to be pickedplots = sns.barplot(x=\"Section\", y=\"Students\", data=df) # Iterrating over the bars one-by-onefor bar in plots.patches: # Using Matplotlib's annotate function and # passing the coordinates where the annotation shall be done plots.annotate(format(bar.get_height(), '.2f'), (bar.get_x() + bar.get_width() / 2, bar.get_height()), ha='center', va='center', size=15, xytext=(0, 5), textcoords='offset points') # Setting the title for the graphplt.title(\"Example 2\") # Finally showing the plotplt.show()", "e": 38397, "s": 37244, "text": null }, { "code": null, "e": 38405, "s": 38397, "text": "Python3" }, { "code": "# Importing libraries for dataframe creation# and graph plottingimport numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # Creating our own dataframedata = {\"Section\": [\"A\", \"B\", \"C\", 'D', 'E'], \"Students\": [0, 10, 20, 30, 40]} # Now convert this dictionary type data into a pandas dataframe# specifying what are the column namesdf = pd.DataFrame(data, columns=['Section', 'Students']) # Defining the plot sizeplt.figure(figsize=(5, 5)) # Defining the values for x-axis, y-axis# and from which dataframe the values are to be pickedplots = sns.barplot(x=\"Section\", y=\"Students\", data=df) # Iterrating over the bars one-by-onefor bar in plots.patches: # Using Matplotlib's annotate function and # passing the coordinates where the annotation shall be done plots.annotate(format(bar.get_height(), '.2f'), (bar.get_x() + bar.get_width() / 2, bar.get_height()), ha='center', va='center', size=15, xytext=(0, 5), textcoords='offset points') # Setting the title for the graphplt.title(\"Example 2\") # Finally showing the plotplt.show()", "e": 39558, "s": 38405, "text": null }, { "code": null, "e": 39566, "s": 39558, "text": "Output:" }, { "code": null, "e": 39582, "s": 39566, "text": "rajeev0719singh" }, { "code": null, "e": 39597, "s": 39582, "text": "sagartomar9927" }, { "code": null, "e": 39612, "s": 39597, "text": "varshagumber28" }, { "code": null, "e": 39630, "s": 39612, "text": "Python-matplotlib" }, { "code": null, "e": 39637, "s": 39630, "text": "Python" }, { "code": null, "e": 39735, "s": 39637, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39744, "s": 39735, "text": "Comments" }, { "code": null, "e": 39757, "s": 39744, "text": "Old Comments" }, { "code": null, "e": 39785, "s": 39757, "text": "Read JSON file using Python" }, { "code": null, "e": 39835, "s": 39785, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 39857, "s": 39835, "text": "Python map() function" }, { "code": null, "e": 39901, "s": 39857, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 39919, "s": 39901, "text": "Python Dictionary" }, { "code": null, "e": 39942, "s": 39919, "text": "Taking input in Python" }, { "code": null, "e": 39977, "s": 39942, "text": "Read a file line by line in Python" }, { "code": null, "e": 39999, "s": 39977, "text": "Enumerate() in Python" }, { "code": null, "e": 40031, "s": 39999, "text": "How to Install PIP on Windows ?" } ]
Difference between JavaScript and AngularJS - GeeksforGeeks
28 Oct, 2020 JavaScript: JavaScript is a lightweight and object-oriented scripting language used to create dynamic HTML pages with interactive effects within a webpage. It is an interpreted scripting language and its code is run in a web browser only and in order to execute and run the code outside the browser we can use Node.js. It is also called a browser’s language and can be used for client-side developments as well as server-side developments. It was developed by Brendan Eich at Netscape and was first released in 1995. JavaScript was created in the first place for DOM manipulation. Earlier websites were mostly static after JS was created dynamic Web sites were made. Functions in JS are objects. They may have properties and methods just like another object. They can be passed as arguments in other functions. Can handle date and time. Performs Form Validation although the forms are created using HTML. No compiler needed. JavaScript Example: javascript <!DOCTYPE html><html> <head> <title></title></head> <body bgcolor="white"> <p>Paragraph 1</p> <script type="text/javascript"> document.bgColor = "lightblue"; </script></body><html> Output: AngularJS: AngularJS is an open-source front-end web development framework for creating web applications and has great functionality and support. It was released in the year 2010 by the angular team of Google. It is a constantly developing and expanding framework which provides improved methods for developing web applications. It mainly works on the model view controller (MVC) concept for building apps and supports both dependency injection and data binding features. Easy to work with: All you need to know to work with AngularJS is basics of HTML, CSS and JavaScript, not necessary to be an expert in these technologies. Time saving: AngularJS allows us to work with components and hence we can use them again which saves time and unnecessary code. Ready to use template: AngularJS is mainly plain HTML, and it mainly makes use of the plain HTML template and passes it to the DOM and then the AngularJS compiler. It traverses the templates and then they are ready to use. AngularJS (version 1.5) was replaced by Angular (Typescript) in 2016. They are completely different frameworks. Angular is currently at version 10. AngularJS Example: javascript <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body> <center> <div ng-app=""> <h1>{{txt}}</h1> <p> <input type="text" ng-model="txt" /> </p> </div> </center></body> </html> Output: Difference between JavaScript and AngularJS : bunnyram19 tim17 AngularJS-Misc JavaScript-Misc AngularJS Difference Between JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Auth Guards in Angular 9/10/11 What is AOT and JIT Compiler in Angular ? Angular PrimeNG Dropdown Component How to set focus on input field automatically on page load in AngularJS ? How to make a Bootstrap Modal Popup in Angular 9/8 ? Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Difference between var, let and const keywords in JavaScript Difference between Process and Thread
[ { "code": null, "e": 24146, "s": 24118, "text": "\n28 Oct, 2020" }, { "code": null, "e": 24664, "s": 24146, "text": "JavaScript: JavaScript is a lightweight and object-oriented scripting language used to create dynamic HTML pages with interactive effects within a webpage. It is an interpreted scripting language and its code is run in a web browser only and in order to execute and run the code outside the browser we can use Node.js. It is also called a browser’s language and can be used for client-side developments as well as server-side developments. It was developed by Brendan Eich at Netscape and was first released in 1995. " }, { "code": null, "e": 24814, "s": 24664, "text": "JavaScript was created in the first place for DOM manipulation. Earlier websites were mostly static after JS was created dynamic Web sites were made." }, { "code": null, "e": 24958, "s": 24814, "text": "Functions in JS are objects. They may have properties and methods just like another object. They can be passed as arguments in other functions." }, { "code": null, "e": 24984, "s": 24958, "text": "Can handle date and time." }, { "code": null, "e": 25052, "s": 24984, "text": "Performs Form Validation although the forms are created using HTML." }, { "code": null, "e": 25072, "s": 25052, "text": "No compiler needed." }, { "code": null, "e": 25092, "s": 25072, "text": "JavaScript Example:" }, { "code": null, "e": 25103, "s": 25092, "text": "javascript" }, { "code": "<!DOCTYPE html><html> <head> <title></title></head> <body bgcolor=\"white\"> <p>Paragraph 1</p> <script type=\"text/javascript\"> document.bgColor = \"lightblue\"; </script></body><html>", "e": 25303, "s": 25103, "text": null }, { "code": null, "e": 25311, "s": 25303, "text": "Output:" }, { "code": null, "e": 25784, "s": 25311, "text": "AngularJS: AngularJS is an open-source front-end web development framework for creating web applications and has great functionality and support. It was released in the year 2010 by the angular team of Google. It is a constantly developing and expanding framework which provides improved methods for developing web applications. It mainly works on the model view controller (MVC) concept for building apps and supports both dependency injection and data binding features. " }, { "code": null, "e": 25939, "s": 25784, "text": "Easy to work with: All you need to know to work with AngularJS is basics of HTML, CSS and JavaScript, not necessary to be an expert in these technologies." }, { "code": null, "e": 26067, "s": 25939, "text": "Time saving: AngularJS allows us to work with components and hence we can use them again which saves time and unnecessary code." }, { "code": null, "e": 26290, "s": 26067, "text": "Ready to use template: AngularJS is mainly plain HTML, and it mainly makes use of the plain HTML template and passes it to the DOM and then the AngularJS compiler. It traverses the templates and then they are ready to use." }, { "code": null, "e": 26440, "s": 26290, "text": "AngularJS (version 1.5) was replaced by Angular (Typescript) in 2016. They are completely different frameworks. Angular is currently at version 10." }, { "code": null, "e": 26459, "s": 26440, "text": "AngularJS Example:" }, { "code": null, "e": 26470, "s": 26459, "text": "javascript" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body> <center> <div ng-app=\"\"> <h1>{{txt}}</h1> <p> <input type=\"text\" ng-model=\"txt\" /> </p> </div> </center></body> </html>", "e": 26801, "s": 26470, "text": null }, { "code": null, "e": 26811, "s": 26801, "text": "Output: " }, { "code": null, "e": 26857, "s": 26811, "text": "Difference between JavaScript and AngularJS :" }, { "code": null, "e": 26868, "s": 26857, "text": "bunnyram19" }, { "code": null, "e": 26874, "s": 26868, "text": "tim17" }, { "code": null, "e": 26889, "s": 26874, "text": "AngularJS-Misc" }, { "code": null, "e": 26905, "s": 26889, "text": "JavaScript-Misc" }, { "code": null, "e": 26915, "s": 26905, "text": "AngularJS" }, { "code": null, "e": 26934, "s": 26915, "text": "Difference Between" }, { "code": null, "e": 26945, "s": 26934, "text": "JavaScript" }, { "code": null, "e": 26962, "s": 26945, "text": "Web Technologies" }, { "code": null, "e": 26989, "s": 26962, "text": "Web technologies Questions" }, { "code": null, "e": 27087, "s": 26989, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27096, "s": 27087, "text": "Comments" }, { "code": null, "e": 27109, "s": 27096, "text": "Old Comments" }, { "code": null, "e": 27140, "s": 27109, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 27182, "s": 27140, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 27217, "s": 27182, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 27291, "s": 27217, "text": "How to set focus on input field automatically on page load in AngularJS ?" }, { "code": null, "e": 27344, "s": 27291, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 27375, "s": 27344, "text": "Difference between BFS and DFS" }, { "code": null, "e": 27415, "s": 27375, "text": "Class method vs Static method in Python" }, { "code": null, "e": 27447, "s": 27415, "text": "Differences between TCP and UDP" }, { "code": null, "e": 27508, "s": 27447, "text": "Difference between var, let and const keywords in JavaScript" } ]
How To Get The Row Count Of a Pandas DataFrame | Towards Data Science
In today’s short guide we will discuss a few ways for computing the row count of pandas DataFrames. Additionally, we will showcase how to omit null values when deriving the counts. Finally, we will observe the performance of each of the methods introduced in this article and identify the most efficient way for computing the number of rows. First, let’s create an example DataFrame that we’ll reference throughout this guide in order to demonstrate a few concepts. import pandas as pddf = pd.DataFrame({ 'colA':[1, 2, None, 4, 5], 'colB': [None, 'b', 'c', 'd', 'e'], 'colC': [True, False, False, True, None],})print(df) colA colB colC0 1.0 None True1 2.0 b False2 NaN c False3 4.0 d True4 5.0 e None The most simple and clear way to compute the row count of a DataFrame is to use len() built-in method: >>> len(df)5 Note that you can even pass df.index for slightly improved performance (more on this in the final section of the article): >>> len(df.index)5 Alternatively, you can even use pandas.DataFrame.shape that returns a tuple representing the dimensionality of the DataFrame. The first element of the tuple corresponds to the number of rows while the second element represents the number of columns. >>> df.shape[0]5 You can also unpack the result of df.shape and infer the row count as shown below: >>> n_rows, _ = df.shape>>> n_rows5 The third option you have when it comes to computing row counts in pandas is pandas.DataFrame.count() method that returns the count for non-NA entries. Let’s assume that we want to count all the rows which have no null values under a certain column. The following should do the trick for us: >>> df[df.columns[1]].count()4 This method should only be used when you want to ignore null values. If this is not the case then you should use either len() or shape. Now that we know a few different ways for computing the count of rows in DataFrames, it would be interesting to discuss the performance implications around them. To do so, we are going to create a larger DataFrame than the one we used so far in this guide. import numpy as npimport pandas as pddf = pd.DataFrame( np.random.randint(0, 100, size=(10000, 4)), columns=list('ABCD'))print(df) A B C D0 61 38 2 391 96 65 20 472 35 56 97 83 71 31 80 254 20 63 99 34 .. .. .. ..9995 96 81 6 439996 43 22 83 479997 62 92 42 269998 11 48 91 859999 55 47 77 66[10000 rows x 4 columns] In order to evaluate performance, we are going to use timeit which is useful when it comes to timing small bits of Python code. >>> %timeit len(df)548 ns ± 24.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)>>> %timeit len(df.index)358 ns ± 10.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)>>> %timeit df.shape[0]904 ns ± 48 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)>>> %timeit df[df.columns[1]].count()81.9 μs ± 4.91 μs per loop (mean ± std. dev. of 7 runs, 10000 loops each) We can see from the results above that the most efficient way for counting rows in pandas is len() method. By providing just the index (len(df.index)) is even faster. The least efficient way is count() and thus you should only be using this method only if you need to exclude null entries from the counts. In today’s article we discussed how to compute row counts of pandas DataFrames using len() shape and count() methods. Note that count() should only be used if you want to omit null rows at certain column(s). Finally, we discussed the difference of each of these methods in terms of performance. Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You may also like
[ { "code": null, "e": 514, "s": 172, "text": "In today’s short guide we will discuss a few ways for computing the row count of pandas DataFrames. Additionally, we will showcase how to omit null values when deriving the counts. Finally, we will observe the performance of each of the methods introduced in this article and identify the most efficient way for computing the number of rows." }, { "code": null, "e": 638, "s": 514, "text": "First, let’s create an example DataFrame that we’ll reference throughout this guide in order to demonstrate a few concepts." }, { "code": null, "e": 923, "s": 638, "text": "import pandas as pddf = pd.DataFrame({ 'colA':[1, 2, None, 4, 5], 'colB': [None, 'b', 'c', 'd', 'e'], 'colC': [True, False, False, True, None],})print(df) colA colB colC0 1.0 None True1 2.0 b False2 NaN c False3 4.0 d True4 5.0 e None" }, { "code": null, "e": 1026, "s": 923, "text": "The most simple and clear way to compute the row count of a DataFrame is to use len() built-in method:" }, { "code": null, "e": 1039, "s": 1026, "text": ">>> len(df)5" }, { "code": null, "e": 1162, "s": 1039, "text": "Note that you can even pass df.index for slightly improved performance (more on this in the final section of the article):" }, { "code": null, "e": 1181, "s": 1162, "text": ">>> len(df.index)5" }, { "code": null, "e": 1431, "s": 1181, "text": "Alternatively, you can even use pandas.DataFrame.shape that returns a tuple representing the dimensionality of the DataFrame. The first element of the tuple corresponds to the number of rows while the second element represents the number of columns." }, { "code": null, "e": 1448, "s": 1431, "text": ">>> df.shape[0]5" }, { "code": null, "e": 1531, "s": 1448, "text": "You can also unpack the result of df.shape and infer the row count as shown below:" }, { "code": null, "e": 1567, "s": 1531, "text": ">>> n_rows, _ = df.shape>>> n_rows5" }, { "code": null, "e": 1719, "s": 1567, "text": "The third option you have when it comes to computing row counts in pandas is pandas.DataFrame.count() method that returns the count for non-NA entries." }, { "code": null, "e": 1859, "s": 1719, "text": "Let’s assume that we want to count all the rows which have no null values under a certain column. The following should do the trick for us:" }, { "code": null, "e": 1890, "s": 1859, "text": ">>> df[df.columns[1]].count()4" }, { "code": null, "e": 2026, "s": 1890, "text": "This method should only be used when you want to ignore null values. If this is not the case then you should use either len() or shape." }, { "code": null, "e": 2283, "s": 2026, "text": "Now that we know a few different ways for computing the count of rows in DataFrames, it would be interesting to discuss the performance implications around them. To do so, we are going to create a larger DataFrame than the one we used so far in this guide." }, { "code": null, "e": 2681, "s": 2283, "text": "import numpy as npimport pandas as pddf = pd.DataFrame( np.random.randint(0, 100, size=(10000, 4)), columns=list('ABCD'))print(df) A B C D0 61 38 2 391 96 65 20 472 35 56 97 83 71 31 80 254 20 63 99 34 .. .. .. ..9995 96 81 6 439996 43 22 83 479997 62 92 42 269998 11 48 91 859999 55 47 77 66[10000 rows x 4 columns]" }, { "code": null, "e": 2809, "s": 2681, "text": "In order to evaluate performance, we are going to use timeit which is useful when it comes to timing small bits of Python code." }, { "code": null, "e": 3207, "s": 2809, "text": ">>> %timeit len(df)548 ns ± 24.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)>>> %timeit len(df.index)358 ns ± 10.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)>>> %timeit df.shape[0]904 ns ± 48 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)>>> %timeit df[df.columns[1]].count()81.9 μs ± 4.91 μs per loop (mean ± std. dev. of 7 runs, 10000 loops each)" }, { "code": null, "e": 3374, "s": 3207, "text": "We can see from the results above that the most efficient way for counting rows in pandas is len() method. By providing just the index (len(df.index)) is even faster." }, { "code": null, "e": 3513, "s": 3374, "text": "The least efficient way is count() and thus you should only be using this method only if you need to exclude null entries from the counts." }, { "code": null, "e": 3598, "s": 3513, "text": "In today’s article we discussed how to compute row counts of pandas DataFrames using" }, { "code": null, "e": 3604, "s": 3598, "text": "len()" }, { "code": null, "e": 3610, "s": 3604, "text": "shape" }, { "code": null, "e": 3622, "s": 3610, "text": "and count()" }, { "code": null, "e": 3808, "s": 3622, "text": "methods. Note that count() should only be used if you want to omit null rows at certain column(s). Finally, we discussed the difference of each of these methods in terms of performance." }, { "code": null, "e": 3925, "s": 3808, "text": "Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read." } ]
Python - RPC JSON Server
JSON or JavaScript Object Notation is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. The RPC call made based on JSON is able to send data in a much compact and efficient manner than the normal XML based RPC call. The python module jsonrpclib is able to create a simple JSON based server and client. In the below example we create a simple JSON server and create a function in it. This function breaks a bigger list into smaller lists mentioning the length of the argument as well as the argument itself. # server program from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer def findlen(*args): res = [] for arg in args: try: lenval = len(arg) except TypeError: lenval = None res.append((lenval, arg)) return res def main(): server = SimpleJSONRPCServer(('localhost', 1006)) server.register_function(findlen) print("Start server") server.serve_forever() if __name__ == '__main__': main() # Call by client from jsonrpclib import Server def main(): conn = Server('http://localhost:1006') print(conn.findlen(('a','x','d','z'), 11, {'Mt. Abu': 1602, 'Mt. Nanda': 3001,'Mt. Kirubu': 102, 'Mt.Nish': 5710})) if __name__ == '__main__': main() When we run the above program, we get the following output − [[4, [u'a', u'x', u'd', u'z']], [None, 11], [4, {u'Mt. Abu': 1602, u'Mt. Kirubu': 102, u'Mt. Nanda': 3001, u'Mt.Nish': 5710}]] 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2706, "s": 2326, "text": "JSON or JavaScript Object Notation is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. The RPC call made based on JSON is able to send data in a much compact and efficient manner than the normal XML based RPC call.\nThe python module jsonrpclib is able to create a simple JSON based server and client. " }, { "code": null, "e": 2912, "s": 2706, "text": "In the below example we create a simple JSON server and create a function in it. This function breaks a bigger list into smaller lists mentioning the length of the argument as well as the argument itself. " }, { "code": null, "e": 3596, "s": 2912, "text": "# server program\nfrom jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer\n\ndef findlen(*args):\n\n\tres = []\n\tfor arg in args:\n\t\ttry:\n\t\t\tlenval = len(arg)\n\t\texcept TypeError:\n\t\t\tlenval = None\n\t\tres.append((lenval, arg))\n\treturn res\n\ndef main():\n\tserver = SimpleJSONRPCServer(('localhost', 1006))\n\tserver.register_function(findlen)\n\tprint(\"Start server\")\n\tserver.serve_forever()\nif __name__ == '__main__': \n main()\n\n\n\n# Call by client\nfrom jsonrpclib import Server\ndef main():\n conn = Server('http://localhost:1006')\n print(conn.findlen(('a','x','d','z'), 11, {'Mt. Abu': 1602, 'Mt. Nanda': 3001,'Mt. Kirubu': 102, 'Mt.Nish': 5710}))\nif __name__ == '__main__':\n main()" }, { "code": null, "e": 3657, "s": 3596, "text": "When we run the above program, we get the following output −" }, { "code": null, "e": 3785, "s": 3657, "text": "[[4, [u'a', u'x', u'd', u'z']], [None, 11], [4, {u'Mt. Abu': 1602, u'Mt. Kirubu': 102, u'Mt. Nanda': 3001, u'Mt.Nish': 5710}]]\n" }, { "code": null, "e": 3822, "s": 3785, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3838, "s": 3822, "text": " Malhar Lathkar" }, { "code": null, "e": 3871, "s": 3838, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3890, "s": 3871, "text": " Arnab Chakraborty" }, { "code": null, "e": 3925, "s": 3890, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3947, "s": 3925, "text": " In28Minutes Official" }, { "code": null, "e": 3981, "s": 3947, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4009, "s": 3981, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4044, "s": 4009, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4058, "s": 4044, "text": " Lets Kode It" }, { "code": null, "e": 4091, "s": 4058, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4108, "s": 4091, "text": " Abhilash Nelson" }, { "code": null, "e": 4115, "s": 4108, "text": " Print" }, { "code": null, "e": 4126, "s": 4115, "text": " Add Notes" } ]
Neo4j Create Constraint - GeeksforGeeks
03 Sep, 2019 The neo4j constraint helps user to nor enter in wrong kind of data. When the constraint is applied and the user by mistake entering the wrong kind of data then it will show an error message. In the neo4j there are two kind of constraint one is uniqueness constraints and other one is property existence constraints.Below is the example of both the constraint with the example:Suppose there is already below database is exist. CREATE(CPP:Language{id:001, Designer: "Bjarne Stroustrup", YOE: 1985}) CREATE(C:Language {id:002, Designer: "Dennis Ritchie", YOE: 1972}) CREATE(Python:Language {id:003, Designer: "Guido van Rossum ", YOE: 1990}) CREATE(Java:Language {id:004, Designer: "James Gosling", YOE: 1995}) CREATE(CSharp:Language {id:005, Designer: "Microsoft", YOE: 2000}) RETURN CPP, C, Python, Java, CSharp Output: Query:CREATE CONSTRAINT ON(l:Language) ASSERT l.id IS UNIQUEOutput: CREATE CONSTRAINT ON(l:Language) ASSERT l.id IS UNIQUE Output: View the Constraint::schemaOutput: :schema Output: Test the Constraint:Here we will try to add another node into that database with a redundant id value(004).Query:CREATE(Neo4j:Language {id:004, Designer: "Neo4j", YOE: 2012})Output: CREATE(Neo4j:Language {id:004, Designer: "Neo4j", YOE: 2012}) Output: Query:CREATE CONSTRAINT ON (label) ASSERT exists(node)Note:Property existence constraints are only available in the Neo4j Enterprise Edition.My Personal Notes arrow_drop_upSave CREATE CONSTRAINT ON (label) ASSERT exists(node) Note:Property existence constraints are only available in the Neo4j Enterprise Edition. DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Second Normal Form (2NF) Introduction of Relational Algebra in DBMS What is Temporary Table in SQL? Types of Functional dependencies in DBMS Difference between Where and Having Clause in SQL Relational Model in DBMS Difference between OLAP and OLTP in DBMS KDD Process in Data Mining MySQL | Regular expressions (Regexp) Difference between File System and DBMS
[ { "code": null, "e": 23913, "s": 23885, "text": "\n03 Sep, 2019" }, { "code": null, "e": 24339, "s": 23913, "text": "The neo4j constraint helps user to nor enter in wrong kind of data. When the constraint is applied and the user by mistake entering the wrong kind of data then it will show an error message. In the neo4j there are two kind of constraint one is uniqueness constraints and other one is property existence constraints.Below is the example of both the constraint with the example:Suppose there is already below database is exist." }, { "code": null, "e": 24730, "s": 24339, "text": "CREATE(CPP:Language{id:001, Designer: \"Bjarne Stroustrup\", YOE: 1985}) \nCREATE(C:Language {id:002, Designer: \"Dennis Ritchie\", YOE: 1972}) \nCREATE(Python:Language {id:003, Designer: \"Guido van Rossum \", YOE: 1990}) \nCREATE(Java:Language {id:004, Designer: \"James Gosling\", YOE: 1995}) \nCREATE(CSharp:Language {id:005, Designer: \"Microsoft\", YOE: 2000})\nRETURN CPP, C, Python, Java, CSharp \n" }, { "code": null, "e": 24738, "s": 24730, "text": "Output:" }, { "code": null, "e": 24806, "s": 24738, "text": "Query:CREATE CONSTRAINT ON(l:Language) ASSERT l.id IS UNIQUEOutput:" }, { "code": null, "e": 24861, "s": 24806, "text": "CREATE CONSTRAINT ON(l:Language) ASSERT l.id IS UNIQUE" }, { "code": null, "e": 24869, "s": 24861, "text": "Output:" }, { "code": null, "e": 24904, "s": 24869, "text": "View the Constraint::schemaOutput:" }, { "code": null, "e": 24912, "s": 24904, "text": ":schema" }, { "code": null, "e": 24920, "s": 24912, "text": "Output:" }, { "code": null, "e": 25102, "s": 24920, "text": "Test the Constraint:Here we will try to add another node into that database with a redundant id value(004).Query:CREATE(Neo4j:Language {id:004, Designer: \"Neo4j\", YOE: 2012})Output:" }, { "code": null, "e": 25164, "s": 25102, "text": "CREATE(Neo4j:Language {id:004, Designer: \"Neo4j\", YOE: 2012})" }, { "code": null, "e": 25172, "s": 25164, "text": "Output:" }, { "code": null, "e": 25349, "s": 25172, "text": "Query:CREATE CONSTRAINT ON (label) ASSERT exists(node)Note:Property existence constraints are only available in the Neo4j Enterprise Edition.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 25398, "s": 25349, "text": "CREATE CONSTRAINT ON (label) ASSERT exists(node)" }, { "code": null, "e": 25486, "s": 25398, "text": "Note:Property existence constraints are only available in the Neo4j Enterprise Edition." }, { "code": null, "e": 25491, "s": 25486, "text": "DBMS" }, { "code": null, "e": 25496, "s": 25491, "text": "DBMS" }, { "code": null, "e": 25594, "s": 25496, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25603, "s": 25594, "text": "Comments" }, { "code": null, "e": 25616, "s": 25603, "text": "Old Comments" }, { "code": null, "e": 25641, "s": 25616, "text": "Second Normal Form (2NF)" }, { "code": null, "e": 25684, "s": 25641, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 25716, "s": 25684, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 25757, "s": 25716, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 25807, "s": 25757, "text": "Difference between Where and Having Clause in SQL" }, { "code": null, "e": 25832, "s": 25807, "text": "Relational Model in DBMS" }, { "code": null, "e": 25873, "s": 25832, "text": "Difference between OLAP and OLTP in DBMS" }, { "code": null, "e": 25900, "s": 25873, "text": "KDD Process in Data Mining" }, { "code": null, "e": 25937, "s": 25900, "text": "MySQL | Regular expressions (Regexp)" } ]
Hive - View and Indexes
This chapter describes how to create and manage views. Views are generated based on user requirements. You can save any result set data as a view. The usage of view in Hive is same as that of the view in SQL. It is a standard RDBMS concept. We can execute all DML operations on a view. You can create a view at the time of executing a SELECT statement. The syntax is as follows: CREATE VIEW [IF NOT EXISTS] view_name [(column_name [COMMENT column_comment], ...) ] [COMMENT table_comment] AS SELECT ... Let us take an example for view. Assume employee table as given below, with the fields Id, Name, Salary, Designation, and Dept. Generate a query to retrieve the employee details who earn a salary of more than Rs 30000. We store the result in a view named emp_30000. +------+--------------+-------------+-------------------+--------+ | ID | Name | Salary | Designation | Dept | +------+--------------+-------------+-------------------+--------+ |1201 | Gopal | 45000 | Technical manager | TP | |1202 | Manisha | 45000 | Proofreader | PR | |1203 | Masthanvali | 40000 | Technical writer | TP | |1204 | Krian | 40000 | Hr Admin | HR | |1205 | Kranthi | 30000 | Op Admin | Admin | +------+--------------+-------------+-------------------+--------+ The following query retrieves the employee details using the above scenario: hive> CREATE VIEW emp_30000 AS SELECT * FROM employee WHERE salary>30000; Use the following syntax to drop a view: DROP VIEW view_name The following query drops a view named as emp_30000: hive> DROP VIEW emp_30000; An Index is nothing but a pointer on a particular column of a table. Creating an index means creating a pointer on a particular column of a table. Its syntax is as follows: CREATE INDEX index_name ON TABLE base_table_name (col_name, ...) AS 'index.handler.class.name' [WITH DEFERRED REBUILD] [IDXPROPERTIES (property_name=property_value, ...)] [IN TABLE index_table_name] [PARTITIONED BY (col_name, ...)] [ [ ROW FORMAT ...] STORED AS ... | STORED BY ... ] [LOCATION hdfs_path] [TBLPROPERTIES (...)] Let us take an example for index. Use the same employee table that we have used earlier with the fields Id, Name, Salary, Designation, and Dept. Create an index named index_salary on the salary column of the employee table. The following query creates an index: hive> CREATE INDEX inedx_salary ON TABLE employee(salary) AS 'org.apache.hadoop.hive.ql.index.compact.CompactIndexHandler'; It is a pointer to the salary column. If the column is modified, the changes are stored using an index value. The following syntax is used to drop an index: DROP INDEX <index_name> ON <table_name> The following query drops an index named index_salary: hive> DROP INDEX index_salary ON employee; 50 Lectures 4 hours Navdeep Kaur 67 Lectures 4 hours Bigdata Engineer 109 Lectures 2 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2236, "s": 1950, "text": "This chapter describes how to create and manage views. Views are generated based on user requirements. You can save any result set data as a view. The usage of view in Hive is same as that of the view in SQL. It is a standard RDBMS concept. We can execute all DML operations on a view." }, { "code": null, "e": 2329, "s": 2236, "text": "You can create a view at the time of executing a SELECT statement. The syntax is as follows:" }, { "code": null, "e": 2452, "s": 2329, "text": "CREATE VIEW [IF NOT EXISTS] view_name [(column_name [COMMENT column_comment], ...) ]\n[COMMENT table_comment]\nAS SELECT ..." }, { "code": null, "e": 2718, "s": 2452, "text": "Let us take an example for view. Assume employee table as given below, with the fields Id, Name, Salary, Designation, and Dept. Generate a query to retrieve the employee details who earn a salary of more than Rs 30000. We store the result in a view named emp_30000." }, { "code": null, "e": 3322, "s": 2718, "text": "+------+--------------+-------------+-------------------+--------+\n| ID | Name | Salary | Designation | Dept |\n+------+--------------+-------------+-------------------+--------+\n|1201 | Gopal | 45000 | Technical manager | TP |\n|1202 | Manisha | 45000 | Proofreader | PR |\n|1203 | Masthanvali | 40000 | Technical writer | TP |\n|1204 | Krian | 40000 | Hr Admin | HR |\n|1205 | Kranthi | 30000 | Op Admin | Admin |\n+------+--------------+-------------+-------------------+--------+\n" }, { "code": null, "e": 3399, "s": 3322, "text": "The following query retrieves the employee details using the above scenario:" }, { "code": null, "e": 3474, "s": 3399, "text": "hive> CREATE VIEW emp_30000 AS\nSELECT * FROM employee\nWHERE salary>30000;\n" }, { "code": null, "e": 3515, "s": 3474, "text": "Use the following syntax to drop a view:" }, { "code": null, "e": 3536, "s": 3515, "text": "DROP VIEW view_name\n" }, { "code": null, "e": 3589, "s": 3536, "text": "The following query drops a view named as emp_30000:" }, { "code": null, "e": 3617, "s": 3589, "text": "hive> DROP VIEW emp_30000;\n" }, { "code": null, "e": 3790, "s": 3617, "text": "An Index is nothing but a pointer on a particular column of a table. Creating an index means creating a pointer on a particular column of a table. Its syntax is as follows:" }, { "code": null, "e": 4124, "s": 3790, "text": "CREATE INDEX index_name\nON TABLE base_table_name (col_name, ...)\nAS 'index.handler.class.name'\n[WITH DEFERRED REBUILD]\n[IDXPROPERTIES (property_name=property_value, ...)]\n[IN TABLE index_table_name]\n[PARTITIONED BY (col_name, ...)]\n[\n [ ROW FORMAT ...] STORED AS ...\n | STORED BY ...\n]\n[LOCATION hdfs_path]\n[TBLPROPERTIES (...)]\n" }, { "code": null, "e": 4348, "s": 4124, "text": "Let us take an example for index. Use the same employee table that we have used earlier with the fields Id, Name, Salary, Designation, and Dept. Create an index named index_salary on the salary column of the employee table." }, { "code": null, "e": 4386, "s": 4348, "text": "The following query creates an index:" }, { "code": null, "e": 4511, "s": 4386, "text": "hive> CREATE INDEX inedx_salary ON TABLE employee(salary)\nAS 'org.apache.hadoop.hive.ql.index.compact.CompactIndexHandler';\n" }, { "code": null, "e": 4621, "s": 4511, "text": "It is a pointer to the salary column. If the column is modified, the changes are stored using an index value." }, { "code": null, "e": 4668, "s": 4621, "text": "The following syntax is used to drop an index:" }, { "code": null, "e": 4709, "s": 4668, "text": "DROP INDEX <index_name> ON <table_name>\n" }, { "code": null, "e": 4764, "s": 4709, "text": "The following query drops an index named index_salary:" }, { "code": null, "e": 4808, "s": 4764, "text": "hive> DROP INDEX index_salary ON employee;\n" }, { "code": null, "e": 4841, "s": 4808, "text": "\n 50 Lectures \n 4 hours \n" }, { "code": null, "e": 4855, "s": 4841, "text": " Navdeep Kaur" }, { "code": null, "e": 4888, "s": 4855, "text": "\n 67 Lectures \n 4 hours \n" }, { "code": null, "e": 4906, "s": 4888, "text": " Bigdata Engineer" }, { "code": null, "e": 4940, "s": 4906, "text": "\n 109 Lectures \n 2 hours \n" }, { "code": null, "e": 4958, "s": 4940, "text": " Bigdata Engineer" }, { "code": null, "e": 4965, "s": 4958, "text": " Print" }, { "code": null, "e": 4976, "s": 4965, "text": " Add Notes" } ]
What is Regular Expressions?
Regular expressions are an important notation for defining patterns. Each pattern connects a set of strings. Therefore regular expressions will give as names for sets of strings. It supports an appropriate and useful notation for describing tokens. Regular Expressions define the language accepted by finite Automata (Transition Diagram). Regular Expressions are defined over an alphabet ∑. If R is a Regular Expression, therefore L(R) represents language denoted by the regular expression. Language − It is a collection of strings over some fixed alphabet. The empty string can be indicated by ε. Example − If L (Language) = set of strings of 0’s & 1’s of length two then L = {00, 01, 10, 11} Example − If L = {1} then L*=L0∪L1∪L2∪..... Here * can be 0, 1, 2, 3........... ∴ L*={ε}∪{1}∪{11}∪..... ∴ L*={ε,1,11,111,.....} The various operations on the regular language are as follows − If L1={00,10} & L2={01,11} Kleene suggests regular expression in the 1950s with the primary operation for a union, concatenation, and Kleene closure. There is some notational extension specified that are directly in use − One or more instance − Unary postfix operator + displays positive closure of a regular expression and its language. It defined that if a is the regular expression, then (a) + indicates the language (L(a) +. There are two algebraic laws r∗ = r+|e and r+ =rr∗ = r∗r relate the positive closure and Kleene closure. One or more instance − Unary postfix operator + displays positive closure of a regular expression and its language. It defined that if a is the regular expression, then (a) + indicates the language (L(a) +. There are two algebraic laws r∗ = r+|e and r+ =rr∗ = r∗r relate the positive closure and Kleene closure. Zero or one instance − Unary postfix operator? define zero or one appearance. It define that r? is similar to r|e or L(r?) = L(r) U {e}. This operator has the equal precedence and associativity as * and +./ Zero or one instance − Unary postfix operator? define zero or one appearance. It define that r? is similar to r|e or L(r?) = L(r) U {e}. This operator has the equal precedence and associativity as * and +./
[ { "code": null, "e": 1241, "s": 1062, "text": "Regular expressions are an important notation for defining patterns. Each pattern connects a set of strings. Therefore regular expressions will give as names for sets of strings." }, { "code": null, "e": 1401, "s": 1241, "text": "It supports an appropriate and useful notation for describing tokens. Regular Expressions define the language accepted by finite Automata (Transition Diagram)." }, { "code": null, "e": 1453, "s": 1401, "text": "Regular Expressions are defined over an alphabet ∑." }, { "code": null, "e": 1553, "s": 1453, "text": "If R is a Regular Expression, therefore L(R) represents language denoted by the regular expression." }, { "code": null, "e": 1660, "s": 1553, "text": "Language − It is a collection of strings over some fixed alphabet. The empty string can be indicated by ε." }, { "code": null, "e": 1730, "s": 1660, "text": "Example − If L (Language) = set of strings of 0’s & 1’s of length two" }, { "code": null, "e": 1756, "s": 1730, "text": "then L = {00, 01, 10, 11}" }, { "code": null, "e": 1777, "s": 1756, "text": "Example − If L = {1}" }, { "code": null, "e": 1884, "s": 1777, "text": "then L*=L0∪L1∪L2∪..... Here * can be 0, 1, 2, 3...........\n∴ L*={ε}∪{1}∪{11}∪.....\n∴ L*={ε,1,11,111,.....}" }, { "code": null, "e": 1948, "s": 1884, "text": "The various operations on the regular language are as follows −" }, { "code": null, "e": 1975, "s": 1948, "text": "If L1={00,10} & L2={01,11}" }, { "code": null, "e": 2098, "s": 1975, "text": "Kleene suggests regular expression in the 1950s with the primary operation for a union, concatenation, and Kleene closure." }, { "code": null, "e": 2170, "s": 2098, "text": "There is some notational extension specified that are directly in use −" }, { "code": null, "e": 2482, "s": 2170, "text": "One or more instance − Unary postfix operator + displays positive closure of a regular expression and its language. It defined that if a is the regular expression, then (a) + indicates the language (L(a) +. There are two algebraic laws r∗ = r+|e and r+ =rr∗ = r∗r relate the positive closure and Kleene closure." }, { "code": null, "e": 2794, "s": 2482, "text": "One or more instance − Unary postfix operator + displays positive closure of a regular expression and its language. It defined that if a is the regular expression, then (a) + indicates the language (L(a) +. There are two algebraic laws r∗ = r+|e and r+ =rr∗ = r∗r relate the positive closure and Kleene closure." }, { "code": null, "e": 3001, "s": 2794, "text": "Zero or one instance − Unary postfix operator? define zero or one appearance. It define that r? is similar to r|e or L(r?) = L(r) U {e}. This operator has the equal precedence and associativity as * and +./" }, { "code": null, "e": 3208, "s": 3001, "text": "Zero or one instance − Unary postfix operator? define zero or one appearance. It define that r? is similar to r|e or L(r?) = L(r) U {e}. This operator has the equal precedence and associativity as * and +./" } ]
How to sum the score of students with the same name in MySQL with ORDER BY?
For this, use ORDER BY along with GROUP BY clause. Let us first create a table with Student Name and Score − mysql> create table countRowValueDemo -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(20), -> StudentMathScore int -> ); Query OK, 0 rows affected (0.71 sec) Following is the query to insert records in the table using insert command − mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('Larry',45); Query OK, 1 row affected (0.19 sec) mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('Mike',56); Query OK, 1 row affected (0.16 sec) mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('John',60); Query OK, 1 row affected (0.15 sec) mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('David',40); Query OK, 1 row affected (0.24 sec) mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('David',70); Query OK, 1 row affected (0.12 sec) mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('John',80); Query OK, 1 row affected (0.13 sec) mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('David',88); Query OK, 1 row affected (0.17 sec) Following is the query to display all records from the table using select statement − mysql> select * from countRowValueDemo; This will produce the following output − +-----------+-------------+------------------+ | StudentId | StudentName | StudentMathScore | +-----------+-------------+------------------+ | 1 | Larry | 45 | | 2 | Mike | 56 | | 3 | John | 60 | | 4 | David | 40 | | 5 | David | 70 | | 6 | John | 80 | | 7 | David | 88 | +-----------+-------------+------------------+ 7 rows in set (0.00 sec) Case 1: Descending order (Sum) Following is the query to sum the score of students with similar name. The result will be displayed in descending order − mysql> select StudentName, -> sum(StudentMathScore) AS TOTAL_SCORE -> from countRowValueDemo -> group by StudentName -> order by sum(StudentMathScore) desc; This will produce the following output − +-------------+-------------+ | StudentName | TOTAL_SCORE | +-------------+-------------+ | David | 198 | | John | 140 | | Mike | 56 | | Larry | 45 | +-------------+-------------+ 4 rows in set (0.00 sec) Case 2: Ascending order (Sum) Following is the query to sum the score of students with similar names. The result will be displayed in descending order − mysql> select StudentName, -> sum(StudentMathScore) AS TOTAL_SCORE -> from countRowValueDemo -> group by StudentName -> order by sum(StudentMathScore); This will produce the following output − +-------------+-------------+ | StudentName | TOTAL_SCORE | +-------------+-------------+ | Larry | 45 | | Mike | 56 | | John | 140 | | David | 198 | +-------------+-------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1171, "s": 1062, "text": "For this, use ORDER BY along with GROUP BY clause. Let us first create a table with Student Name and Score −" }, { "code": null, "e": 1378, "s": 1171, "text": "mysql> create table countRowValueDemo\n -> (\n -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> StudentName varchar(20),\n -> StudentMathScore int\n -> );\nQuery OK, 0 rows affected (0.71 sec)" }, { "code": null, "e": 1455, "s": 1378, "text": "Following is the query to insert records in the table using insert command −" }, { "code": null, "e": 2319, "s": 1455, "text": "mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('Larry',45);\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('Mike',56);\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('John',60);\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('David',40);\nQuery OK, 1 row affected (0.24 sec)\n\nmysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('David',70);\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('John',80);\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('David',88);\nQuery OK, 1 row affected (0.17 sec)" }, { "code": null, "e": 2405, "s": 2319, "text": "Following is the query to display all records from the table using select statement −" }, { "code": null, "e": 2445, "s": 2405, "text": "mysql> select * from countRowValueDemo;" }, { "code": null, "e": 2486, "s": 2445, "text": "This will produce the following output −" }, { "code": null, "e": 3028, "s": 2486, "text": "+-----------+-------------+------------------+\n| StudentId | StudentName | StudentMathScore |\n+-----------+-------------+------------------+\n| 1 | Larry | 45 |\n| 2 | Mike | 56 |\n| 3 | John | 60 |\n| 4 | David | 40 |\n| 5 | David | 70 |\n| 6 | John | 80 |\n| 7 | David | 88 |\n+-----------+-------------+------------------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 3059, "s": 3028, "text": "Case 1: Descending order (Sum)" }, { "code": null, "e": 3181, "s": 3059, "text": "Following is the query to sum the score of students with similar name. The result will be displayed in descending order −" }, { "code": null, "e": 3350, "s": 3181, "text": "mysql> select StudentName,\n -> sum(StudentMathScore) AS TOTAL_SCORE\n -> from countRowValueDemo\n -> group by StudentName\n -> order by sum(StudentMathScore) desc;" }, { "code": null, "e": 3391, "s": 3350, "text": "This will produce the following output −" }, { "code": null, "e": 3656, "s": 3391, "text": "+-------------+-------------+\n| StudentName | TOTAL_SCORE |\n+-------------+-------------+\n| David | 198 |\n| John | 140 |\n| Mike | 56 |\n| Larry | 45 |\n+-------------+-------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 3686, "s": 3656, "text": "Case 2: Ascending order (Sum)" }, { "code": null, "e": 3809, "s": 3686, "text": "Following is the query to sum the score of students with similar names. The result will be displayed in descending order −" }, { "code": null, "e": 3973, "s": 3809, "text": "mysql> select StudentName,\n -> sum(StudentMathScore) AS TOTAL_SCORE\n -> from countRowValueDemo\n -> group by StudentName\n -> order by sum(StudentMathScore);" }, { "code": null, "e": 4014, "s": 3973, "text": "This will produce the following output −" }, { "code": null, "e": 4279, "s": 4014, "text": "+-------------+-------------+\n| StudentName | TOTAL_SCORE |\n+-------------+-------------+\n| Larry | 45 |\n| Mike | 56 |\n| John | 140 |\n| David | 198 |\n+-------------+-------------+\n4 rows in set (0.00 sec)" } ]
Jupyter QtConsole - Getting Started
In this chapter, let us understand how to get started with QtConsole. This chapter will give you an overview about this software and explains its installation steps. The Qt console is a GUI application similar to IPython terminal. However, it provides a number of enhancements which are not available in text based IPython terminal. The enhance features are inline figures, multi-line editing with syntax highlighting, graphical calltips, etc. The Qt console can use any Jupyter kernel, default being IPython kernel. Jupyter QtConsole is a part of Project Jupyter. Anaconda distribution is already having QTconsole application in it. In order to install it individually, use pip command as shown below − pip3 install qtconsole You can also use the conda command for this purpose − conda install qtconsole You can start Jupyter console from Anaconda navigator. To start it from the command line, you should use the following command, either from the Windows command prompt or Anaconda prompt − jupyter qtonsole You get a terminal similar to IPython terminal with first In[] prompt. You can now execute any Python expression exactly like we do in IPython terminal or Jupyter notebook 22 Lectures 49 mins Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2826, "s": 2660, "text": "In this chapter, let us understand how to get started with QtConsole. This chapter will give you an overview about this software and explains its installation steps." }, { "code": null, "e": 3177, "s": 2826, "text": "The Qt console is a GUI application similar to IPython terminal. However, it provides a number of enhancements which are not available in text based IPython terminal. The enhance features are inline figures, multi-line editing with syntax highlighting, graphical calltips, etc. The Qt console can use any Jupyter kernel, default being IPython kernel." }, { "code": null, "e": 3364, "s": 3177, "text": "Jupyter QtConsole is a part of Project Jupyter. Anaconda distribution is already having QTconsole application in it. In order to install it individually, use pip command as shown below −" }, { "code": null, "e": 3388, "s": 3364, "text": "pip3 install qtconsole\n" }, { "code": null, "e": 3442, "s": 3388, "text": "You can also use the conda command for this purpose −" }, { "code": null, "e": 3467, "s": 3442, "text": "conda install qtconsole\n" }, { "code": null, "e": 3655, "s": 3467, "text": "You can start Jupyter console from Anaconda navigator. To start it from the command line, you should use the following command, either from the Windows command prompt or Anaconda prompt −" }, { "code": null, "e": 3673, "s": 3655, "text": "jupyter qtonsole\n" }, { "code": null, "e": 3845, "s": 3673, "text": "You get a terminal similar to IPython terminal with first In[] prompt. You can now execute any Python expression exactly like we do in IPython terminal or Jupyter notebook" }, { "code": null, "e": 3877, "s": 3845, "text": "\n 22 Lectures \n 49 mins\n" }, { "code": null, "e": 3895, "s": 3877, "text": " Bigdata Engineer" }, { "code": null, "e": 3902, "s": 3895, "text": " Print" }, { "code": null, "e": 3913, "s": 3902, "text": " Add Notes" } ]
ip6tables - Unix, Linux Command
Each chain is a list of rules which can match a set of packets. Each rule specifies what to do with a packet that matches. This is called a ‘target’, which may be a jump to a user-defined chain in the same table. ACCEPT means to let the packet through. DROP means to drop the packet on the floor. QUEUE means to pass the packet to userspace. (How the packet can be received by a userspace process differs by the particular queue handler. 2.4.x and 2.6.x kernels up to 2.6.13 include the ip_queue queue handler. Kernels 2.6.14 and later additionally include the nfnetlink_queue queue handler. Packets with a target of QUEUE will be sent to queue number ’0’ in this case. Please also see the NFQUEUE target as described later in this man page.) RETURN means stop traversing this chain and resume at the next rule in the previous (calling) chain. If the end of a built-in chain is reached or a rule in a built-in chain with target RETURN is matched, the target specified by the chain policy determines the fate of the packet. The tables are as follows: ip6tables -t mangle -n -L ip6tables -L -v The following are included in the base package, and most of these can be preceded by a ! to invert the sense of the match. ip6tables -p ipv6-icmp -h ip6tables -A FORWARD -p tcp --tcp-flags SYN,ACK,FIN,RST SYN icmp6-no-route no-route icmp6-adm-prohibited adm-prohibited icmp6-addr-unreachable addr-unreach icmp6-port-unreachable port-unreach The other main difference is that -i refers to the input interface; -o refers to the output interface, and both are available for packets entering the FORWARD chain. There are several other changes in ip6tables. ip6tables (8) ip6tables (8) ip6tables (8) ip6tables (8) iptables (8) iptables (8) iptables (8) iptables (8) iptables (8) iptables (8) Marc Boucher made Rusty abandon ipnatctl by lobbying for a generic packet selection framework in iptables, then wrote the mangle table, the owner match, the mark stuff, and ran around doing cool stuff everywhere. James Morris wrote the TOS target, and tos match. Jozsef Kadlecsik wrote the REJECT target. Harald Welte wrote the ULOG and NFQUEUE target, the new libiptc, aswell as TTL match+target and libipulog. The Netfilter Core Team is: Marc Boucher, Martin Josefsson, Jozsef Kadlecsik, James Morris, Harald Welte and Rusty Russell. ip6tables man page created by Andras Kis-Szabo, based on iptables man page written by Herve Eychenne <rv@wallfire.org>. Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10794, "s": 10577, "text": "\nEach chain is a list of rules which can match a set of packets. Each\nrule specifies what to do with a packet that matches. This is called\na ‘target’, which may be a jump to a user-defined chain in the same\ntable.\n" }, { "code": null, "e": 11616, "s": 10796, "text": "\nACCEPT means to let the packet through.\nDROP means to drop the packet on the floor.\nQUEUE means to pass the packet to userspace. (How the packet can be received\nby a userspace process differs by the particular queue handler. 2.4.x\nand 2.6.x kernels up to 2.6.13 include the\n ip_queue\nqueue handler. Kernels 2.6.14 and later additionally include the\n nfnetlink_queue\nqueue handler. Packets with a target of QUEUE will be sent to queue number ’0’\nin this case. Please also see the\n NFQUEUE\ntarget as described later in this man page.)\nRETURN means stop traversing this chain and resume at the next rule in the\nprevious (calling) chain. If the end of a built-in chain is reached\nor a rule in a built-in chain with target\nRETURN is matched, the target specified by the chain policy determines the\nfate of the packet.\n" }, { "code": null, "e": 11645, "s": 11616, "text": "\nThe tables are as follows:\n" }, { "code": null, "e": 11673, "s": 11645, "text": " ip6tables -t mangle -n -L\n" }, { "code": null, "e": 11691, "s": 11673, "text": " ip6tables -L -v\n" }, { "code": null, "e": 11816, "s": 11691, "text": "\nThe following are included in the base package, and most of these can\nbe preceded by a\n! to invert the sense of the match.\n" }, { "code": null, "e": 11844, "s": 11816, "text": " ip6tables -p ipv6-icmp -h\n" }, { "code": null, "e": 11906, "s": 11844, "text": " ip6tables -A FORWARD -p tcp --tcp-flags SYN,ACK,FIN,RST SYN\n" }, { "code": null, "e": 12055, "s": 11906, "text": " icmp6-no-route \n no-route \n icmp6-adm-prohibited \n adm-prohibited \n icmp6-addr-unreachable \n addr-unreach \n icmp6-port-unreachable \n port-unreach \n" }, { "code": null, "e": 12271, "s": 12057, "text": "\nThe other main difference is that\n-i refers to the input interface;\n-o refers to the output interface, and both are available for packets\nentering the\nFORWARD chain.\nThere are several other changes in ip6tables.\n" }, { "code": null, "e": 12285, "s": 12271, "text": "ip6tables (8)" }, { "code": null, "e": 12299, "s": 12285, "text": "ip6tables (8)" }, { "code": null, "e": 12313, "s": 12299, "text": "ip6tables (8)" }, { "code": null, "e": 12327, "s": 12313, "text": "ip6tables (8)" }, { "code": null, "e": 12340, "s": 12327, "text": "iptables (8)" }, { "code": null, "e": 12353, "s": 12340, "text": "iptables (8)" }, { "code": null, "e": 12366, "s": 12353, "text": "iptables (8)" }, { "code": null, "e": 12379, "s": 12366, "text": "iptables (8)" }, { "code": null, "e": 12392, "s": 12379, "text": "iptables (8)" }, { "code": null, "e": 12405, "s": 12392, "text": "iptables (8)" }, { "code": null, "e": 12620, "s": 12405, "text": "\nMarc Boucher made Rusty abandon ipnatctl by lobbying for a generic packet\nselection framework in iptables, then wrote the mangle table, the owner match,\nthe mark stuff, and ran around doing cool stuff everywhere.\n" }, { "code": null, "e": 12672, "s": 12620, "text": "\nJames Morris wrote the TOS target, and tos match.\n" }, { "code": null, "e": 12716, "s": 12672, "text": "\nJozsef Kadlecsik wrote the REJECT target.\n" }, { "code": null, "e": 12825, "s": 12716, "text": "\nHarald Welte wrote the ULOG and NFQUEUE target, the new libiptc, aswell as TTL match+target and libipulog.\n" }, { "code": null, "e": 12951, "s": 12825, "text": "\nThe Netfilter Core Team is: Marc Boucher, Martin Josefsson, Jozsef Kadlecsik,\nJames Morris, Harald Welte and Rusty Russell.\n" }, { "code": null, "e": 13082, "s": 12951, "text": "\nip6tables man page created by Andras Kis-Szabo, based on\niptables man page written by Herve Eychenne <rv@wallfire.org>.\n\n\n\n\n\n\n\n\n\n" }, { "code": null, "e": 13099, "s": 13082, "text": "\nAdvertisements\n" }, { "code": null, "e": 13134, "s": 13099, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 13162, "s": 13134, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 13196, "s": 13162, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 13213, "s": 13196, "text": " Frahaan Hussain" }, { "code": null, "e": 13246, "s": 13213, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 13257, "s": 13246, "text": " Pradeep D" }, { "code": null, "e": 13292, "s": 13257, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13308, "s": 13292, "text": " Musab Zayadneh" }, { "code": null, "e": 13341, "s": 13308, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 13353, "s": 13341, "text": " GUHARAJANM" }, { "code": null, "e": 13385, "s": 13353, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 13393, "s": 13385, "text": " Uplatz" }, { "code": null, "e": 13400, "s": 13393, "text": " Print" }, { "code": null, "e": 13411, "s": 13400, "text": " Add Notes" } ]
How to define jQuery function ?
19 Feb, 2020 Defining the function in jQuery is different from JavaScript, the syntax is totally different. A function is a set of statements that takes input, do some specific computation and produce output. Basically, a function is a set of statements that performs some specific task or does some computation and then return the result to the user.The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can call that function. Syntax: $.fn.myFunction = function(){} Below examples illustrate the function definition in jQuery: Example 1: <!DOCTYPE html> <html> <head> <title> How to Define jQuery function ? </title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script> <script> $(document).ready(function() { $.fn.myFunction = function() { document.getElementById("geeks").innerHTML = "JQuery function is defined!"; } $(".gfg").click(function(){ $.fn.myFunction(); }); }); </script></head> <body style="text-align:center"> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> Defining function in jQuery </h3> <p id="geeks"></p> <button type="button" class="gfg"> Click </button></body> </html> Output: Example 2: <!DOCTYPE html> <html> <head> <title> How to Define jQuery function ? </title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script> <script> $(document).ready(function() { $.fn.myFunction = function() { alert('JQuery function is defined!'); } $(".gfg").click(function(){ $.fn.myFunction(); }); }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> Defining function in jQuery </h3> <button type="button" class="gfg"> Click </button></body> </html> Output: jQuery-Misc JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Form validation using jQuery How to Dynamically Add/Remove Table Rows using jQuery ? jQuery | children() with Examples Scroll to the top of the page using JavaScript/jQuery How to get the value in an input text box using jQuery ? 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 fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Feb, 2020" }, { "code": null, "e": 559, "s": 28, "text": "Defining the function in jQuery is different from JavaScript, the syntax is totally different. A function is a set of statements that takes input, do some specific computation and produce output. Basically, a function is a set of statements that performs some specific task or does some computation and then return the result to the user.The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can call that function." }, { "code": null, "e": 567, "s": 559, "text": "Syntax:" }, { "code": null, "e": 598, "s": 567, "text": "$.fn.myFunction = function(){}" }, { "code": null, "e": 659, "s": 598, "text": "Below examples illustrate the function definition in jQuery:" }, { "code": null, "e": 670, "s": 659, "text": "Example 1:" }, { "code": "<!DOCTYPE html> <html> <head> <title> How to Define jQuery function ? </title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script> <script> $(document).ready(function() { $.fn.myFunction = function() { document.getElementById(\"geeks\").innerHTML = \"JQuery function is defined!\"; } $(\".gfg\").click(function(){ $.fn.myFunction(); }); }); </script></head> <body style=\"text-align:center\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> Defining function in jQuery </h3> <p id=\"geeks\"></p> <button type=\"button\" class=\"gfg\"> Click </button></body> </html> ", "e": 1485, "s": 670, "text": null }, { "code": null, "e": 1493, "s": 1485, "text": "Output:" }, { "code": null, "e": 1504, "s": 1493, "text": "Example 2:" }, { "code": "<!DOCTYPE html> <html> <head> <title> How to Define jQuery function ? </title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script> <script> $(document).ready(function() { $.fn.myFunction = function() { alert('JQuery function is defined!'); } $(\".gfg\").click(function(){ $.fn.myFunction(); }); }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> Defining function in jQuery </h3> <button type=\"button\" class=\"gfg\"> Click </button></body> </html> ", "e": 2225, "s": 1504, "text": null }, { "code": null, "e": 2233, "s": 2225, "text": "Output:" }, { "code": null, "e": 2245, "s": 2233, "text": "jQuery-Misc" }, { "code": null, "e": 2252, "s": 2245, "text": "JQuery" }, { "code": null, "e": 2269, "s": 2252, "text": "Web Technologies" }, { "code": null, "e": 2296, "s": 2269, "text": "Web technologies Questions" }, { "code": null, "e": 2394, "s": 2296, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2423, "s": 2394, "text": "Form validation using jQuery" }, { "code": null, "e": 2479, "s": 2423, "text": "How to Dynamically Add/Remove Table Rows using jQuery ?" }, { "code": null, "e": 2513, "s": 2479, "text": "jQuery | children() with Examples" }, { "code": null, "e": 2567, "s": 2513, "text": "Scroll to the top of the page using JavaScript/jQuery" }, { "code": null, "e": 2624, "s": 2567, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 2657, "s": 2624, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2719, "s": 2657, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2780, "s": 2719, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2823, "s": 2780, "text": "How to fetch data from an API in ReactJS ?" } ]
getppid() and getpid() in Linux
26 Sep, 2017 Both getppid() and getpid() are inbuilt functions defined in unistd.h library. getppid() : returns the process ID of the parent of the calling process. If the calling process was created by the fork() function and the parent process still exists at the time of the getppid function call, this function returns the process ID of the parent process. Otherwise, this function returns a value of 1 which is the process id for init process.Syntax:pid_t getppid(void); Return type: getppid() returns the process ID of the parent of the current process. It never throws any error therefore is always successful.// C++ Code to demonstrate getppid()#include <iostream>#include <unistd.h>using namespace std; // Driver Codeint main(){ int pid; pid = fork(); if (pid == 0) { cout << "\nParent Process id : " << getpid() << endl; cout << "\nChild Process with parent id : " << getppid() << endl; } return 0;}Output(Will be different on different systems):Parent Process id of current process : 3849 Child Process with parent id : 3851 NOTE: At some instance of time, it is not necessary that child process will execute first or parent process will be first allotted CPU, any process may get CPU assigned, at some quantum time. Moreover process id may differ during different executions.getpid() : returns the process ID of the calling process. This is often used by routines that generate unique temporary filenames.Syntax:pid_t getpid(void); Return type: getpid() returns the process ID of the current process. It never throws any error therefore is always successful.// C++ Code to demonstrate getpid()#include <iostream>#include <unistd.h>using namespace std; // Driver Codeint main(){ int pid = fork(); if (pid == 0) cout << "\nCurrent process id of Process : " << getpid() << endl; return 0;}Output (Will be different on different systems):Current process id of Process : 4195 getppid() : returns the process ID of the parent of the calling process. If the calling process was created by the fork() function and the parent process still exists at the time of the getppid function call, this function returns the process ID of the parent process. Otherwise, this function returns a value of 1 which is the process id for init process.Syntax:pid_t getppid(void); Return type: getppid() returns the process ID of the parent of the current process. It never throws any error therefore is always successful.// C++ Code to demonstrate getppid()#include <iostream>#include <unistd.h>using namespace std; // Driver Codeint main(){ int pid; pid = fork(); if (pid == 0) { cout << "\nParent Process id : " << getpid() << endl; cout << "\nChild Process with parent id : " << getppid() << endl; } return 0;}Output(Will be different on different systems):Parent Process id of current process : 3849 Child Process with parent id : 3851 NOTE: At some instance of time, it is not necessary that child process will execute first or parent process will be first allotted CPU, any process may get CPU assigned, at some quantum time. Moreover process id may differ during different executions. pid_t getppid(void); Return type: getppid() returns the process ID of the parent of the current process. It never throws any error therefore is always successful. // C++ Code to demonstrate getppid()#include <iostream>#include <unistd.h>using namespace std; // Driver Codeint main(){ int pid; pid = fork(); if (pid == 0) { cout << "\nParent Process id : " << getpid() << endl; cout << "\nChild Process with parent id : " << getppid() << endl; } return 0;} Output(Will be different on different systems): Parent Process id of current process : 3849 Child Process with parent id : 3851 NOTE: At some instance of time, it is not necessary that child process will execute first or parent process will be first allotted CPU, any process may get CPU assigned, at some quantum time. Moreover process id may differ during different executions. getpid() : returns the process ID of the calling process. This is often used by routines that generate unique temporary filenames.Syntax:pid_t getpid(void); Return type: getpid() returns the process ID of the current process. It never throws any error therefore is always successful.// C++ Code to demonstrate getpid()#include <iostream>#include <unistd.h>using namespace std; // Driver Codeint main(){ int pid = fork(); if (pid == 0) cout << "\nCurrent process id of Process : " << getpid() << endl; return 0;}Output (Will be different on different systems):Current process id of Process : 4195 pid_t getpid(void); Return type: getpid() returns the process ID of the current process. It never throws any error therefore is always successful. // C++ Code to demonstrate getpid()#include <iostream>#include <unistd.h>using namespace std; // Driver Codeint main(){ int pid = fork(); if (pid == 0) cout << "\nCurrent process id of Process : " << getpid() << endl; return 0;} Output (Will be different on different systems): Current process id of Process : 4195 This article is contributed by Pushpanjali Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. CPP-Library system-programming C Language Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C std::string class in C++ Unordered Sets in C++ Standard Template Library Different Methods to Reverse a String in C++ Sed Command in Linux/Unix with examples grep command in Unix/Linux AWK command in Unix/Linux with examples cut command in Linux with examples cp command in Linux with examples
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Sep, 2017" }, { "code": null, "e": 131, "s": 52, "text": "Both getppid() and getpid() are inbuilt functions defined in unistd.h library." }, { "code": null, "e": 2012, "s": 131, "text": "getppid() : returns the process ID of the parent of the calling process. If the calling process was created by the fork() function and the parent process still exists at the time of the getppid function call, this function returns the process ID of the parent process. Otherwise, this function returns a value of 1 which is the process id for init process.Syntax:pid_t getppid(void);\nReturn type: getppid() returns the process ID of the parent of the current process. It never throws any error therefore is always successful.// C++ Code to demonstrate getppid()#include <iostream>#include <unistd.h>using namespace std; // Driver Codeint main(){ int pid; pid = fork(); if (pid == 0) { cout << \"\\nParent Process id : \" << getpid() << endl; cout << \"\\nChild Process with parent id : \" << getppid() << endl; } return 0;}Output(Will be different on different systems):Parent Process id of current process : 3849\nChild Process with parent id : 3851\nNOTE: At some instance of time, it is not necessary that child process will execute first or parent process will be first allotted CPU, any process may get CPU assigned, at some quantum time. Moreover process id may differ during different executions.getpid() : returns the process ID of the calling process. This is often used by routines that generate unique temporary filenames.Syntax:pid_t getpid(void);\nReturn type: getpid() returns the process ID of the current process. It never throws any error therefore is always successful.// C++ Code to demonstrate getpid()#include <iostream>#include <unistd.h>using namespace std; // Driver Codeint main(){ int pid = fork(); if (pid == 0) cout << \"\\nCurrent process id of Process : \" << getpid() << endl; return 0;}Output (Will be different on different systems):Current process id of Process : 4195\n" }, { "code": null, "e": 3267, "s": 2012, "text": "getppid() : returns the process ID of the parent of the calling process. If the calling process was created by the fork() function and the parent process still exists at the time of the getppid function call, this function returns the process ID of the parent process. Otherwise, this function returns a value of 1 which is the process id for init process.Syntax:pid_t getppid(void);\nReturn type: getppid() returns the process ID of the parent of the current process. It never throws any error therefore is always successful.// C++ Code to demonstrate getppid()#include <iostream>#include <unistd.h>using namespace std; // Driver Codeint main(){ int pid; pid = fork(); if (pid == 0) { cout << \"\\nParent Process id : \" << getpid() << endl; cout << \"\\nChild Process with parent id : \" << getppid() << endl; } return 0;}Output(Will be different on different systems):Parent Process id of current process : 3849\nChild Process with parent id : 3851\nNOTE: At some instance of time, it is not necessary that child process will execute first or parent process will be first allotted CPU, any process may get CPU assigned, at some quantum time. Moreover process id may differ during different executions." }, { "code": null, "e": 3289, "s": 3267, "text": "pid_t getppid(void);\n" }, { "code": null, "e": 3431, "s": 3289, "text": "Return type: getppid() returns the process ID of the parent of the current process. It never throws any error therefore is always successful." }, { "code": "// C++ Code to demonstrate getppid()#include <iostream>#include <unistd.h>using namespace std; // Driver Codeint main(){ int pid; pid = fork(); if (pid == 0) { cout << \"\\nParent Process id : \" << getpid() << endl; cout << \"\\nChild Process with parent id : \" << getppid() << endl; } return 0;}", "e": 3783, "s": 3431, "text": null }, { "code": null, "e": 3831, "s": 3783, "text": "Output(Will be different on different systems):" }, { "code": null, "e": 3912, "s": 3831, "text": "Parent Process id of current process : 3849\nChild Process with parent id : 3851\n" }, { "code": null, "e": 4164, "s": 3912, "text": "NOTE: At some instance of time, it is not necessary that child process will execute first or parent process will be first allotted CPU, any process may get CPU assigned, at some quantum time. Moreover process id may differ during different executions." }, { "code": null, "e": 4791, "s": 4164, "text": "getpid() : returns the process ID of the calling process. This is often used by routines that generate unique temporary filenames.Syntax:pid_t getpid(void);\nReturn type: getpid() returns the process ID of the current process. It never throws any error therefore is always successful.// C++ Code to demonstrate getpid()#include <iostream>#include <unistd.h>using namespace std; // Driver Codeint main(){ int pid = fork(); if (pid == 0) cout << \"\\nCurrent process id of Process : \" << getpid() << endl; return 0;}Output (Will be different on different systems):Current process id of Process : 4195\n" }, { "code": null, "e": 4812, "s": 4791, "text": "pid_t getpid(void);\n" }, { "code": null, "e": 4939, "s": 4812, "text": "Return type: getpid() returns the process ID of the current process. It never throws any error therefore is always successful." }, { "code": "// C++ Code to demonstrate getpid()#include <iostream>#include <unistd.h>using namespace std; // Driver Codeint main(){ int pid = fork(); if (pid == 0) cout << \"\\nCurrent process id of Process : \" << getpid() << endl; return 0;}", "e": 5198, "s": 4939, "text": null }, { "code": null, "e": 5247, "s": 5198, "text": "Output (Will be different on different systems):" }, { "code": null, "e": 5285, "s": 5247, "text": "Current process id of Process : 4195\n" }, { "code": null, "e": 5592, "s": 5285, "text": "This article is contributed by Pushpanjali Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 5717, "s": 5592, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5729, "s": 5717, "text": "CPP-Library" }, { "code": null, "e": 5748, "s": 5729, "text": "system-programming" }, { "code": null, "e": 5759, "s": 5748, "text": "C Language" }, { "code": null, "e": 5770, "s": 5759, "text": "Linux-Unix" }, { "code": null, "e": 5868, "s": 5770, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5885, "s": 5868, "text": "Substring in C++" }, { "code": null, "e": 5907, "s": 5885, "text": "Function Pointer in C" }, { "code": null, "e": 5932, "s": 5907, "text": "std::string class in C++" }, { "code": null, "e": 5980, "s": 5932, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 6025, "s": 5980, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 6065, "s": 6025, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 6092, "s": 6065, "text": "grep command in Unix/Linux" }, { "code": null, "e": 6132, "s": 6092, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 6167, "s": 6132, "text": "cut command in Linux with examples" } ]
GATE | GATE-CS-2015 (Set 2) | Question 65
10 Nov, 2021 Consider a processor with byte-addressable memory. Assume that all registers, including Program Counter (PC) and Program Status Word (PSW), are of size 2 bytes. A stack in the main memory is implemented from memory location (0100)16 and it grows upward. The stack pointer (SP) points to the top element of the stack. The current value of SP is (016E)16. The CALL instruction is of two words, the first word is the op-code and the second word is the starting address of the subroutine (one word = 2 bytes). The CALL instruction is implemented as follows: • Store the current value of PC in the stack. • Store the value of PSW register in the stack. • Load the starting address of the subroutine in PC. The content of PC just before the fetch of a CALL instruction is (5FA0)16. After execution of the CALL instruction, the value of the stack pointer isA.(016A)16B.(016C)16C.(0170)16D.(0172)16(A) A(B) B(C) C(D) DAnswer: (D)Explanation: The current value of SP is (016E)16 The value of SP after following operations is asked in question • Store the current value of PC in the stack. This operation increments SP by 2 bytes as size of PC is given 2 bytes in question. So becomes (016E)16 + 2 = (0170)16 • Store the value of PSW register in the stack. This operation also increments SP by 2 bytes as size of PSW is also given 2 bytes. So becomes (0170)16 + 2 = (0172)16 • Load the starting address of the subroutine in PC. The Load operation doesn't change SP. So new value of SP is (0172)16 Quiz of this Question GATE-CS-2015 (Set 2) GATE-GATE-CS-2015 (Set 2) 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-2015 (Set 3) | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 1996 | Question 63 GATE | Gate IT 2005 | Question 52 GATE | GATE-CS-2001 | Question 50 GATE | GATE CS 1997 | Question 50 GATE | GATE CS 2011 | Question 49 GATE | GATE CS 2013 | Question 43
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Nov, 2021" }, { "code": null, "e": 582, "s": 28, "text": "Consider a processor with byte-addressable memory. Assume that all registers, including Program Counter (PC) and Program Status Word (PSW), are of size 2 bytes. A stack in the main memory is implemented from memory location (0100)16 and it grows upward. The stack pointer (SP) points to the top element of the stack. The current value of SP is (016E)16. The CALL instruction is of two words, the first word is the op-code and the second word is the starting address of the subroutine (one word = 2 bytes). The CALL instruction is implemented as follows:" }, { "code": null, "e": 739, "s": 582, "text": " • Store the current value of PC in the stack.\n • Store the value of PSW register in the stack.\n • Load the starting address of the subroutine in PC. " }, { "code": null, "e": 972, "s": 739, "text": "The content of PC just before the fetch of a CALL instruction is (5FA0)16. After execution of the CALL instruction, the value of the stack pointer isA.(016A)16B.(016C)16C.(0170)16D.(0172)16(A) A(B) B(C) C(D) DAnswer: (D)Explanation:" }, { "code": null, "e": 1539, "s": 972, "text": "The current value of SP is (016E)16\n\nThe value of SP after following operations is asked \nin question\n\n • Store the current value of PC in the stack.\nThis operation increments SP by 2 bytes as size\nof PC is given 2 bytes in question. \nSo becomes (016E)16 + 2 = (0170)16\n\n• Store the value of PSW register in the stack.\nThis operation also increments SP by 2 bytes as size\nof PSW is also given 2 bytes.\nSo becomes (0170)16 + 2 = (0172)16\n\n• Load the starting address of the subroutine in PC. \nThe Load operation doesn't change SP.\n\nSo new value of SP is (0172)16 " }, { "code": null, "e": 1561, "s": 1539, "text": "Quiz of this Question" }, { "code": null, "e": 1582, "s": 1561, "text": "GATE-CS-2015 (Set 2)" }, { "code": null, "e": 1608, "s": 1582, "text": "GATE-GATE-CS-2015 (Set 2)" }, { "code": null, "e": 1613, "s": 1608, "text": "GATE" }, { "code": null, "e": 1711, "s": 1613, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1753, "s": 1711, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 1815, "s": 1753, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 1857, "s": 1815, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 1899, "s": 1857, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 1933, "s": 1899, "text": "GATE | GATE CS 1996 | Question 63" }, { "code": null, "e": 1967, "s": 1933, "text": "GATE | Gate IT 2005 | Question 52" }, { "code": null, "e": 2001, "s": 1967, "text": "GATE | GATE-CS-2001 | Question 50" }, { "code": null, "e": 2035, "s": 2001, "text": "GATE | GATE CS 1997 | Question 50" }, { "code": null, "e": 2069, "s": 2035, "text": "GATE | GATE CS 2011 | Question 49" } ]
How to validate if input in input field has valid hexadecimal color only using express-validator ?
07 Apr, 2022 In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only valid hexadecimal color codes strings are allowed. We can also validate these input fields to only accept valid hexadecimal color codes strings using express-validator middleware. Command to install express-validator: npm install express-validator Steps to use express-validator to implement the logic: Install express-validator middleware. Create a validator.js file to code all the validation logic. Validate input by validateInputField: check(input field name) and chain on validation isHexColorl() with ‘ . ‘ Use the validation name(validateInputField) in the routes as a middleware as an array of validations. Destructure ‘validationResult’ function from express-validator to use it to find any errors. If error occurs redirect to the same page passing the error information. If error list is empty, give access to the user for the subsequent request. Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql. Example: This example illustrates how to validate an input field to only allow valid hexadecimal color code. Filename – index.js javascript const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateFavouriteColor } = require('./validator')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post( '/info', [validateFavouriteColor], async (req, res) => { const errors = validationResult(req) if(!errors.isEmpty()) { return res.send(formTemplet({errors})) } const {name, color} = req.body // New record await repo.create({ 'Name':name, 'Color':color }) res.send('<strong>Response submitted..!!</strong>')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)}) Filename – repository.js: This file contains all the logic to create a local database and interact with it. javascript // Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // Filename where data are going to store if(!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll() { return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs) { // Fetch all existing records const records = await this.getAll() // All the existing records with new // record push back to database records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json') Filename – form.js: This file contains logic to show the form. javascript const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/info' method='POST'> <div> <div> <label class='label' id='name'> Name </label> </div> <input class='input' type='text' name='name' placeholder='Vinit singh' for='name'> </div> <div> <div> <label class='label' id='color'> Favourite color </label> </div> <input class='input' type='text' name='color' placeholder= 'Hexadecimal color code' for='color'> <p class="help is-danger"> ${getError(errors, 'color')} </p> </div> <div> <button class='button is-primary'> Submit </button> </div> </form> </div> </div> </div></body> </html> `} Filename – validator.js: This file contain all the validation logic (Logic to validate a input field to only allow valid hexadecimal color code. javascript const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateFavouriteColor : check('color') // To delete leading and trailing space .trim() // Validate color input field to accept // only valid hexadecimal color code .isHexColor() // Custom message .withMessage('Must be a valid hexadecimal color code') } Filename – package.json package.json file Database: Database Output: Attempt to submit form data when colors input field is not a valid hexadecimal color Response when attempt to submit form data where colors input field is not a valid hexadecimal color Attempt to submit form data when colors input field is a valid hexadecimal color Attempt to submit form data when colors input field is a valid hexadecimal color Database after successful form submission: Database after successful submission of form Note: We have used some Bulma classes(CSS framework) in the form.js file to design the content. rkbhola5 Express.js Node.js-Misc Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Apr, 2022" }, { "code": null, "e": 459, "s": 28, "text": "In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only valid hexadecimal color codes strings are allowed. We can also validate these input fields to only accept valid hexadecimal color codes strings using express-validator middleware." }, { "code": null, "e": 497, "s": 459, "text": "Command to install express-validator:" }, { "code": null, "e": 527, "s": 497, "text": "npm install express-validator" }, { "code": null, "e": 582, "s": 527, "text": "Steps to use express-validator to implement the logic:" }, { "code": null, "e": 620, "s": 582, "text": "Install express-validator middleware." }, { "code": null, "e": 681, "s": 620, "text": "Create a validator.js file to code all the validation logic." }, { "code": null, "e": 792, "s": 681, "text": "Validate input by validateInputField: check(input field name) and chain on validation isHexColorl() with ‘ . ‘" }, { "code": null, "e": 894, "s": 792, "text": "Use the validation name(validateInputField) in the routes as a middleware as an array of validations." }, { "code": null, "e": 987, "s": 894, "text": "Destructure ‘validationResult’ function from express-validator to use it to find any errors." }, { "code": null, "e": 1060, "s": 987, "text": "If error occurs redirect to the same page passing the error information." }, { "code": null, "e": 1136, "s": 1060, "text": "If error list is empty, give access to the user for the subsequent request." }, { "code": null, "e": 1302, "s": 1136, "text": "Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql." }, { "code": null, "e": 1411, "s": 1302, "text": "Example: This example illustrates how to validate an input field to only allow valid hexadecimal color code." }, { "code": null, "e": 1431, "s": 1411, "text": "Filename – index.js" }, { "code": null, "e": 1442, "s": 1431, "text": "javascript" }, { "code": "const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateFavouriteColor } = require('./validator')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post( '/info', [validateFavouriteColor], async (req, res) => { const errors = validationResult(req) if(!errors.isEmpty()) { return res.send(formTemplet({errors})) } const {name, color} = req.body // New record await repo.create({ 'Name':name, 'Color':color }) res.send('<strong>Response submitted..!!</strong>')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})", "e": 2450, "s": 1442, "text": null }, { "code": null, "e": 2558, "s": 2450, "text": "Filename – repository.js: This file contains all the logic to create a local database and interact with it." }, { "code": null, "e": 2569, "s": 2558, "text": "javascript" }, { "code": "// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // Filename where data are going to store if(!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll() { return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs) { // Fetch all existing records const records = await this.getAll() // All the existing records with new // record push back to database records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json')", "e": 3709, "s": 2569, "text": null }, { "code": null, "e": 3772, "s": 3709, "text": "Filename – form.js: This file contains logic to show the form." }, { "code": null, "e": 3783, "s": 3772, "text": "javascript" }, { "code": "const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/info' method='POST'> <div> <div> <label class='label' id='name'> Name </label> </div> <input class='input' type='text' name='name' placeholder='Vinit singh' for='name'> </div> <div> <div> <label class='label' id='color'> Favourite color </label> </div> <input class='input' type='text' name='color' placeholder= 'Hexadecimal color code' for='color'> <p class=\"help is-danger\"> ${getError(errors, 'color')} </p> </div> <div> <button class='button is-primary'> Submit </button> </div> </form> </div> </div> </div></body> </html> `}", "e": 5191, "s": 3783, "text": null }, { "code": null, "e": 5336, "s": 5191, "text": "Filename – validator.js: This file contain all the validation logic (Logic to validate a input field to only allow valid hexadecimal color code." }, { "code": null, "e": 5347, "s": 5336, "text": "javascript" }, { "code": "const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateFavouriteColor : check('color') // To delete leading and trailing space .trim() // Validate color input field to accept // only valid hexadecimal color code .isHexColor() // Custom message .withMessage('Must be a valid hexadecimal color code') }", "e": 5729, "s": 5347, "text": null }, { "code": null, "e": 5753, "s": 5729, "text": "Filename – package.json" }, { "code": null, "e": 5771, "s": 5753, "text": "package.json file" }, { "code": null, "e": 5781, "s": 5771, "text": "Database:" }, { "code": null, "e": 5790, "s": 5781, "text": "Database" }, { "code": null, "e": 5798, "s": 5790, "text": "Output:" }, { "code": null, "e": 5883, "s": 5798, "text": "Attempt to submit form data when colors input field is not a valid hexadecimal color" }, { "code": null, "e": 5983, "s": 5883, "text": "Response when attempt to submit form data where colors input field is not a valid hexadecimal color" }, { "code": null, "e": 6064, "s": 5983, "text": "Attempt to submit form data when colors input field is a valid hexadecimal color" }, { "code": null, "e": 6145, "s": 6064, "text": "Attempt to submit form data when colors input field is a valid hexadecimal color" }, { "code": null, "e": 6188, "s": 6145, "text": "Database after successful form submission:" }, { "code": null, "e": 6233, "s": 6188, "text": "Database after successful submission of form" }, { "code": null, "e": 6329, "s": 6233, "text": "Note: We have used some Bulma classes(CSS framework) in the form.js file to design the content." }, { "code": null, "e": 6338, "s": 6329, "text": "rkbhola5" }, { "code": null, "e": 6349, "s": 6338, "text": "Express.js" }, { "code": null, "e": 6362, "s": 6349, "text": "Node.js-Misc" }, { "code": null, "e": 6370, "s": 6362, "text": "Node.js" }, { "code": null, "e": 6387, "s": 6370, "text": "Web Technologies" } ]
Output of Python Programs | Set 24 (Sets)
29 Dec, 2017 Prerequisite: Python-Sets 1. What is the output of the code shown below? sets = {1, 2, 3, 4, 4}print(sets) Options: {1, 2, 3}{1, 2, 3, 4}{1, 2, 3, 4, 4}Error {1, 2, 3} {1, 2, 3, 4} {1, 2, 3, 4, 4} Error Output: 2. {1, 2, 3, 4} Explanation : Duplicate values are not allowed in sets. Hence, the output of the code shown above will be a set containing the duplicate value only once. Hence output will be {1, 2, 3, 4}. 2. What is the output of the code shown below? sets = {3, 4, 5}sets.update([1, 2, 3])print(sets) Options: {1, 2, 3, 4, 5}{3, 4, 5, 1, 2, 3}{1, 2, 3, 3, 4, 5}Error {1, 2, 3, 4, 5} {3, 4, 5, 1, 2, 3} {1, 2, 3, 3, 4, 5} Error Output: 1. {1, 2, 3, 4, 5} Explanation: The method update adds elements to a set. 3. What is the output of the code shown below? set1 = {1, 2, 3}set2 = set1.copy()set2.add(4)print(set1) Options: {1, 2, 3, 4}{1, 2, 3}Invalid SyntaxError {1, 2, 3, 4} {1, 2, 3} Invalid Syntax Error Output: 2. {1, 2, 3} Explanation: In the above piece of code, set2 is barely a copy and not an alias of set1. Hence any change made in set2 isn’t reflected in set1. 4. What is the output of the code shown below? set1 = {1, 2, 3}set2 = set1.add(4)print(set2) Options: {1, 2, 3, 4}{1, 2, 3}Invalid SyntaxNone {1, 2, 3, 4} {1, 2, 3} Invalid Syntax None Output: 4. None Explanation: add method doesn’t return anything. Hence there will be no output. 5. What is the output of the code shown below? set1 = {1, 2, 3}set2 = {4, 5, 6}print(len(set1 + set2)) Options: 36UnexpectedError 3 6 Unexpected Error Output: 4. Error Explanation: unsupported operand type(s) for +: ‘set’ and ‘set’. Python-Output python-set Program Output python-set Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Dec, 2017" }, { "code": null, "e": 78, "s": 52, "text": "Prerequisite: Python-Sets" }, { "code": null, "e": 125, "s": 78, "text": "1. What is the output of the code shown below?" }, { "code": "sets = {1, 2, 3, 4, 4}print(sets)", "e": 159, "s": 125, "text": null }, { "code": null, "e": 168, "s": 159, "text": "Options:" }, { "code": null, "e": 210, "s": 168, "text": "{1, 2, 3}{1, 2, 3, 4}{1, 2, 3, 4, 4}Error" }, { "code": null, "e": 220, "s": 210, "text": "{1, 2, 3}" }, { "code": null, "e": 233, "s": 220, "text": "{1, 2, 3, 4}" }, { "code": null, "e": 249, "s": 233, "text": "{1, 2, 3, 4, 4}" }, { "code": null, "e": 255, "s": 249, "text": "Error" }, { "code": null, "e": 280, "s": 255, "text": "Output:\n2. {1, 2, 3, 4}\n" }, { "code": null, "e": 469, "s": 280, "text": "Explanation : Duplicate values are not allowed in sets. Hence, the output of the code shown above will be a set containing the duplicate value only once. Hence output will be {1, 2, 3, 4}." }, { "code": null, "e": 516, "s": 469, "text": "2. What is the output of the code shown below?" }, { "code": "sets = {3, 4, 5}sets.update([1, 2, 3])print(sets)", "e": 566, "s": 516, "text": null }, { "code": null, "e": 575, "s": 566, "text": "Options:" }, { "code": null, "e": 632, "s": 575, "text": "{1, 2, 3, 4, 5}{3, 4, 5, 1, 2, 3}{1, 2, 3, 3, 4, 5}Error" }, { "code": null, "e": 648, "s": 632, "text": "{1, 2, 3, 4, 5}" }, { "code": null, "e": 667, "s": 648, "text": "{3, 4, 5, 1, 2, 3}" }, { "code": null, "e": 686, "s": 667, "text": "{1, 2, 3, 3, 4, 5}" }, { "code": null, "e": 692, "s": 686, "text": "Error" }, { "code": null, "e": 720, "s": 692, "text": "Output:\n1. {1, 2, 3, 4, 5}\n" }, { "code": null, "e": 775, "s": 720, "text": "Explanation: The method update adds elements to a set." }, { "code": null, "e": 822, "s": 775, "text": "3. What is the output of the code shown below?" }, { "code": "set1 = {1, 2, 3}set2 = set1.copy()set2.add(4)print(set1)", "e": 879, "s": 822, "text": null }, { "code": null, "e": 888, "s": 879, "text": "Options:" }, { "code": null, "e": 929, "s": 888, "text": "{1, 2, 3, 4}{1, 2, 3}Invalid SyntaxError" }, { "code": null, "e": 942, "s": 929, "text": "{1, 2, 3, 4}" }, { "code": null, "e": 952, "s": 942, "text": "{1, 2, 3}" }, { "code": null, "e": 967, "s": 952, "text": "Invalid Syntax" }, { "code": null, "e": 973, "s": 967, "text": "Error" }, { "code": null, "e": 995, "s": 973, "text": "Output:\n2. {1, 2, 3}\n" }, { "code": null, "e": 1139, "s": 995, "text": "Explanation: In the above piece of code, set2 is barely a copy and not an alias of set1. Hence any change made in set2 isn’t reflected in set1." }, { "code": null, "e": 1186, "s": 1139, "text": "4. What is the output of the code shown below?" }, { "code": "set1 = {1, 2, 3}set2 = set1.add(4)print(set2)", "e": 1232, "s": 1186, "text": null }, { "code": null, "e": 1241, "s": 1232, "text": "Options:" }, { "code": null, "e": 1281, "s": 1241, "text": "{1, 2, 3, 4}{1, 2, 3}Invalid SyntaxNone" }, { "code": null, "e": 1294, "s": 1281, "text": "{1, 2, 3, 4}" }, { "code": null, "e": 1304, "s": 1294, "text": "{1, 2, 3}" }, { "code": null, "e": 1319, "s": 1304, "text": "Invalid Syntax" }, { "code": null, "e": 1324, "s": 1319, "text": "None" }, { "code": null, "e": 1341, "s": 1324, "text": "Output:\n4. None\n" }, { "code": null, "e": 1421, "s": 1341, "text": "Explanation: add method doesn’t return anything. Hence there will be no output." }, { "code": null, "e": 1468, "s": 1421, "text": "5. What is the output of the code shown below?" }, { "code": "set1 = {1, 2, 3}set2 = {4, 5, 6}print(len(set1 + set2))", "e": 1524, "s": 1468, "text": null }, { "code": null, "e": 1533, "s": 1524, "text": "Options:" }, { "code": null, "e": 1551, "s": 1533, "text": "36UnexpectedError" }, { "code": null, "e": 1553, "s": 1551, "text": "3" }, { "code": null, "e": 1555, "s": 1553, "text": "6" }, { "code": null, "e": 1566, "s": 1555, "text": "Unexpected" }, { "code": null, "e": 1572, "s": 1566, "text": "Error" }, { "code": null, "e": 1590, "s": 1572, "text": "Output:\n4. Error\n" }, { "code": null, "e": 1655, "s": 1590, "text": "Explanation: unsupported operand type(s) for +: ‘set’ and ‘set’." }, { "code": null, "e": 1669, "s": 1655, "text": "Python-Output" }, { "code": null, "e": 1680, "s": 1669, "text": "python-set" }, { "code": null, "e": 1695, "s": 1680, "text": "Program Output" }, { "code": null, "e": 1706, "s": 1695, "text": "python-set" } ]
How to get column index from column name in Python Pandas?
To get column index from column name in Python Pandas, we can use the get_loc() method. Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df. Print the input DataFrame, df. Find the columns of DataFrame, using df.columns. Print the columns from Step 3. Initialize a variable column_name. Get the location, i.e., of index for column_name. Print the index of the column_name. import pandas as pd df = pd.DataFrame( { "x": [5, 2, 7, 0], "y": [4, 7, 5, 1], "z": [9, 3, 5, 1] } ) print"Input DataFrame 1 is:\n", df columns = df.columns print"Columns in the given DataFrame: ", columns column_name = "z" column_index = columns.get_loc(column_name) print"Index of the column ", column_name, " is: ", column_index column_name = "x" column_index = columns.get_loc(column_name) print"Index of the column ", column_name, " is: ", column_index column_name = "y" column_index = columns.get_loc(column_name) print"Index of the column ", column_name, " is: ", column_index Input DataFrame 1 is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 Columns in the given DataFrame: Index(['x', 'y', 'z'], dtype='object') Index of the column z is: 2 Index of the column x is: 0 Index of the column y is: 1
[ { "code": null, "e": 1275, "s": 1187, "text": "To get column index from column name in Python Pandas, we can use the get_loc() method." }, { "code": null, "e": 1359, "s": 1275, "text": "Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df." }, { "code": null, "e": 1390, "s": 1359, "text": "Print the input DataFrame, df." }, { "code": null, "e": 1439, "s": 1390, "text": "Find the columns of DataFrame, using df.columns." }, { "code": null, "e": 1470, "s": 1439, "text": "Print the columns from Step 3." }, { "code": null, "e": 1505, "s": 1470, "text": "Initialize a variable column_name." }, { "code": null, "e": 1555, "s": 1505, "text": "Get the location, i.e., of index for column_name." }, { "code": null, "e": 1591, "s": 1555, "text": "Print the index of the column_name." }, { "code": null, "e": 2204, "s": 1591, "text": "import pandas as pd\n\ndf = pd.DataFrame(\n {\n \"x\": [5, 2, 7, 0],\n \"y\": [4, 7, 5, 1],\n \"z\": [9, 3, 5, 1]\n }\n)\n\nprint\"Input DataFrame 1 is:\\n\", df\ncolumns = df.columns\nprint\"Columns in the given DataFrame: \", columns\n\ncolumn_name = \"z\"\ncolumn_index = columns.get_loc(column_name)\nprint\"Index of the column \", column_name, \" is: \", column_index\n\ncolumn_name = \"x\"\ncolumn_index = columns.get_loc(column_name)\nprint\"Index of the column \", column_name, \" is: \", column_index\n\ncolumn_name = \"y\"\ncolumn_index = columns.get_loc(column_name)\nprint\"Index of the column \", column_name, \" is: \", column_index" }, { "code": null, "e": 2421, "s": 2204, "text": "Input DataFrame 1 is:\nx y z\n0 5 4 9\n1 2 7 3\n2 7 5 5\n3 0 1 1\n\nColumns in the given DataFrame: Index(['x', 'y', 'z'],\ndtype='object')\n\nIndex of the column z is: 2\nIndex of the column x is: 0\nIndex of the column y is: 1" } ]
Components of an Android Application
30 Apr, 2021 There are some necessary building blocks that an Android application consists of. These loosely coupled components are bound by the application manifest file which contains the description of each component and how they interact. The manifest file also contains the app’s metadata, its hardware configuration, and platform requirements, external libraries, and required permissions. There are the following main components of an android app: Activities are said to be the presentation layer of our applications. The UI of our application is built around one or more extensions of the Activity class. By using Fragments and Views, activities set the layout and display the output and also respond to the user’s actions. An activity is implemented as a subclass of class Activity. Java Kotlin public class MainActivity extends Activity {} class MainActivity : AppCompatActivity() {} To read more, refer to the article: Introduction to Activities in Android Services are like invisible workers of our app. These components run at the backend, updating your data sources and Activities, triggering Notification, and also broadcast Intents. They also perform some tasks when applications are not active. A service can be used as a subclass of class Service: Java Kotlin public class ServiceName extends Service {} class ServiceName : Service() {} To read more, refer to the article: Services in Android with Example It is used to manage and persist the application data also typically interacts with the SQL database. They are also responsible for sharing the data beyond the application boundaries. The Content Providers of a particular application can be configured to allow access from other applications, and the Content Providers exposed by other applications can also be configured. A content provider should be a sub-class of the class ContentProvider. Java Kotlin public class contentProviderName extends ContentProvider { public void onCreate(){}} class contentProviderName : ContentProvider() { override fun onCreate(): Boolean {}} To read more, refer to the article: Content Providers in Android with Example They are known to be intent listeners as they enable your application to listen to the Intents that satisfy the matching criteria specified by us. Broadcast Receivers make our application react to any received Intent thereby making them perfect for creating event-driven applications. To read more, refer to the article: Broadcast Receiver in Android With Example It is a powerful inter-application message-passing framework. They are extensively used throughout Android. Intents can be used to start and stop Activities and Services, to broadcast messages system-wide or to an explicit Activity, Service or Broadcast Receiver or to request action be performed on a particular piece of data. To read more, refer to the article: Intent and Intent Filters These are the small visual application components that you can find on the home screen of the devices. They are a special variation of Broadcast Receivers that allow us to create dynamic, interactive application components for users to embed on their Home Screen. Notifications are the application alerts that are used to draw the user’s attention to some particular app event without stealing focus or interrupting the current activity of the user. They are generally used to grab user’s attention when the application is not visible or active, particularly from within a Service or Broadcast Receiver. Examples: E-mail popups, Messenger popups, etc. To read more, refer to the article: Notifications in Android with Example AmiyaRanjanRout aashaypawar 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 RecyclerView in Kotlin Android SDK and it's Components Broadcast Receiver in Android With Example How to Communicate Between Fragments in Android? Navigation Drawer in Android Flutter - Custom Bottom Navigation Bar How to Create and Add Data to SQLite Database in Android? How to Update Gradle in Android Studio? Content Providers in Android with Example
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Apr, 2021" }, { "code": null, "e": 496, "s": 54, "text": "There are some necessary building blocks that an Android application consists of. These loosely coupled components are bound by the application manifest file which contains the description of each component and how they interact. The manifest file also contains the app’s metadata, its hardware configuration, and platform requirements, external libraries, and required permissions. There are the following main components of an android app:" }, { "code": null, "e": 834, "s": 496, "text": "Activities are said to be the presentation layer of our applications. The UI of our application is built around one or more extensions of the Activity class. By using Fragments and Views, activities set the layout and display the output and also respond to the user’s actions. An activity is implemented as a subclass of class Activity. " }, { "code": null, "e": 839, "s": 834, "text": "Java" }, { "code": null, "e": 846, "s": 839, "text": "Kotlin" }, { "code": "public class MainActivity extends Activity {}", "e": 892, "s": 846, "text": null }, { "code": "class MainActivity : AppCompatActivity() {}", "e": 936, "s": 892, "text": null }, { "code": null, "e": 1010, "s": 936, "text": "To read more, refer to the article: Introduction to Activities in Android" }, { "code": null, "e": 1309, "s": 1010, "text": "Services are like invisible workers of our app. These components run at the backend, updating your data sources and Activities, triggering Notification, and also broadcast Intents. They also perform some tasks when applications are not active. A service can be used as a subclass of class Service: " }, { "code": null, "e": 1314, "s": 1309, "text": "Java" }, { "code": null, "e": 1321, "s": 1314, "text": "Kotlin" }, { "code": "public class ServiceName extends Service {}", "e": 1365, "s": 1321, "text": null }, { "code": "class ServiceName : Service() {}", "e": 1398, "s": 1365, "text": null }, { "code": null, "e": 1467, "s": 1398, "text": "To read more, refer to the article: Services in Android with Example" }, { "code": null, "e": 1913, "s": 1467, "text": "It is used to manage and persist the application data also typically interacts with the SQL database. They are also responsible for sharing the data beyond the application boundaries. The Content Providers of a particular application can be configured to allow access from other applications, and the Content Providers exposed by other applications can also be configured. A content provider should be a sub-class of the class ContentProvider. " }, { "code": null, "e": 1918, "s": 1913, "text": "Java" }, { "code": null, "e": 1925, "s": 1918, "text": "Kotlin" }, { "code": "public class contentProviderName extends ContentProvider { public void onCreate(){}}", "e": 2013, "s": 1925, "text": null }, { "code": "class contentProviderName : ContentProvider() { override fun onCreate(): Boolean {}}", "e": 2099, "s": 2013, "text": null }, { "code": null, "e": 2177, "s": 2099, "text": "To read more, refer to the article: Content Providers in Android with Example" }, { "code": null, "e": 2462, "s": 2177, "text": "They are known to be intent listeners as they enable your application to listen to the Intents that satisfy the matching criteria specified by us. Broadcast Receivers make our application react to any received Intent thereby making them perfect for creating event-driven applications." }, { "code": null, "e": 2541, "s": 2462, "text": "To read more, refer to the article: Broadcast Receiver in Android With Example" }, { "code": null, "e": 2869, "s": 2541, "text": "It is a powerful inter-application message-passing framework. They are extensively used throughout Android. Intents can be used to start and stop Activities and Services, to broadcast messages system-wide or to an explicit Activity, Service or Broadcast Receiver or to request action be performed on a particular piece of data." }, { "code": null, "e": 2931, "s": 2869, "text": "To read more, refer to the article: Intent and Intent Filters" }, { "code": null, "e": 3195, "s": 2931, "text": "These are the small visual application components that you can find on the home screen of the devices. They are a special variation of Broadcast Receivers that allow us to create dynamic, interactive application components for users to embed on their Home Screen." }, { "code": null, "e": 3583, "s": 3195, "text": "Notifications are the application alerts that are used to draw the user’s attention to some particular app event without stealing focus or interrupting the current activity of the user. They are generally used to grab user’s attention when the application is not visible or active, particularly from within a Service or Broadcast Receiver. Examples: E-mail popups, Messenger popups, etc." }, { "code": null, "e": 3657, "s": 3583, "text": "To read more, refer to the article: Notifications in Android with Example" }, { "code": null, "e": 3673, "s": 3657, "text": "AmiyaRanjanRout" }, { "code": null, "e": 3685, "s": 3673, "text": "aashaypawar" }, { "code": null, "e": 3693, "s": 3685, "text": "Android" }, { "code": null, "e": 3701, "s": 3693, "text": "Android" }, { "code": null, "e": 3799, "s": 3701, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3868, "s": 3799, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 3899, "s": 3868, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 3931, "s": 3899, "text": "Android SDK and it's Components" }, { "code": null, "e": 3974, "s": 3931, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 4023, "s": 3974, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 4052, "s": 4023, "text": "Navigation Drawer in Android" }, { "code": null, "e": 4091, "s": 4052, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 4149, "s": 4091, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 4189, "s": 4149, "text": "How to Update Gradle in Android Studio?" } ]
Python – Non-Central Chi-squared Distribution in Statistics
10 Jan, 2020 scipy.stats.ncx2() is a non-central chi-squared continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution. Parameters : q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’). Results : non-central chi-squared continuous random variable Code #1 : Creating non-central chi-squared continuous random variable # importing library from scipy.stats import ncx2 numargs = ncx2.numargs a, b = 4.32, 3.18rv = ncx2(a, b) print ("RV : \n", rv) Output : RV : scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D6E0FE08 Code #2 : non-central chi-squared continuous variates and probability distribution import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = ncx2.rvs(a, b) print ("Random Variates : \n", R) # PDF R = ncx2.pdf(a, b, quantile) print ("\nProbability Distribution : \n", R) Output : Random Variates : 1.452454339214702 Probability Distribution : [0.10195838 0.10369453 0.10528707 0.1067405 0.10805931 0.1092479 0.11031066 0.1112519 0.11207589 0.11278684] Code #3 : Graphical Representation. import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print("Distribution : \n", distribution) plot = plt.plot(distribution, rv.pdf(distribution)) Output : Distribution : [0. 0.04081633 0.08163265 0.12244898 0.16326531 0.20408163 0.24489796 0.28571429 0.32653061 0.36734694 0.40816327 0.44897959 0.48979592 0.53061224 0.57142857 0.6122449 0.65306122 0.69387755 0.73469388 0.7755102 0.81632653 0.85714286 0.89795918 0.93877551 0.97959184 1.02040816 1.06122449 1.10204082 1.14285714 1.18367347 1.2244898 1.26530612 1.30612245 1.34693878 1.3877551 1.42857143 1.46938776 1.51020408 1.55102041 1.59183673 1.63265306 1.67346939 1.71428571 1.75510204 1.79591837 1.83673469 1.87755102 1.91836735 1.95918367 2. ] Code #4 : Varying Positional Arguments import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = ncx2 .pdf(x, 1, 3) y2 = ncx2 .pdf(x, 1, 4) plt.plot(x, y1, "*", x, y2, "r--") Output : Python scipy-stats-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jan, 2020" }, { "code": null, "e": 272, "s": 28, "text": "scipy.stats.ncx2() is a non-central chi-squared continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution." }, { "code": null, "e": 285, "s": 272, "text": "Parameters :" }, { "code": null, "e": 631, "s": 285, "text": "q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’)." }, { "code": null, "e": 692, "s": 631, "text": "Results : non-central chi-squared continuous random variable" }, { "code": null, "e": 762, "s": 692, "text": "Code #1 : Creating non-central chi-squared continuous random variable" }, { "code": "# importing library from scipy.stats import ncx2 numargs = ncx2.numargs a, b = 4.32, 3.18rv = ncx2(a, b) print (\"RV : \\n\", rv) ", "e": 901, "s": 762, "text": null }, { "code": null, "e": 910, "s": 901, "text": "Output :" }, { "code": null, "e": 991, "s": 910, "text": "RV : \n scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D6E0FE08\n" }, { "code": null, "e": 1074, "s": 991, "text": "Code #2 : non-central chi-squared continuous variates and probability distribution" }, { "code": "import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = ncx2.rvs(a, b) print (\"Random Variates : \\n\", R) # PDF R = ncx2.pdf(a, b, quantile) print (\"\\nProbability Distribution : \\n\", R) ", "e": 1285, "s": 1074, "text": null }, { "code": null, "e": 1294, "s": 1285, "text": "Output :" }, { "code": null, "e": 1476, "s": 1294, "text": "Random Variates : \n 1.452454339214702\n\nProbability Distribution : \n [0.10195838 0.10369453 0.10528707 0.1067405 0.10805931 0.1092479\n 0.11031066 0.1112519 0.11207589 0.11278684]\n\n" }, { "code": null, "e": 1512, "s": 1476, "text": "Code #3 : Graphical Representation." }, { "code": "import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print(\"Distribution : \\n\", distribution) plot = plt.plot(distribution, rv.pdf(distribution)) ", "e": 1723, "s": 1512, "text": null }, { "code": null, "e": 1732, "s": 1723, "text": "Output :" }, { "code": null, "e": 2311, "s": 1732, "text": "Distribution : \n [0. 0.04081633 0.08163265 0.12244898 0.16326531 0.20408163\n 0.24489796 0.28571429 0.32653061 0.36734694 0.40816327 0.44897959\n 0.48979592 0.53061224 0.57142857 0.6122449 0.65306122 0.69387755\n 0.73469388 0.7755102 0.81632653 0.85714286 0.89795918 0.93877551\n 0.97959184 1.02040816 1.06122449 1.10204082 1.14285714 1.18367347\n 1.2244898 1.26530612 1.30612245 1.34693878 1.3877551 1.42857143\n 1.46938776 1.51020408 1.55102041 1.59183673 1.63265306 1.67346939\n 1.71428571 1.75510204 1.79591837 1.83673469 1.87755102 1.91836735\n 1.95918367 2. ]\n " }, { "code": null, "e": 2350, "s": 2311, "text": "Code #4 : Varying Positional Arguments" }, { "code": "import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = ncx2 .pdf(x, 1, 3) y2 = ncx2 .pdf(x, 1, 4) plt.plot(x, y1, \"*\", x, y2, \"r--\") ", "e": 2553, "s": 2350, "text": null }, { "code": null, "e": 2562, "s": 2553, "text": "Output :" }, { "code": null, "e": 2591, "s": 2562, "text": "Python scipy-stats-functions" }, { "code": null, "e": 2598, "s": 2591, "text": "Python" } ]
JavaScript Helper Methods
01 Jul, 2022 An array in JavaScript is usually considered as “list-objects”. In simple words, we can say an array is an object that contains some values. But an array is a special object in JavaScript. An array can store heterogeneous data structures. It can store data values of any type like objects and array . Javascript const arr = [ 1, // Number type "Praveen kumar", // String type { // Object type firstname: "Christopher", lastname: 'Nolan' }, [9.1, 9.2, 8.7, 5] // Array type]; console.log( arr ); In JavaScript, an array is an object. If an array is an object then why we don’t use an object in place of an array”. After a lot of research, we found that we can use an object in place of an array. But it comes with some caveats. In the above program, both an object and an array store data in exactly the same way. But there is some difference. The first one is an array that contains a property named length. It tells us the number of elements in an array. This is not the only difference. The main difference comes out when you open the __proto__ property of both an array and an object. An array comes with some great helper methods which we are going to discuss in this article. Let’s discuss some important methods. 1. every() Method: This method is used to check if all elements of an array pass the test that is implemented by the passed higher-order function. What compiler does under the hood is, it iterates over the employees array and check for all employee, if he is a developer or not. As in this case, it should return false. Input: predicate function Output: Boolean value Javascript const employees = [ { name: "Sam", age: 25, role: "Developer" }, { name: "John", age: 32, role: "Manager" }, { name: "Ronaldo", age: 29, role: "Architect" }, { name: "Perker", age: 25, role: "Developer" }, { name: "Sophia", age: 38, role: "Director" }, { name: "kristine", age: 21, role: "Developer" },]; function isDeveloper(employee) { return employee.role === "Developer";}console.log(employees.every(isDeveloper)); Output: false 2. fill() Method: This method fills the array with a static value. It overrides all array values starting from the first element(0th index) and up to the last element(array.length-1 index). Input: value Output: Modified array Javascript const employees = [ { name: "Sam", age: 25, role: "Developer" }, { name: "John", age: 32, role: "Manager" }, { name: "Ronaldo", age: 29, role: "Architect" }, { name: "Perker", age: 25, role: "Developer" }, { name: "Sophia", age: 38, role: "Director" }, { name: "kristine", age: 21, role: "Developer" },]; const newEmployees = employees.fill( { name: "Sam", age: 25, role: "Developer" });console.log(employees); console.log(newEmployees === employees); // true Output: [ { name: 'Sam', age: 25, role: 'Developer' }, { name: 'Sam', age: 25, role: 'Developer' }, { name: 'Sam', age: 25, role: 'Developer' }, { name: 'Sam', age: 25, role: 'Developer' }, { name: 'Sam', age: 25, role: 'Developer' }, { name: 'Sam', age: 25, role: 'Developer' } ] true 3. filter() Method: This method filters the array that passes the test with the function passed to it. It returns a new array. Input: Predicate function Output: New Array with filtered elements Javascript const employees = [ { name: "Sam", age: 25, role: "Developer" }, { name: "John", age: 32, role: "Manager" }, { name: "Ronaldo", age: 29, role: "Architect" }, { name: "Perker", age: 25, role: "Developer" }, { name: "Sophia", age: 38, role: "Director" }, { name: "kristine", age: 21, role: "Developer" },]; function filterDevEmp(employee) { return employee.role === "Developer";}const filteredDevEmployees = employees.filter(filterDevEmp);console.log(filteredDevEmployees); Output: [ { name: 'Sam', age: 25, role: 'Developer' }, { name: 'Perker', age: 25, role: 'Developer' }, { name: 'kristine', age: 21, role: 'Developer' } ] 4. find() Method: This method returns the first element that passes the test with the provided function. Input: Predicate function Output: Element that passes the test else undefined Javascript const employees = [ { name: "Sam", age: 25, role: "Developer" }, { name: "John", age: 32, role: "Manager" }, { name: "Ronaldo", age: 29, role: "Architect" }, { name: "Perker", age: 25, role: "Developer" }, { name: "Sophia", age: 38, role: "Director" }, { name: "kristine", age: 21, role: "Developer" },]; function searchFirstDevEmployee(employee) { return employee.role === "Developer";} const firstEmployeeDeveloper = employees.find(searchFirstDevEmployee); console.log(firstEmployeeDeveloper); Output: { name: 'Sam', age: 25, role: 'Developer' } 5. findIndex() Method: This method returns the first element index that passes the test with the provided function. It can be used in the case of primitive and in the case of objects. Input: Predicate function Output: element index that passes the test else -1 Javascript const employees = [ { name: "Sam", age: 25, role: "Developer" }, { name: "John", age: 32, role: "Manager" }, { name: "Ronaldo", age: 29, role: "Architect" }, { name: "Perker", age: 25, role: "Developer" }, { name: "Sophia", age: 38, role: "Director" }, { name: "kristine", age: 21, role: "Developer" },]; function searchFirstArchitectEmployeeIndex(employee) { return employee.role === "Architect";} const firstEmpArchitectIndex = employees.findIndex(searchFirstArchitectEmployeeIndex); console.log(firstEmpArchitectIndex); Output: 2 6. flat() Method: This method is used to flatten the array or concatenate the array with the sub-array elements recursively. Input: depth(default value is 1) Output: New array Javascript const arr1 = [1, [2, 3, 4], 5];const flattened1 = arr1.flat();console.log(flattened1); // [ 1, 2, 3, 4, 5 ] const arr2 = [1, 2, [3, 4, [5, 6]]]; const flattened2 = arr2.flat();console.log(flattened2); // [1, 2, 3, 4, [5, 6]] Output: [1, 2, 3, 4, 5] [1, 2, 3, 4, [5, 6]] 7. forEach() Method: This is one of the most used method. It is used to call or execute the provided/passed function once for each element in an array. It modifies the original array. Input: function Output: undefined Javascript const employees = [ { name: "Sam", age: 25, role: "Developer" }, { name: "John", age: 32, role: "Manager" }, { name: "Ronaldo", age: 29, role: "Architect" }, { name: "Perker", age: 25, role: "Developer" }, { name: "Sophia", age: 38, role: "Director" }, { name: "kristine", age: 21, role: "Developer" },]; function increaseAgeByOne(employee) { employee.age += 1;}employees.forEach(increaseAgeByOne);console.log(employees); Output: [ { name: 'Sam', age: 26, role: 'Developer' }, { name: 'John', age: 33, role: 'Manager' }, { name: 'Ronaldo', age: 30, role: 'Architect' }, { name: 'Perker', age: 26, role: 'Developer' }, { name: 'Sophia', age: 39, role: 'Director' }, { name: 'kristine', age: 22, role: 'Developer' } ] 8. includes() Method: This method is used to test whether an element is present in an array or not. It checks for a value in primitive and reference in case of an object. Input: value Output: Boolean value weather array includes value or not Javascript const numbers = [1, 6, 8, 11, 5, 9, 4];console.log( numbers.includes(6) ); console.log( numbers.includes(3) ); Output: true false In case of an object Javascript const arch = { name: "Ronaldo", age: 29, role: "Architect" }; const employees = [ { name: "Sam", age: 25, role: "Developer" }, { name: "John", age: 32, role: "Manager" }, arch, { name: "Perker", age: 25, role: "Developer" }, { name: "Sophia", age: 38, role: "Director" }, { name: "kristine", age: 21, role: "Developer" },]; console.log(employees.includes(arch)); Output: true 9. indexOf() Method: This method returns the first element index that passes the test with the provided function. It takes a value as input. It should be used in case of primitive. As in the case of objects, it will check its reference. Check is case-sensitive. Input: value Output: element index that passes the test else -1 Javascript const names = ["Sam", "John", "Ronaldo", "Perker", "Sophia", "kristine"];names.indexOf("John"); names.indexOf("john"); Output: 1 -1 10. join() Method: This method concatenates the array values into a string separated by comma(if no separator is provided) or with separator provided. Input: separator Output: New string Javascript const names = ["Sam", "John", "Ronaldo", "Perker", "Sophia", "kristine"];console.log( names.join() ); console.log( names.join(" -> ") ); Output: 'Sam, John, Ronaldo, Perker, Sophia, kristine' 'Sam -> John -> Ronaldo -> Perker -> Sophia -> kristine' 11. lastIndexOf() Method: It searches for an element in an array and returns the last index of the elements provided in an array. It takes a value as input. It should be used in case of primitive. As in the case of objects, it will check its reference. Input: value Output: last element index that is equal(test using ===) to value provided else -1 Javascript const roles = [ "Developer", "Manager", "Architect", "Developer", "Director", "Developer"]; console.log(roles.lastIndexOf("Developer")); Output: 5 12. map() Method: This method call the provided function and execute this function for each element. It returns a new array. Input: function Output: new array Javascript const employees = [ { name: "Sam", age: 25, role: "Developer" }, { name: "John", age: 32, role: "Manager" }, { name: "Ronaldo", age: 29, role: "Architect" }, { name: "Perker", age: 25, role: "Developer" }, { name: "Sophia", age: 38, role: "Director" }, { name: "kristine", age: 21, role: "Developer" },]; function getName(employee) { return employee.name;} const names = employees.map(getName);console.log(names); function concetenateNameWithAge(employee) { return employee.name + " " + employee.age;}const nameWithAge = employees.map(concetenateNameWithAge);console.log(nameWithAge); Output: [ 'Sam', 'John', 'Ronaldo', 'Perker', 'Sophia', 'kristine' ] [ 'Sam 25', 'John 32', 'Ronaldo 29', 'Perker 25', 'Sophia 38', 'kristine 21' ] 13. pop() Method: It removes the last element from an array and returns the removed element. Output: Removed element Javascript const employees = [ { name: "Sam", age: 25, role: "Developer" }, { name: "John", age: 32, role: "Manager" }, { name: "Ronaldo", age: 29, role: "Architect" }, { name: "Perker", age: 25, role: "Developer" }, { name: "Sophia", age: 38, role: "Director" }, { name: "kristine", age: 21, role: "Developer" },]; const removedEmployee = employees.pop();console.log(removedEmployee); console.log(employees.length); Output: { name: 'kristine', age: 21, role: 'Developer' } 5 14. push() Method: It adds or pushes an element as the last element in an array. Input: Array element Output: new length of an array Javascript const employees = [ { name: "Sam", age: 25, role: "Developer" }, { name: "John", age: 32, role: "Manager" }, { name: "Ronaldo", age: 29, role: "Architect" }, { name: "Perker", age: 25, role: "Developer" }, { name: "Sophia", age: 38, role: "Director" }, { name: "kristine", age: 21, role: "Developer" },]; const totalEmployees = employees.push({ name: "Donald", age: 21, role: "Manager" });console.log(employees);console.log( totalEmployees ); Output: [ { name: 'Sam', age: 25, role: 'Developer' }, { name: 'John', age: 32, role: 'Manager' }, { name: 'Ronaldo', age: 29, role: 'Architect' }, { name: 'Perker', age: 25, role: 'Developer' }, { name: 'Sophia', age: 38, role: 'Director' }, { name: 'kristine', age: 21, role: 'Developer' }, { name: 'Donald', age: 21, role: 'Manager' } ] 7 15. reduce() Method: The array reduce() method executes the reducer function that you pass on each element and it always returns a single value. The reducer function takes 4 parameters Accumulator Current value Array current index Source array Note: Reducer function always returns value and the value get assigned to accumulator in next iteration. Input: First argument is reducer function that takes minimum 2 value i.e. accumulator and current value. Second argument is initial value of accumulator. Output: A single value. If accumulator value is not provided then the source array first value or initial value is taken as the second argument of the reduce method and iteration starts from next to the initial value of the source array. Javascript const employees = [ { name: "Sam", age: 25, role: "Developer" }, { name: "John", age: 32, role: "Manager" }, { name: "Ronaldo", age: 29, role: "Architect" }, { name: "Perker", age: 25, role: "Developer" }, { name: "Sophia", age: 38, role: "Director" }, { name: "kristine", age: 21, role: "Developer" },]; function getRoleReducer(acc, currentValue) { acc.push(currentValue.role); return acc;}const roles = employees.reduce(getRoleReducer, []);console.log(roles); Output: [ 'Developer', 'Manager', 'Architect', 'Developer', 'Director', 'Developer' ] 16. reduceRight() Method: It is exactly the same as the Array reduce method but the iteration starts from right to left. Javascript const employees = [ { name: "Sam", age: 25, role: "Developer" }, { name: "John", age: 32, role: "Manager" }, { name: "Ronaldo", age: 29, role: "Architect" }, { name: "Perker", age: 25, role: "Developer" }, { name: "Sophia", age: 38, role: "Director" }, { name: "kristine", age: 21, role: "Developer" },]; function getRoleReducer(acc, currentValue) { acc.push(currentValue.role); return acc;}const roles = employees.reduceRight(getRoleReducer, []);console.log(roles); Output: [ 'Developer', 'Director', 'Developer', 'Architect', 'Manager', 'Developer' ] 17. reverse() Method: This method reverses the array elements. Output: Same array but with reversed elements Javascript const employees = [ { name: "Sam", age: 25, role: "Developer" }, { name: "John", age: 32, role: "Manager" }, { name: "Ronaldo", age: 29, role: "Architect" }, { name: "Perker", age: 25, role: "Developer" }, { name: "Sophia", age: 38, role: "Director" }, { name: "kristine", age: 21, role: "Developer" },]; const reversedEmployees = employees.reverse();console.log(reversedEmployees);console.log(employees === reversedEmployees); Output: [ { name: 'kristine', age: 21, role: 'Developer' }, { name: 'Sophia', age: 38, role: 'Director' }, { name: 'Perker', age: 25, role: 'Developer' }, { name: 'Ronaldo', age: 29, role: 'Architect' }, { name: 'John', age: 32, role: 'Manager' }, { name: 'Sam', age: 25, role: 'Developer' } ] true 18. shift() Method: It removes the first element from an array and returns the removed element. Output: removed element or if an array is empty returns undefined Javascript const employees = [ { name: "Sam", age: 25, role: "Developer" }, { name: "John", age: 32, role: "Manager" }, { name: "Ronaldo", age: 29, role: "Architect" }, { name: "Perker", age: 25, role: "Developer" }, { name: "Sophia", age: 38, role: "Director" }, { name: "kristine", age: 21, role: "Developer" },]; const removedEmployee = employees.shift();console.log(removedEmployee);console.log(employees); Output: { name: 'Sam', age: 25, role: 'Developer' } [ { name: 'John', age: 32, role: 'Manager' }, { name: 'Ronaldo', age: 29, role: 'Architect' }, { name: 'Perker', age: 25, role: 'Developer' }, { name: 'Sophia', age: 38, role: 'Director' }, { name: 'kristine', age: 21, role: 'Developer' } ] 19. slice() Method: The slice() method returns the new array with the elements specified within the starting and ending index. The new array contains the element at the starting index but does not include the element at the end index. If the end index is not provided then it is considered as an array.length-1. The slice method doesn’t change the original array. Input: Start index and end index Output: New array HTML const employees = [ { name: "Sam", age: 25, role: "Developer" }, { name: "John", age: 32, role: "Manager" }, { name: "Ronaldo", age: 29, role: "Architect" }, { name: "Perker", age: 25, role: "Developer" }, { name: "Sophia", age: 38, role: "Director" }, { name: "kristine", age: 21, role: "Developer" },]; const someEmployees = employees.slice(1, 3);console.log(someEmployees);console.log(employees); Output: [ { name: 'John', age: 32, role: 'Manager' }, { name: 'Ronaldo', age: 29, role: 'Architect' } ] [ { name: 'Sam', age: 25, role: 'Developer' }, { name: 'John', age: 32, role: 'Manager' }, { name: 'Ronaldo', age: 29, role: 'Architect' }, { name: 'Perker', age: 25, role: 'Developer' }, { name: 'Sophia', age: 38, role: 'Director' }, { name: 'kristine', age: 21, role: 'Developer' } ] 20. some() Method: This method checks if any one of the elements in the array passes the test provided by the predicate function. If in any array index the test pass some method returns true else false. It just checks the element exists in an array. It returns as soon as the predicate function returns true. Input: predicate function Output: Boolean Javascript function checkIfDevExist(employee) { return employee.role === "Developer";}const isDeveloperExist = employees.some(checkIfDevExist);console.log(isDeveloperExist); Output: true 21. sort() Method: This method sorts the array in ascending order(default behavior if compare function is not specified). This method mutates the original array.Input: optional comparer function Output: sorted array Javascript const names = ["Sam", "John", "Ronaldo", "Perker", "Sophia", "kristine"];names.sort();console.log(names); Output: [ 'John', 'Perker', 'Ronaldo', 'Sam', 'Sophia', 'kristine' ] 22. splice() Method: The splice() method in an array is used to add, remove, or replace elements in an array. It mutates the original array. Input: Starting index from where changes will takes place. (optional) No of element to delete or remove from the start index. (optional) The elements to add at starting index. Output: array with removed elements. Javascript const employees = [ { name: "Sam", age: 25, role: "Developer" }, { name: "John", age: 32, role: "Manager" }, { name: "Ronaldo", age: 29, role: "Architect" }, { name: "Perker", age: 25, role: "Developer" }, { name: "Sophia", age: 38, role: "Director" }, { name: "kristine", age: 21, role: "Developer" },]; const removedElements = employees.splice(3, 1, { name: "kristine", age: 21, role: "Developer",}); console.log(removedElements);console.log(employees); Output: [ { name: 'Perker', age: 25, role: 'Developer' } ] [ { name: 'Sam', age: 25, role: 'Developer' }, { name: 'John', age: 32, role: 'Manager' }, { name: 'Ronaldo', age: 29, role: 'Architect' }, { name: 'kristine', age: 21, role: 'Developer' }, { name: 'Sophia', age: 38, role: 'Director' }, { name: 'kristine', age: 21, role: 'Developer' } ] 23. unshift() Method: It adds or inserts an element at the starting position of an array. Input: Element to insert Output: Array length after element insertion Javascript const employees = [ { name: "Sam", age: 25, role: "Developer" }, { name: "John", age: 32, role: "Manager" }, { name: "Ronaldo", age: 29, role: "Architect" }, { name: "Perker", age: 25, role: "Developer" }, { name: "Sophia", age: 38, role: "Director" }, { name: "kristine", age: 21, role: "Developer" },]; const totalNoOfemployees = employees.unshift({ name: "kristine", age: 21, role: "Developer",}); console.log(totalNoOfemployees);console.log(employees); Output: 7 [ { name: 'kristine', age: 21, role: 'Developer' }, { name: 'Sam', age: 25, role: 'Developer' }, { name: 'John', age: 32, role: 'Manager' }, { name: 'Ronaldo', age: 29, role: 'Architect' }, { name: 'Perker', age: 25, role: 'Developer' }, { name: 'Sophia', age: 38, role: 'Director' }, { name: 'kristine', age: 21, role: 'Developer' } ] clintra sweetyty javascript-array JavaScript-Methods 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 Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JavaScript | Promises 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": 54, "s": 26, "text": "\n01 Jul, 2022" }, { "code": null, "e": 356, "s": 54, "text": "An array in JavaScript is usually considered as “list-objects”. In simple words, we can say an array is an object that contains some values. But an array is a special object in JavaScript. An array can store heterogeneous data structures. It can store data values of any type like objects and array . " }, { "code": null, "e": 367, "s": 356, "text": "Javascript" }, { "code": "const arr = [ 1, // Number type \"Praveen kumar\", // String type { // Object type firstname: \"Christopher\", lastname: 'Nolan' }, [9.1, 9.2, 8.7, 5] // Array type]; console.log( arr );", "e": 624, "s": 367, "text": null }, { "code": null, "e": 856, "s": 624, "text": "In JavaScript, an array is an object. If an array is an object then why we don’t use an object in place of an array”. After a lot of research, we found that we can use an object in place of an array. But it comes with some caveats." }, { "code": null, "e": 972, "s": 856, "text": "In the above program, both an object and an array store data in exactly the same way. But there is some difference." }, { "code": null, "e": 1348, "s": 972, "text": "The first one is an array that contains a property named length. It tells us the number of elements in an array. This is not the only difference. The main difference comes out when you open the __proto__ property of both an array and an object. An array comes with some great helper methods which we are going to discuss in this article. Let’s discuss some important methods." }, { "code": null, "e": 1668, "s": 1348, "text": "1. every() Method: This method is used to check if all elements of an array pass the test that is implemented by the passed higher-order function. What compiler does under the hood is, it iterates over the employees array and check for all employee, if he is a developer or not. As in this case, it should return false." }, { "code": null, "e": 1676, "s": 1668, "text": "Input: " }, { "code": null, "e": 1696, "s": 1676, "text": " predicate function" }, { "code": null, "e": 1704, "s": 1696, "text": "Output:" }, { "code": null, "e": 1718, "s": 1704, "text": "Boolean value" }, { "code": null, "e": 1729, "s": 1718, "text": "Javascript" }, { "code": "const employees = [ { name: \"Sam\", age: 25, role: \"Developer\" }, { name: \"John\", age: 32, role: \"Manager\" }, { name: \"Ronaldo\", age: 29, role: \"Architect\" }, { name: \"Perker\", age: 25, role: \"Developer\" }, { name: \"Sophia\", age: 38, role: \"Director\" }, { name: \"kristine\", age: 21, role: \"Developer\" },]; function isDeveloper(employee) { return employee.role === \"Developer\";}console.log(employees.every(isDeveloper));", "e": 2172, "s": 1729, "text": null }, { "code": null, "e": 2180, "s": 2172, "text": "Output:" }, { "code": null, "e": 2186, "s": 2180, "text": "false" }, { "code": null, "e": 2376, "s": 2186, "text": "2. fill() Method: This method fills the array with a static value. It overrides all array values starting from the first element(0th index) and up to the last element(array.length-1 index)." }, { "code": null, "e": 2383, "s": 2376, "text": "Input:" }, { "code": null, "e": 2390, "s": 2383, "text": "value " }, { "code": null, "e": 2398, "s": 2390, "text": "Output:" }, { "code": null, "e": 2413, "s": 2398, "text": "Modified array" }, { "code": null, "e": 2424, "s": 2413, "text": "Javascript" }, { "code": "const employees = [ { name: \"Sam\", age: 25, role: \"Developer\" }, { name: \"John\", age: 32, role: \"Manager\" }, { name: \"Ronaldo\", age: 29, role: \"Architect\" }, { name: \"Perker\", age: 25, role: \"Developer\" }, { name: \"Sophia\", age: 38, role: \"Director\" }, { name: \"kristine\", age: 21, role: \"Developer\" },]; const newEmployees = employees.fill( { name: \"Sam\", age: 25, role: \"Developer\" });console.log(employees); console.log(newEmployees === employees); // true", "e": 2933, "s": 2424, "text": null }, { "code": null, "e": 2941, "s": 2933, "text": "Output:" }, { "code": null, "e": 3226, "s": 2941, "text": "[\n { name: 'Sam', age: 25, role: 'Developer' },\n { name: 'Sam', age: 25, role: 'Developer' },\n { name: 'Sam', age: 25, role: 'Developer' },\n { name: 'Sam', age: 25, role: 'Developer' },\n { name: 'Sam', age: 25, role: 'Developer' },\n { name: 'Sam', age: 25, role: 'Developer' }\n]\n\ntrue" }, { "code": null, "e": 3353, "s": 3226, "text": "3. filter() Method: This method filters the array that passes the test with the function passed to it. It returns a new array." }, { "code": null, "e": 3360, "s": 3353, "text": "Input:" }, { "code": null, "e": 3379, "s": 3360, "text": "Predicate function" }, { "code": null, "e": 3387, "s": 3379, "text": "Output:" }, { "code": null, "e": 3420, "s": 3387, "text": "New Array with filtered elements" }, { "code": null, "e": 3431, "s": 3420, "text": "Javascript" }, { "code": "const employees = [ { name: \"Sam\", age: 25, role: \"Developer\" }, { name: \"John\", age: 32, role: \"Manager\" }, { name: \"Ronaldo\", age: 29, role: \"Architect\" }, { name: \"Perker\", age: 25, role: \"Developer\" }, { name: \"Sophia\", age: 38, role: \"Director\" }, { name: \"kristine\", age: 21, role: \"Developer\" },]; function filterDevEmp(employee) { return employee.role === \"Developer\";}const filteredDevEmployees = employees.filter(filterDevEmp);console.log(filteredDevEmployees);", "e": 3947, "s": 3431, "text": null }, { "code": null, "e": 3955, "s": 3947, "text": "Output:" }, { "code": null, "e": 4104, "s": 3955, "text": "[\n { name: 'Sam', age: 25, role: 'Developer' },\n { name: 'Perker', age: 25, role: 'Developer' },\n { name: 'kristine', age: 21, role: 'Developer' }\n]" }, { "code": null, "e": 4209, "s": 4104, "text": "4. find() Method: This method returns the first element that passes the test with the provided function." }, { "code": null, "e": 4216, "s": 4209, "text": "Input:" }, { "code": null, "e": 4236, "s": 4216, "text": "Predicate function " }, { "code": null, "e": 4244, "s": 4236, "text": "Output:" }, { "code": null, "e": 4288, "s": 4244, "text": "Element that passes the test else undefined" }, { "code": null, "e": 4299, "s": 4288, "text": "Javascript" }, { "code": "const employees = [ { name: \"Sam\", age: 25, role: \"Developer\" }, { name: \"John\", age: 32, role: \"Manager\" }, { name: \"Ronaldo\", age: 29, role: \"Architect\" }, { name: \"Perker\", age: 25, role: \"Developer\" }, { name: \"Sophia\", age: 38, role: \"Director\" }, { name: \"kristine\", age: 21, role: \"Developer\" },]; function searchFirstDevEmployee(employee) { return employee.role === \"Developer\";} const firstEmployeeDeveloper = employees.find(searchFirstDevEmployee); console.log(firstEmployeeDeveloper); ", "e": 4837, "s": 4299, "text": null }, { "code": null, "e": 4845, "s": 4837, "text": "Output:" }, { "code": null, "e": 4890, "s": 4845, "text": " { name: 'Sam', age: 25, role: 'Developer' }" }, { "code": null, "e": 5074, "s": 4890, "text": "5. findIndex() Method: This method returns the first element index that passes the test with the provided function. It can be used in the case of primitive and in the case of objects." }, { "code": null, "e": 5082, "s": 5074, "text": "Input: " }, { "code": null, "e": 5101, "s": 5082, "text": "Predicate function" }, { "code": null, "e": 5110, "s": 5101, "text": "Output: " }, { "code": null, "e": 5153, "s": 5110, "text": "element index that passes the test else -1" }, { "code": null, "e": 5164, "s": 5153, "text": "Javascript" }, { "code": "const employees = [ { name: \"Sam\", age: 25, role: \"Developer\" }, { name: \"John\", age: 32, role: \"Manager\" }, { name: \"Ronaldo\", age: 29, role: \"Architect\" }, { name: \"Perker\", age: 25, role: \"Developer\" }, { name: \"Sophia\", age: 38, role: \"Director\" }, { name: \"kristine\", age: 21, role: \"Developer\" },]; function searchFirstArchitectEmployeeIndex(employee) { return employee.role === \"Architect\";} const firstEmpArchitectIndex = employees.findIndex(searchFirstArchitectEmployeeIndex); console.log(firstEmpArchitectIndex); ", "e": 5727, "s": 5164, "text": null }, { "code": null, "e": 5735, "s": 5727, "text": "Output:" }, { "code": null, "e": 5737, "s": 5735, "text": "2" }, { "code": null, "e": 5862, "s": 5737, "text": "6. flat() Method: This method is used to flatten the array or concatenate the array with the sub-array elements recursively." }, { "code": null, "e": 5870, "s": 5862, "text": "Input: " }, { "code": null, "e": 5897, "s": 5870, "text": " depth(default value is 1)" }, { "code": null, "e": 5905, "s": 5897, "text": "Output:" }, { "code": null, "e": 5915, "s": 5905, "text": "New array" }, { "code": null, "e": 5926, "s": 5915, "text": "Javascript" }, { "code": "const arr1 = [1, [2, 3, 4], 5];const flattened1 = arr1.flat();console.log(flattened1); // [ 1, 2, 3, 4, 5 ] const arr2 = [1, 2, [3, 4, [5, 6]]]; const flattened2 = arr2.flat();console.log(flattened2); // [1, 2, 3, 4, [5, 6]]", "e": 6151, "s": 5926, "text": null }, { "code": null, "e": 6160, "s": 6151, "text": "Output: " }, { "code": null, "e": 6197, "s": 6160, "text": "[1, 2, 3, 4, 5]\n[1, 2, 3, 4, [5, 6]]" }, { "code": null, "e": 6381, "s": 6197, "text": "7. forEach() Method: This is one of the most used method. It is used to call or execute the provided/passed function once for each element in an array. It modifies the original array." }, { "code": null, "e": 6389, "s": 6381, "text": "Input: " }, { "code": null, "e": 6398, "s": 6389, "text": "function" }, { "code": null, "e": 6406, "s": 6398, "text": "Output:" }, { "code": null, "e": 6416, "s": 6406, "text": "undefined" }, { "code": null, "e": 6427, "s": 6416, "text": "Javascript" }, { "code": "const employees = [ { name: \"Sam\", age: 25, role: \"Developer\" }, { name: \"John\", age: 32, role: \"Manager\" }, { name: \"Ronaldo\", age: 29, role: \"Architect\" }, { name: \"Perker\", age: 25, role: \"Developer\" }, { name: \"Sophia\", age: 38, role: \"Director\" }, { name: \"kristine\", age: 21, role: \"Developer\" },]; function increaseAgeByOne(employee) { employee.age += 1;}employees.forEach(increaseAgeByOne);console.log(employees);", "e": 6893, "s": 6427, "text": null }, { "code": null, "e": 6901, "s": 6893, "text": "Output:" }, { "code": null, "e": 7193, "s": 6901, "text": "[\n { name: 'Sam', age: 26, role: 'Developer' },\n { name: 'John', age: 33, role: 'Manager' },\n { name: 'Ronaldo', age: 30, role: 'Architect' },\n { name: 'Perker', age: 26, role: 'Developer' },\n { name: 'Sophia', age: 39, role: 'Director' },\n { name: 'kristine', age: 22, role: 'Developer' }\n]" }, { "code": null, "e": 7364, "s": 7193, "text": "8. includes() Method: This method is used to test whether an element is present in an array or not. It checks for a value in primitive and reference in case of an object." }, { "code": null, "e": 7373, "s": 7364, "text": "Input: " }, { "code": null, "e": 7379, "s": 7373, "text": "value" }, { "code": null, "e": 7387, "s": 7379, "text": "Output:" }, { "code": null, "e": 7437, "s": 7387, "text": "Boolean value weather array includes value or not" }, { "code": null, "e": 7448, "s": 7437, "text": "Javascript" }, { "code": "const numbers = [1, 6, 8, 11, 5, 9, 4];console.log( numbers.includes(6) ); console.log( numbers.includes(3) );", "e": 7559, "s": 7448, "text": null }, { "code": null, "e": 7567, "s": 7559, "text": "Output:" }, { "code": null, "e": 7578, "s": 7567, "text": "true\nfalse" }, { "code": null, "e": 7599, "s": 7578, "text": "In case of an object" }, { "code": null, "e": 7610, "s": 7599, "text": "Javascript" }, { "code": "const arch = { name: \"Ronaldo\", age: 29, role: \"Architect\" }; const employees = [ { name: \"Sam\", age: 25, role: \"Developer\" }, { name: \"John\", age: 32, role: \"Manager\" }, arch, { name: \"Perker\", age: 25, role: \"Developer\" }, { name: \"Sophia\", age: 38, role: \"Director\" }, { name: \"kristine\", age: 21, role: \"Developer\" },]; console.log(employees.includes(arch));", "e": 7979, "s": 7610, "text": null }, { "code": null, "e": 7987, "s": 7979, "text": "Output:" }, { "code": null, "e": 7992, "s": 7987, "text": "true" }, { "code": null, "e": 8254, "s": 7992, "text": "9. indexOf() Method: This method returns the first element index that passes the test with the provided function. It takes a value as input. It should be used in case of primitive. As in the case of objects, it will check its reference. Check is case-sensitive." }, { "code": null, "e": 8262, "s": 8254, "text": "Input: " }, { "code": null, "e": 8268, "s": 8262, "text": "value" }, { "code": null, "e": 8276, "s": 8268, "text": "Output:" }, { "code": null, "e": 8319, "s": 8276, "text": "element index that passes the test else -1" }, { "code": null, "e": 8330, "s": 8319, "text": "Javascript" }, { "code": "const names = [\"Sam\", \"John\", \"Ronaldo\", \"Perker\", \"Sophia\", \"kristine\"];names.indexOf(\"John\"); names.indexOf(\"john\");", "e": 8454, "s": 8330, "text": null }, { "code": null, "e": 8462, "s": 8454, "text": "Output:" }, { "code": null, "e": 8467, "s": 8462, "text": "1\n-1" }, { "code": null, "e": 8618, "s": 8467, "text": "10. join() Method: This method concatenates the array values into a string separated by comma(if no separator is provided) or with separator provided." }, { "code": null, "e": 8626, "s": 8618, "text": "Input: " }, { "code": null, "e": 8636, "s": 8626, "text": "separator" }, { "code": null, "e": 8644, "s": 8636, "text": "Output:" }, { "code": null, "e": 8655, "s": 8644, "text": "New string" }, { "code": null, "e": 8666, "s": 8655, "text": "Javascript" }, { "code": "const names = [\"Sam\", \"John\", \"Ronaldo\", \"Perker\", \"Sophia\", \"kristine\"];console.log( names.join() ); console.log( names.join(\" -> \") );", "e": 8806, "s": 8666, "text": null }, { "code": null, "e": 8814, "s": 8806, "text": "Output:" }, { "code": null, "e": 8919, "s": 8814, "text": "'Sam, John, Ronaldo, Perker, Sophia, kristine'\n 'Sam -> John -> Ronaldo -> Perker -> Sophia -> kristine'" }, { "code": null, "e": 9172, "s": 8919, "text": "11. lastIndexOf() Method: It searches for an element in an array and returns the last index of the elements provided in an array. It takes a value as input. It should be used in case of primitive. As in the case of objects, it will check its reference." }, { "code": null, "e": 9180, "s": 9172, "text": "Input: " }, { "code": null, "e": 9186, "s": 9180, "text": "value" }, { "code": null, "e": 9194, "s": 9186, "text": "Output:" }, { "code": null, "e": 9270, "s": 9194, "text": "last element index that is equal(test using ===) \nto value provided else -1" }, { "code": null, "e": 9281, "s": 9270, "text": "Javascript" }, { "code": "const roles = [ \"Developer\", \"Manager\", \"Architect\", \"Developer\", \"Director\", \"Developer\"]; console.log(roles.lastIndexOf(\"Developer\"));", "e": 9421, "s": 9281, "text": null }, { "code": null, "e": 9429, "s": 9421, "text": "Output:" }, { "code": null, "e": 9431, "s": 9429, "text": "5" }, { "code": null, "e": 9556, "s": 9431, "text": "12. map() Method: This method call the provided function and execute this function for each element. It returns a new array." }, { "code": null, "e": 9563, "s": 9556, "text": "Input:" }, { "code": null, "e": 9572, "s": 9563, "text": "function" }, { "code": null, "e": 9580, "s": 9572, "text": "Output:" }, { "code": null, "e": 9590, "s": 9580, "text": "new array" }, { "code": null, "e": 9601, "s": 9590, "text": "Javascript" }, { "code": "const employees = [ { name: \"Sam\", age: 25, role: \"Developer\" }, { name: \"John\", age: 32, role: \"Manager\" }, { name: \"Ronaldo\", age: 29, role: \"Architect\" }, { name: \"Perker\", age: 25, role: \"Developer\" }, { name: \"Sophia\", age: 38, role: \"Director\" }, { name: \"kristine\", age: 21, role: \"Developer\" },]; function getName(employee) { return employee.name;} const names = employees.map(getName);console.log(names); function concetenateNameWithAge(employee) { return employee.name + \" \" + employee.age;}const nameWithAge = employees.map(concetenateNameWithAge);console.log(nameWithAge);", "e": 10226, "s": 9601, "text": null }, { "code": null, "e": 10234, "s": 10226, "text": "Output:" }, { "code": null, "e": 10381, "s": 10234, "text": " [ 'Sam', 'John', 'Ronaldo', 'Perker', 'Sophia', 'kristine' ]\n[\n 'Sam 25',\n 'John 32',\n 'Ronaldo 29',\n 'Perker 25',\n 'Sophia 38',\n 'kristine 21'\n]" }, { "code": null, "e": 10474, "s": 10381, "text": "13. pop() Method: It removes the last element from an array and returns the removed element." }, { "code": null, "e": 10483, "s": 10474, "text": "Output: " }, { "code": null, "e": 10499, "s": 10483, "text": "Removed element" }, { "code": null, "e": 10510, "s": 10499, "text": "Javascript" }, { "code": "const employees = [ { name: \"Sam\", age: 25, role: \"Developer\" }, { name: \"John\", age: 32, role: \"Manager\" }, { name: \"Ronaldo\", age: 29, role: \"Architect\" }, { name: \"Perker\", age: 25, role: \"Developer\" }, { name: \"Sophia\", age: 38, role: \"Director\" }, { name: \"kristine\", age: 21, role: \"Developer\" },]; const removedEmployee = employees.pop();console.log(removedEmployee); console.log(employees.length); ", "e": 10956, "s": 10510, "text": null }, { "code": null, "e": 10964, "s": 10956, "text": "Output:" }, { "code": null, "e": 11016, "s": 10964, "text": "{ name: 'kristine', age: 21, role: 'Developer' }\n 5" }, { "code": null, "e": 11097, "s": 11016, "text": "14. push() Method: It adds or pushes an element as the last element in an array." }, { "code": null, "e": 11104, "s": 11097, "text": "Input:" }, { "code": null, "e": 11118, "s": 11104, "text": "Array element" }, { "code": null, "e": 11127, "s": 11118, "text": "Output: " }, { "code": null, "e": 11150, "s": 11127, "text": "new length of an array" }, { "code": null, "e": 11161, "s": 11150, "text": "Javascript" }, { "code": "const employees = [ { name: \"Sam\", age: 25, role: \"Developer\" }, { name: \"John\", age: 32, role: \"Manager\" }, { name: \"Ronaldo\", age: 29, role: \"Architect\" }, { name: \"Perker\", age: 25, role: \"Developer\" }, { name: \"Sophia\", age: 38, role: \"Director\" }, { name: \"kristine\", age: 21, role: \"Developer\" },]; const totalEmployees = employees.push({ name: \"Donald\", age: 21, role: \"Manager\" });console.log(employees);console.log( totalEmployees );", "e": 11642, "s": 11161, "text": null }, { "code": null, "e": 11650, "s": 11642, "text": "Output:" }, { "code": null, "e": 11991, "s": 11650, "text": "[\n { name: 'Sam', age: 25, role: 'Developer' },\n { name: 'John', age: 32, role: 'Manager' },\n { name: 'Ronaldo', age: 29, role: 'Architect' },\n { name: 'Perker', age: 25, role: 'Developer' },\n { name: 'Sophia', age: 38, role: 'Director' },\n { name: 'kristine', age: 21, role: 'Developer' },\n { name: 'Donald', age: 21, role: 'Manager' }\n]\n7" }, { "code": null, "e": 12176, "s": 11991, "text": "15. reduce() Method: The array reduce() method executes the reducer function that you pass on each element and it always returns a single value. The reducer function takes 4 parameters" }, { "code": null, "e": 12188, "s": 12176, "text": "Accumulator" }, { "code": null, "e": 12202, "s": 12188, "text": "Current value" }, { "code": null, "e": 12222, "s": 12202, "text": "Array current index" }, { "code": null, "e": 12235, "s": 12222, "text": "Source array" }, { "code": null, "e": 12340, "s": 12235, "text": "Note: Reducer function always returns value and the value get assigned to accumulator in next iteration." }, { "code": null, "e": 12348, "s": 12340, "text": "Input: " }, { "code": null, "e": 12497, "s": 12348, "text": "First argument is reducer function that takes minimum \n2 value i.e. accumulator and current value. Second \nargument is initial value of accumulator." }, { "code": null, "e": 12506, "s": 12497, "text": "Output: " }, { "code": null, "e": 12522, "s": 12506, "text": "A single value." }, { "code": null, "e": 12737, "s": 12522, "text": "If accumulator value is not provided then the source array first value or initial value is taken as the second argument of the reduce method and iteration starts from next to the initial value of the source array. " }, { "code": null, "e": 12748, "s": 12737, "text": "Javascript" }, { "code": "const employees = [ { name: \"Sam\", age: 25, role: \"Developer\" }, { name: \"John\", age: 32, role: \"Manager\" }, { name: \"Ronaldo\", age: 29, role: \"Architect\" }, { name: \"Perker\", age: 25, role: \"Developer\" }, { name: \"Sophia\", age: 38, role: \"Director\" }, { name: \"kristine\", age: 21, role: \"Developer\" },]; function getRoleReducer(acc, currentValue) { acc.push(currentValue.role); return acc;}const roles = employees.reduce(getRoleReducer, []);console.log(roles);", "e": 13247, "s": 12748, "text": null }, { "code": null, "e": 13255, "s": 13247, "text": "Output:" }, { "code": null, "e": 13339, "s": 13255, "text": "[\n 'Developer',\n 'Manager',\n 'Architect',\n 'Developer',\n 'Director',\n 'Developer'\n]" }, { "code": null, "e": 13460, "s": 13339, "text": "16. reduceRight() Method: It is exactly the same as the Array reduce method but the iteration starts from right to left." }, { "code": null, "e": 13471, "s": 13460, "text": "Javascript" }, { "code": "const employees = [ { name: \"Sam\", age: 25, role: \"Developer\" }, { name: \"John\", age: 32, role: \"Manager\" }, { name: \"Ronaldo\", age: 29, role: \"Architect\" }, { name: \"Perker\", age: 25, role: \"Developer\" }, { name: \"Sophia\", age: 38, role: \"Director\" }, { name: \"kristine\", age: 21, role: \"Developer\" },]; function getRoleReducer(acc, currentValue) { acc.push(currentValue.role); return acc;}const roles = employees.reduceRight(getRoleReducer, []);console.log(roles);", "e": 13975, "s": 13471, "text": null }, { "code": null, "e": 13983, "s": 13975, "text": "Output:" }, { "code": null, "e": 14067, "s": 13983, "text": "[\n 'Developer',\n 'Director',\n 'Developer',\n 'Architect',\n 'Manager',\n 'Developer'\n]" }, { "code": null, "e": 14130, "s": 14067, "text": "17. reverse() Method: This method reverses the array elements." }, { "code": null, "e": 14139, "s": 14130, "text": "Output: " }, { "code": null, "e": 14177, "s": 14139, "text": "Same array but with reversed elements" }, { "code": null, "e": 14188, "s": 14177, "text": "Javascript" }, { "code": "const employees = [ { name: \"Sam\", age: 25, role: \"Developer\" }, { name: \"John\", age: 32, role: \"Manager\" }, { name: \"Ronaldo\", age: 29, role: \"Architect\" }, { name: \"Perker\", age: 25, role: \"Developer\" }, { name: \"Sophia\", age: 38, role: \"Director\" }, { name: \"kristine\", age: 21, role: \"Developer\" },]; const reversedEmployees = employees.reverse();console.log(reversedEmployees);console.log(employees === reversedEmployees);", "e": 14651, "s": 14188, "text": null }, { "code": null, "e": 14659, "s": 14651, "text": "Output:" }, { "code": null, "e": 14956, "s": 14659, "text": "[\n { name: 'kristine', age: 21, role: 'Developer' },\n { name: 'Sophia', age: 38, role: 'Director' },\n { name: 'Perker', age: 25, role: 'Developer' },\n { name: 'Ronaldo', age: 29, role: 'Architect' },\n { name: 'John', age: 32, role: 'Manager' },\n { name: 'Sam', age: 25, role: 'Developer' }\n]\ntrue" }, { "code": null, "e": 15052, "s": 14956, "text": "18. shift() Method: It removes the first element from an array and returns the removed element." }, { "code": null, "e": 15061, "s": 15052, "text": "Output: " }, { "code": null, "e": 15119, "s": 15061, "text": "removed element or if an array is empty returns undefined" }, { "code": null, "e": 15130, "s": 15119, "text": "Javascript" }, { "code": " const employees = [ { name: \"Sam\", age: 25, role: \"Developer\" }, { name: \"John\", age: 32, role: \"Manager\" }, { name: \"Ronaldo\", age: 29, role: \"Architect\" }, { name: \"Perker\", age: 25, role: \"Developer\" }, { name: \"Sophia\", age: 38, role: \"Director\" }, { name: \"kristine\", age: 21, role: \"Developer\" },]; const removedEmployee = employees.shift();console.log(removedEmployee);console.log(employees);", "e": 15569, "s": 15130, "text": null }, { "code": null, "e": 15577, "s": 15569, "text": "Output:" }, { "code": null, "e": 15867, "s": 15577, "text": "{ name: 'Sam', age: 25, role: 'Developer' }\n[\n { name: 'John', age: 32, role: 'Manager' },\n { name: 'Ronaldo', age: 29, role: 'Architect' },\n { name: 'Perker', age: 25, role: 'Developer' },\n { name: 'Sophia', age: 38, role: 'Director' },\n { name: 'kristine', age: 21, role: 'Developer' }\n]" }, { "code": null, "e": 16231, "s": 15867, "text": "19. slice() Method: The slice() method returns the new array with the elements specified within the starting and ending index. The new array contains the element at the starting index but does not include the element at the end index. If the end index is not provided then it is considered as an array.length-1. The slice method doesn’t change the original array." }, { "code": null, "e": 16240, "s": 16231, "text": "Input: " }, { "code": null, "e": 16266, "s": 16240, "text": "Start index and end index" }, { "code": null, "e": 16275, "s": 16266, "text": "Output: " }, { "code": null, "e": 16286, "s": 16275, "text": " New array" }, { "code": null, "e": 16291, "s": 16286, "text": "HTML" }, { "code": " const employees = [ { name: \"Sam\", age: 25, role: \"Developer\" }, { name: \"John\", age: 32, role: \"Manager\" }, { name: \"Ronaldo\", age: 29, role: \"Architect\" }, { name: \"Perker\", age: 25, role: \"Developer\" }, { name: \"Sophia\", age: 38, role: \"Director\" }, { name: \"kristine\", age: 21, role: \"Developer\" },]; const someEmployees = employees.slice(1, 3);console.log(someEmployees);console.log(employees);", "e": 16730, "s": 16291, "text": null }, { "code": null, "e": 16738, "s": 16730, "text": "Output:" }, { "code": null, "e": 17128, "s": 16738, "text": "[\n { name: 'John', age: 32, role: 'Manager' },\n { name: 'Ronaldo', age: 29, role: 'Architect' }\n]\n[\n { name: 'Sam', age: 25, role: 'Developer' },\n { name: 'John', age: 32, role: 'Manager' },\n { name: 'Ronaldo', age: 29, role: 'Architect' },\n { name: 'Perker', age: 25, role: 'Developer' },\n { name: 'Sophia', age: 38, role: 'Director' },\n { name: 'kristine', age: 21, role: 'Developer' }\n]" }, { "code": null, "e": 17437, "s": 17128, "text": "20. some() Method: This method checks if any one of the elements in the array passes the test provided by the predicate function. If in any array index the test pass some method returns true else false. It just checks the element exists in an array. It returns as soon as the predicate function returns true." }, { "code": null, "e": 17445, "s": 17437, "text": "Input: " }, { "code": null, "e": 17464, "s": 17445, "text": "predicate function" }, { "code": null, "e": 17473, "s": 17464, "text": "Output: " }, { "code": null, "e": 17481, "s": 17473, "text": "Boolean" }, { "code": null, "e": 17492, "s": 17481, "text": "Javascript" }, { "code": "function checkIfDevExist(employee) { return employee.role === \"Developer\";}const isDeveloperExist = employees.some(checkIfDevExist);console.log(isDeveloperExist);", "e": 17656, "s": 17492, "text": null }, { "code": null, "e": 17664, "s": 17656, "text": "Output:" }, { "code": null, "e": 17669, "s": 17664, "text": "true" }, { "code": null, "e": 17837, "s": 17669, "text": "21. sort() Method: This method sorts the array in ascending order(default behavior if compare function is not specified). This method mutates the original array.Input:" }, { "code": null, "e": 17864, "s": 17837, "text": "optional comparer function" }, { "code": null, "e": 17872, "s": 17864, "text": "Output:" }, { "code": null, "e": 17885, "s": 17872, "text": "sorted array" }, { "code": null, "e": 17896, "s": 17885, "text": "Javascript" }, { "code": "const names = [\"Sam\", \"John\", \"Ronaldo\", \"Perker\", \"Sophia\", \"kristine\"];names.sort();console.log(names);", "e": 18002, "s": 17896, "text": null }, { "code": null, "e": 18010, "s": 18002, "text": "Output:" }, { "code": null, "e": 18072, "s": 18010, "text": " [ 'John', 'Perker', 'Ronaldo', 'Sam', 'Sophia', 'kristine' ]" }, { "code": null, "e": 18213, "s": 18072, "text": "22. splice() Method: The splice() method in an array is used to add, remove, or replace elements in an array. It mutates the original array." }, { "code": null, "e": 18220, "s": 18213, "text": "Input:" }, { "code": null, "e": 18393, "s": 18220, "text": "Starting index from where changes will takes place.\n(optional) No of element to delete or remove from the start index.\n(optional) The elements to add at starting index. " }, { "code": null, "e": 18402, "s": 18393, "text": "Output: " }, { "code": null, "e": 18431, "s": 18402, "text": "array with removed elements." }, { "code": null, "e": 18442, "s": 18431, "text": "Javascript" }, { "code": "const employees = [ { name: \"Sam\", age: 25, role: \"Developer\" }, { name: \"John\", age: 32, role: \"Manager\" }, { name: \"Ronaldo\", age: 29, role: \"Architect\" }, { name: \"Perker\", age: 25, role: \"Developer\" }, { name: \"Sophia\", age: 38, role: \"Director\" }, { name: \"kristine\", age: 21, role: \"Developer\" },]; const removedElements = employees.splice(3, 1, { name: \"kristine\", age: 21, role: \"Developer\",}); console.log(removedElements);console.log(employees);", "e": 18950, "s": 18442, "text": null }, { "code": null, "e": 18958, "s": 18950, "text": "Output:" }, { "code": null, "e": 19303, "s": 18958, "text": "[ { name: 'Perker', age: 25, role: 'Developer' } ]\n[\n { name: 'Sam', age: 25, role: 'Developer' },\n { name: 'John', age: 32, role: 'Manager' },\n { name: 'Ronaldo', age: 29, role: 'Architect' },\n { name: 'kristine', age: 21, role: 'Developer' },\n { name: 'Sophia', age: 38, role: 'Director' },\n { name: 'kristine', age: 21, role: 'Developer' }\n]" }, { "code": null, "e": 19393, "s": 19303, "text": "23. unshift() Method: It adds or inserts an element at the starting position of an array." }, { "code": null, "e": 19401, "s": 19393, "text": "Input: " }, { "code": null, "e": 19419, "s": 19401, "text": "Element to insert" }, { "code": null, "e": 19429, "s": 19419, "text": "Output: " }, { "code": null, "e": 19466, "s": 19429, "text": "Array length after element insertion" }, { "code": null, "e": 19477, "s": 19466, "text": "Javascript" }, { "code": "const employees = [ { name: \"Sam\", age: 25, role: \"Developer\" }, { name: \"John\", age: 32, role: \"Manager\" }, { name: \"Ronaldo\", age: 29, role: \"Architect\" }, { name: \"Perker\", age: 25, role: \"Developer\" }, { name: \"Sophia\", age: 38, role: \"Director\" }, { name: \"kristine\", age: 21, role: \"Developer\" },]; const totalNoOfemployees = employees.unshift({ name: \"kristine\", age: 21, role: \"Developer\",}); console.log(totalNoOfemployees);console.log(employees);", "e": 19986, "s": 19477, "text": null }, { "code": null, "e": 19994, "s": 19986, "text": "Output:" }, { "code": null, "e": 20339, "s": 19994, "text": "7\n[\n { name: 'kristine', age: 21, role: 'Developer' },\n { name: 'Sam', age: 25, role: 'Developer' },\n { name: 'John', age: 32, role: 'Manager' },\n { name: 'Ronaldo', age: 29, role: 'Architect' },\n { name: 'Perker', age: 25, role: 'Developer' },\n { name: 'Sophia', age: 38, role: 'Director' },\n { name: 'kristine', age: 21, role: 'Developer' }\n]" }, { "code": null, "e": 20347, "s": 20339, "text": "clintra" }, { "code": null, "e": 20356, "s": 20347, "text": "sweetyty" }, { "code": null, "e": 20373, "s": 20356, "text": "javascript-array" }, { "code": null, "e": 20392, "s": 20373, "text": "JavaScript-Methods" }, { "code": null, "e": 20403, "s": 20392, "text": "JavaScript" }, { "code": null, "e": 20420, "s": 20403, "text": "Web Technologies" }, { "code": null, "e": 20518, "s": 20420, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 20579, "s": 20518, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 20619, "s": 20579, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 20661, "s": 20619, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 20702, "s": 20661, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 20724, "s": 20702, "text": "JavaScript | Promises" }, { "code": null, "e": 20757, "s": 20724, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 20819, "s": 20757, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 20880, "s": 20819, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 20930, "s": 20880, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Transaction Isolation Levels in DBMS
01 Feb, 2022 Prerequisite – Concurrency control in DBMS, ACID Properties in DBMS As we know that, in order to maintain consistency in a database, it follows ACID properties. Among these four properties (Atomicity, Consistency, Isolation, and Durability) Isolation determines how transaction integrity is visible to other users and systems. It means that a transaction should take place in a system in such a way that it is the only transaction that is accessing the resources in a database system. Isolation levels define the degree to which a transaction must be isolated from the data modifications made by any other transaction in the database system. A transaction isolation level is defined by the following phenomena – Dirty Read – A Dirty read is a situation when a transaction reads data that has not yet been committed. For example, Let’s say transaction 1 updates a row and leaves it uncommitted, meanwhile, Transaction 2 reads the updated row. If transaction 1 rolls back the change, transaction 2 will have read data that is considered never to have existed. Non Repeatable read – Non Repeatable read occurs when a transaction reads the same row twice and gets a different value each time. For example, suppose transaction T1 reads data. Due to concurrency, another transaction T2 updates the same data and commit, Now if transaction T1 rereads the same data, it will retrieve a different value. Phantom Read – Phantom Read occurs when two same queries are executed, but the rows retrieved by the two, are different. For example, suppose transaction T1 retrieves a set of rows that satisfy some search criteria. Now, Transaction T2 generates some new rows that match the search criteria for transaction T1. If transaction T1 re-executes the statement that reads the rows, it gets a different set of rows this time. Based on these phenomena, The SQL standard defines four isolation levels : Read Uncommitted – Read Uncommitted is the lowest isolation level. In this level, one transaction may read not yet committed changes made by other transactions, thereby allowing dirty reads. At this level, transactions are not isolated from each other.Read Committed – This isolation level guarantees that any data read is committed at the moment it is read. Thus it does not allow dirty read. The transaction holds a read or write lock on the current row, and thus prevents other transactions from reading, updating, or deleting it.Repeatable Read – This is the most restrictive isolation level. The transaction holds read locks on all rows it references and writes locks on referenced rows for update and delete actions. Since other transactions cannot read, update or delete these rows, consequently it avoids non-repeatable read.Serializable – This is the highest isolation level. A serializable execution is guaranteed to be serializable. Serializable execution is defined to be an execution of operations in which concurrently executing transactions appears to be serially executing. Read Uncommitted – Read Uncommitted is the lowest isolation level. In this level, one transaction may read not yet committed changes made by other transactions, thereby allowing dirty reads. At this level, transactions are not isolated from each other. Read Committed – This isolation level guarantees that any data read is committed at the moment it is read. Thus it does not allow dirty read. The transaction holds a read or write lock on the current row, and thus prevents other transactions from reading, updating, or deleting it. Repeatable Read – This is the most restrictive isolation level. The transaction holds read locks on all rows it references and writes locks on referenced rows for update and delete actions. Since other transactions cannot read, update or delete these rows, consequently it avoids non-repeatable read. Serializable – This is the highest isolation level. A serializable execution is guaranteed to be serializable. Serializable execution is defined to be an execution of operations in which concurrently executing transactions appears to be serially executing. The Table is given below clearly depicts the relationship between isolation levels, read phenomena, and locks : Anomaly Serializable is not the same as Serializable. That is, it is necessary, but not sufficient that a Serializable schedule should be free of all three phenomena types. References – Isolation – Wikipedia Transaction Isolation Levels – docs.microsoft SaurabhKushwaha shyam.patil55555 abhidas(zanty) DBMS GATE CS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL | Join (Inner, Left, Right and Full Joins) SQL | WITH clause SQL query to find second highest salary? CTE in SQL Difference between Clustered and Non-clustered index Layers of OSI Model TCP/IP Model Types of Operating Systems Page Replacement Algorithms in Operating Systems Inter Process Communication (IPC)
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Feb, 2022" }, { "code": null, "e": 123, "s": 54, "text": "Prerequisite – Concurrency control in DBMS, ACID Properties in DBMS " }, { "code": null, "e": 768, "s": 123, "text": "As we know that, in order to maintain consistency in a database, it follows ACID properties. Among these four properties (Atomicity, Consistency, Isolation, and Durability) Isolation determines how transaction integrity is visible to other users and systems. It means that a transaction should take place in a system in such a way that it is the only transaction that is accessing the resources in a database system. Isolation levels define the degree to which a transaction must be isolated from the data modifications made by any other transaction in the database system. A transaction isolation level is defined by the following phenomena – " }, { "code": null, "e": 1116, "s": 770, "text": "Dirty Read – A Dirty read is a situation when a transaction reads data that has not yet been committed. For example, Let’s say transaction 1 updates a row and leaves it uncommitted, meanwhile, Transaction 2 reads the updated row. If transaction 1 rolls back the change, transaction 2 will have read data that is considered never to have existed." }, { "code": null, "e": 1453, "s": 1116, "text": "Non Repeatable read – Non Repeatable read occurs when a transaction reads the same row twice and gets a different value each time. For example, suppose transaction T1 reads data. Due to concurrency, another transaction T2 updates the same data and commit, Now if transaction T1 rereads the same data, it will retrieve a different value." }, { "code": null, "e": 1872, "s": 1453, "text": "Phantom Read – Phantom Read occurs when two same queries are executed, but the rows retrieved by the two, are different. For example, suppose transaction T1 retrieves a set of rows that satisfy some search criteria. Now, Transaction T2 generates some new rows that match the search criteria for transaction T1. If transaction T1 re-executes the statement that reads the rows, it gets a different set of rows this time." }, { "code": null, "e": 1948, "s": 1872, "text": "Based on these phenomena, The SQL standard defines four isolation levels : " }, { "code": null, "e": 3040, "s": 1950, "text": "Read Uncommitted – Read Uncommitted is the lowest isolation level. In this level, one transaction may read not yet committed changes made by other transactions, thereby allowing dirty reads. At this level, transactions are not isolated from each other.Read Committed – This isolation level guarantees that any data read is committed at the moment it is read. Thus it does not allow dirty read. The transaction holds a read or write lock on the current row, and thus prevents other transactions from reading, updating, or deleting it.Repeatable Read – This is the most restrictive isolation level. The transaction holds read locks on all rows it references and writes locks on referenced rows for update and delete actions. Since other transactions cannot read, update or delete these rows, consequently it avoids non-repeatable read.Serializable – This is the highest isolation level. A serializable execution is guaranteed to be serializable. Serializable execution is defined to be an execution of operations in which concurrently executing transactions appears to be serially executing." }, { "code": null, "e": 3293, "s": 3040, "text": "Read Uncommitted – Read Uncommitted is the lowest isolation level. In this level, one transaction may read not yet committed changes made by other transactions, thereby allowing dirty reads. At this level, transactions are not isolated from each other." }, { "code": null, "e": 3575, "s": 3293, "text": "Read Committed – This isolation level guarantees that any data read is committed at the moment it is read. Thus it does not allow dirty read. The transaction holds a read or write lock on the current row, and thus prevents other transactions from reading, updating, or deleting it." }, { "code": null, "e": 3876, "s": 3575, "text": "Repeatable Read – This is the most restrictive isolation level. The transaction holds read locks on all rows it references and writes locks on referenced rows for update and delete actions. Since other transactions cannot read, update or delete these rows, consequently it avoids non-repeatable read." }, { "code": null, "e": 4133, "s": 3876, "text": "Serializable – This is the highest isolation level. A serializable execution is guaranteed to be serializable. Serializable execution is defined to be an execution of operations in which concurrently executing transactions appears to be serially executing." }, { "code": null, "e": 4246, "s": 4133, "text": "The Table is given below clearly depicts the relationship between isolation levels, read phenomena, and locks : " }, { "code": null, "e": 4420, "s": 4246, "text": "Anomaly Serializable is not the same as Serializable. That is, it is necessary, but not sufficient that a Serializable schedule should be free of all three phenomena types. " }, { "code": null, "e": 4502, "s": 4420, "text": "References – Isolation – Wikipedia Transaction Isolation Levels – docs.microsoft " }, { "code": null, "e": 4520, "s": 4504, "text": "SaurabhKushwaha" }, { "code": null, "e": 4537, "s": 4520, "text": "shyam.patil55555" }, { "code": null, "e": 4552, "s": 4537, "text": "abhidas(zanty)" }, { "code": null, "e": 4557, "s": 4552, "text": "DBMS" }, { "code": null, "e": 4565, "s": 4557, "text": "GATE CS" }, { "code": null, "e": 4570, "s": 4565, "text": "DBMS" }, { "code": null, "e": 4668, "s": 4570, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4715, "s": 4668, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 4733, "s": 4715, "text": "SQL | WITH clause" }, { "code": null, "e": 4774, "s": 4733, "text": "SQL query to find second highest salary?" }, { "code": null, "e": 4785, "s": 4774, "text": "CTE in SQL" }, { "code": null, "e": 4838, "s": 4785, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 4858, "s": 4838, "text": "Layers of OSI Model" }, { "code": null, "e": 4871, "s": 4858, "text": "TCP/IP Model" }, { "code": null, "e": 4898, "s": 4871, "text": "Types of Operating Systems" }, { "code": null, "e": 4947, "s": 4898, "text": "Page Replacement Algorithms in Operating Systems" } ]
What is the difference between call and apply in JavaScript?
21 Apr, 2022 call() Method: It calls the method, taking the owner object as argument. The keyword this refers to the ‘owner’ of the function or the object it belongs to. We can call a method which can be used on different objects. Syntax: object.objectMethod.call( objectInstance, arguments ) Parameters: It accepts two parameters as mentioned above and described below: objectInstance: It holds the instance of an object. arguments: The call() method takes the comma separated arguments. apply() Method: The apply() method is used to write methods, which can be used on different objects. It is different from the function call() because it takes arguments as an array. Syntax: object.objectMethod.apply(objectInstance, arrayOfArguments) Parameters: It accepts two parameters as mentioned above and described below: objectInstance: It holds the instance of an object. arrayOfArguments: The apply() method takes the array of arguments. Difference between call() and apply() method: The only difference is call() method takes the arguments separated by comma while apply() method takes the array of arguments. Example 1: This example uses call() method to call a function. html <!DOCTYPE html><html> <head> <title>call() method</title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <button onClick="fun()"> click </button> <p id="GFG"></p> <!-- Script to use call() method to call function --> <script> function fun() { let p = { fullName: function(addr1, addr2) { return this.fName + " " + this.lName + ", " + addr1 + ", " + addr2; } } let p1 = { fName:"GFGfName", lName: "GFGlName", } let x = p.fullName.call(p1, "India", "USA"); document.getElementById("GFG").innerHTML = x; } </script> </body></html> Output: Before clicking the button: After clicking the button: Example 2: This example does the same work by using apply() method. HTML <!DOCTYPE html><html> <head> <title>JavaScript apply() method</title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <button onClick="fun()"> click </button> <p id="GFG"></p> <script> function fun() { let p = { fullName: function(addr1, addr2) { return this.fName + " " + this.lName + ", " + addr1 + ", " + addr2; } } let p1 = { fName:"GFGfName", lName: "GFGlName", } let x = p.fullName.apply(p1, ["India", "USA"]); document.getElementById("GFG").innerHTML = x; } </script> </body></html> Output : Before clicking the button: After clicking the button: Let us understand differences in a tabular form -: Syntax -: object.objectMethod.call( objectInstance, arguments ) Syntax -: object.objectMethod.apply(objectInstance, arrayOfArguments) mayank007rawa javascript-functions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request 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": 54, "s": 26, "text": "\n21 Apr, 2022" }, { "code": null, "e": 273, "s": 54, "text": "call() Method: It calls the method, taking the owner object as argument. The keyword this refers to the ‘owner’ of the function or the object it belongs to. We can call a method which can be used on different objects. " }, { "code": null, "e": 281, "s": 273, "text": "Syntax:" }, { "code": null, "e": 335, "s": 281, "text": "object.objectMethod.call( objectInstance, arguments )" }, { "code": null, "e": 413, "s": 335, "text": "Parameters: It accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 465, "s": 413, "text": "objectInstance: It holds the instance of an object." }, { "code": null, "e": 531, "s": 465, "text": "arguments: The call() method takes the comma separated arguments." }, { "code": null, "e": 714, "s": 531, "text": "apply() Method: The apply() method is used to write methods, which can be used on different objects. It is different from the function call() because it takes arguments as an array. " }, { "code": null, "e": 722, "s": 714, "text": "Syntax:" }, { "code": null, "e": 782, "s": 722, "text": "object.objectMethod.apply(objectInstance, arrayOfArguments)" }, { "code": null, "e": 860, "s": 782, "text": "Parameters: It accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 912, "s": 860, "text": "objectInstance: It holds the instance of an object." }, { "code": null, "e": 979, "s": 912, "text": "arrayOfArguments: The apply() method takes the array of arguments." }, { "code": null, "e": 1153, "s": 979, "text": "Difference between call() and apply() method: The only difference is call() method takes the arguments separated by comma while apply() method takes the array of arguments. " }, { "code": null, "e": 1217, "s": 1153, "text": "Example 1: This example uses call() method to call a function. " }, { "code": null, "e": 1222, "s": 1217, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>call() method</title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <button onClick=\"fun()\"> click </button> <p id=\"GFG\"></p> <!-- Script to use call() method to call function --> <script> function fun() { let p = { fullName: function(addr1, addr2) { return this.fName + \" \" + this.lName + \", \" + addr1 + \", \" + addr2; } } let p1 = { fName:\"GFGfName\", lName: \"GFGlName\", } let x = p.fullName.call(p1, \"India\", \"USA\"); document.getElementById(\"GFG\").innerHTML = x; } </script> </body></html>", "e": 2149, "s": 1222, "text": null }, { "code": null, "e": 2157, "s": 2149, "text": "Output:" }, { "code": null, "e": 2185, "s": 2157, "text": "Before clicking the button:" }, { "code": null, "e": 2216, "s": 2188, "text": "After clicking the button: " }, { "code": null, "e": 2284, "s": 2216, "text": "Example 2: This example does the same work by using apply() method." }, { "code": null, "e": 2289, "s": 2284, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>JavaScript apply() method</title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <button onClick=\"fun()\"> click </button> <p id=\"GFG\"></p> <script> function fun() { let p = { fullName: function(addr1, addr2) { return this.fName + \" \" + this.lName + \", \" + addr1 + \", \" + addr2; } } let p1 = { fName:\"GFGfName\", lName: \"GFGlName\", } let x = p.fullName.apply(p1, [\"India\", \"USA\"]); document.getElementById(\"GFG\").innerHTML = x; } </script> </body></html>", "e": 3154, "s": 2289, "text": null }, { "code": null, "e": 3163, "s": 3154, "text": "Output :" }, { "code": null, "e": 3192, "s": 3163, "text": "Before clicking the button: " }, { "code": null, "e": 3220, "s": 3192, "text": "After clicking the button: " }, { "code": null, "e": 3271, "s": 3220, "text": "Let us understand differences in a tabular form -:" }, { "code": null, "e": 3281, "s": 3271, "text": "Syntax -:" }, { "code": null, "e": 3335, "s": 3281, "text": "object.objectMethod.call( objectInstance, arguments )" }, { "code": null, "e": 3345, "s": 3335, "text": "Syntax -:" }, { "code": null, "e": 3405, "s": 3345, "text": "object.objectMethod.apply(objectInstance, arrayOfArguments)" }, { "code": null, "e": 3419, "s": 3405, "text": "mayank007rawa" }, { "code": null, "e": 3440, "s": 3419, "text": "javascript-functions" }, { "code": null, "e": 3447, "s": 3440, "text": "Picked" }, { "code": null, "e": 3458, "s": 3447, "text": "JavaScript" }, { "code": null, "e": 3475, "s": 3458, "text": "Web Technologies" }, { "code": null, "e": 3573, "s": 3475, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3634, "s": 3573, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3706, "s": 3634, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3746, "s": 3706, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3788, "s": 3746, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3829, "s": 3788, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3862, "s": 3829, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3924, "s": 3862, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3985, "s": 3924, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4035, "s": 3985, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
LISP - Environment Setup
If you are still willing to set up your environment for Lisp programming language, you need the following two softwares available on your computer, (a) Text Editor and (b) The Lisp Executer. This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX. The files you create with your editor are called source files and contain program source code. The source files for Lisp programs are typically named with the extension ".lisp". Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, finally execute it. The source code written in source file is the human readable source for your program. It needs to be "executed", to turn into machine language so that your CPU can actually execute the program as per instructions given. This Lisp programming language will be used to execute your source code into final executable program. I assume you have basic knowledge about a programming language. CLISP is the GNU Common LISP multi-architechtural compiler used for setting up LISP in Windows. The windows version emulates a unix environment using MingW under windows. The installer takes care of this and automatically adds clisp to the windows PATH variable. You can get the latest CLISP for Windows from here - https://sourceforge.net/projects/clisp/files/latest/download It creates a shortcut in the Start Menu by default, for the line-by-line interpreter. During installation, clisp is automatically added to your PATH variable if you select the option (RECOMMENDED) This means that you can simply open a new Command Prompt window and type “clisp” to bring up the compiler. To run a *.lisp or *.lsp file, simply use −
[ { "code": null, "e": 2385, "s": 2194, "text": "If you are still willing to set up your environment for Lisp programming language, you need the following two softwares available on your computer, (a) Text Editor and (b) The Lisp Executer." }, { "code": null, "e": 2529, "s": 2385, "text": "This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi." }, { "code": null, "e": 2711, "s": 2529, "text": "Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX." }, { "code": null, "e": 2889, "s": 2711, "text": "The files you create with your editor are called source files and contain program source code. The source files for Lisp programs are typically named with the extension \".lisp\"." }, { "code": null, "e": 3066, "s": 2889, "text": "Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, finally execute it." }, { "code": null, "e": 3286, "s": 3066, "text": "The source code written in source file is the human readable source for your program. It needs to be \"executed\", to turn into machine language so that your CPU can actually execute the program as per instructions given." }, { "code": null, "e": 3453, "s": 3286, "text": "This Lisp programming language will be used to execute your source code into final executable program. I assume you have basic knowledge about a programming language." }, { "code": null, "e": 3716, "s": 3453, "text": "CLISP is the GNU Common LISP multi-architechtural compiler used for setting up LISP in Windows. The windows version emulates a unix environment using MingW under windows. The installer takes care of this and automatically adds clisp to the windows PATH variable." }, { "code": null, "e": 3830, "s": 3716, "text": "You can get the latest CLISP for Windows from here - https://sourceforge.net/projects/clisp/files/latest/download" }, { "code": null, "e": 3916, "s": 3830, "text": "It creates a shortcut in the Start Menu by default, for the line-by-line interpreter." }, { "code": null, "e": 4135, "s": 3916, "text": "During installation, clisp is automatically added to your PATH variable if you select the option (RECOMMENDED) This means that you can simply open a new Command Prompt window and type “clisp” to bring up the compiler." } ]
Create a Tabular representation of Data in R Programming – table() Function
19 Jun, 2020 table() function in R Language is used to create a categorical representation of data with variable name and the frequency in the form of a table. Syntax: table(x) Parameters:x: Object to be converted Example 1: # R Program to create # a tabular representation of data # Creating a vectorvec = c(2, 4, 3, 1, 2, 3, 2, 1, 4, 2) # Calling table() Functiontable(vec) Output: vec 1 2 3 4 2 4 2 2 Example 2: # R Program to create # a tabular representation of data # Creating a data frame df = data.frame( "Name" = c("abc", "cde", "def"), "Gender" = c("Male", "Female", "Male") ) # Calling table() function table(df) Output: Gender Name Female Male abc 0 1 cde 1 0 def 0 1 R DataFrame-Function R List-Function R Matrix-Function R Object-Function R Vector-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Jun, 2020" }, { "code": null, "e": 175, "s": 28, "text": "table() function in R Language is used to create a categorical representation of data with variable name and the frequency in the form of a table." }, { "code": null, "e": 192, "s": 175, "text": "Syntax: table(x)" }, { "code": null, "e": 229, "s": 192, "text": "Parameters:x: Object to be converted" }, { "code": null, "e": 240, "s": 229, "text": "Example 1:" }, { "code": "# R Program to create # a tabular representation of data # Creating a vectorvec = c(2, 4, 3, 1, 2, 3, 2, 1, 4, 2) # Calling table() Functiontable(vec)", "e": 394, "s": 240, "text": null }, { "code": null, "e": 402, "s": 394, "text": "Output:" }, { "code": null, "e": 425, "s": 402, "text": "vec\n1 2 3 4 \n2 4 2 2 \n" }, { "code": null, "e": 436, "s": 425, "text": "Example 2:" }, { "code": "# R Program to create # a tabular representation of data # Creating a data frame df = data.frame( \"Name\" = c(\"abc\", \"cde\", \"def\"), \"Gender\" = c(\"Male\", \"Female\", \"Male\") ) # Calling table() function table(df) ", "e": 658, "s": 436, "text": null }, { "code": null, "e": 666, "s": 658, "text": "Output:" }, { "code": null, "e": 751, "s": 666, "text": " Gender\nName Female Male\n abc 0 1\n cde 1 0\n def 0 1\n" }, { "code": null, "e": 772, "s": 751, "text": "R DataFrame-Function" }, { "code": null, "e": 788, "s": 772, "text": "R List-Function" }, { "code": null, "e": 806, "s": 788, "text": "R Matrix-Function" }, { "code": null, "e": 824, "s": 806, "text": "R Object-Function" }, { "code": null, "e": 842, "s": 824, "text": "R Vector-Function" }, { "code": null, "e": 853, "s": 842, "text": "R Language" } ]
Table Widget in Flutter
19 Sep, 2021 Table widget is used to display items in a table layout. There is no need to use Rows and Columns to create a table. If we have multiple rows with the same width of columns then Table widget is the right approach. SliverList or Column will be most suitable if we only want to have a single column. The height of rows in the Table widget is dependent on the content inside them. But the width of the column can be changed by specifying columnWidths property. Syntax: Table({Key key, List<TableRow> children, Map<int, TableColumnWidth> columnWidths, TableColumnWidth defaultColumnWidth, TextDirection textDirection, TableBorder border, TableCellVerticalAlignment defaultVerticalAlignment, TextBaseline textBaseline}) children: This property of Table widget takes a list of table row as a parameter (List<TableRow>). TableRow, in turn, can take a list of widgets as children. columnWidhts: This property determines the width of the columns in the Table widget. textDirection: It defines the direction in which columns are ordered in Table. It can be either from left-to-right or from right-to-left. defaultColumnWidth: This property takes in TableComumnWidth class as the input parameter to set the default width of the column in the Table widget. key: This property decides how widgets will replace one another in the widget tree. border: This property takes TableBorder widget as the parameter and it sets the border of the table. By default, there is no border in Table widget. defaultVerticalAlignment: This property takes TableCellVerticalAlignment enum as the parameter value to sets the alignment of cells vertically in the table. textBaseline: This property takes TextBaseline enum as the parameter. Using this property we can specify a horizontal line uses to align text on the screen inside the Table widget. Example: The main.dart file. Dart import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root // of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Table', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); }} class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title:Text("GeeksforGeeks"), backgroundColor: Colors.green, ), body: Column( children:<Widget>[ Padding( padding: const EdgeInsets.all(8.0), child: Text("Table",textScaleFactor: 2,style: TextStyle(fontWeight:FontWeight.bold),), ), Padding( padding: const EdgeInsets.all(8.0), child: Table( // textDirection: TextDirection.rtl, // defaultVerticalAlignment: TableCellVerticalAlignment.bottom, // border:TableBorder.all(width: 2.0,color: Colors.red), children: [ TableRow( children: [ Text("Education",textScaleFactor: 1.5,), Text("Institution name",textScaleFactor: 1.5), Text("University",textScaleFactor: 1.5), ] ), TableRow( children: [ Text("B.Tech",textScaleFactor: 1.5), Text("ABESEC",textScaleFactor: 1.5), Text("AKTU",textScaleFactor: 1.5), ] ), TableRow( children: [ Text("12th",textScaleFactor: 1.5), Text("Delhi Public School",textScaleFactor: 1.5), Text("CBSE",textScaleFactor: 1.5), ] ), TableRow( children: [ Text("High School",textScaleFactor: 1.5), Text("SFS",textScaleFactor: 1.5), Text("ICSE",textScaleFactor: 1.5), ] ), ], ), ), ] ), ); }} Output: If we make the below changes to the above example: textDirection: TextDirection.ltr, border:TableBorder.all(width: 1.0,color: Colors.red) The resultant will be as depicted below: If we make the below changes to the above example: textDirection: TextDirection.ltr, defaultVerticalAlignment: TableCellVerticalAlignment.bottom, border:TableBorder.all(width: 1.0,color: Colors.red), The resultant will be as depicted below: If we make the below changes to the above example: textDirection: TextDirection.rtl, border:TableBorder.all(width: 1.0,color: Colors.red), The resultant will be as depicted below: If we make the below changes to the above example: textDirection: TextDirection.ltr, defaultVerticalAlignment: TableCellVerticalAlignment.middle, border:TableBorder.all(width: 1.5,color: Colors.red), The resultant will be as depicted below: For the complete code, you can refer to https://github.com/singhteekam/Flutter-Data-Table-and-Table-Widget ankit_kumar_ sagartomar9927 Flutter Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget ListView Class in Flutter Flutter - Stack Widget Flutter - Search Bar Flutter - FutureBuilder Widget Operators in Dart Flutter - Dialogs Flutter - Flexible Widget Flutter - ListTile Widget
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Sep, 2021" }, { "code": null, "e": 510, "s": 52, "text": "Table widget is used to display items in a table layout. There is no need to use Rows and Columns to create a table. If we have multiple rows with the same width of columns then Table widget is the right approach. SliverList or Column will be most suitable if we only want to have a single column. The height of rows in the Table widget is dependent on the content inside them. But the width of the column can be changed by specifying columnWidths property." }, { "code": null, "e": 774, "s": 510, "text": "Syntax:\nTable({Key key, \nList<TableRow> children, \nMap<int, TableColumnWidth> columnWidths, \nTableColumnWidth defaultColumnWidth, \nTextDirection textDirection, \nTableBorder border, \nTableCellVerticalAlignment defaultVerticalAlignment, \nTextBaseline textBaseline})" }, { "code": null, "e": 932, "s": 774, "text": "children: This property of Table widget takes a list of table row as a parameter (List<TableRow>). TableRow, in turn, can take a list of widgets as children." }, { "code": null, "e": 1017, "s": 932, "text": "columnWidhts: This property determines the width of the columns in the Table widget." }, { "code": null, "e": 1155, "s": 1017, "text": "textDirection: It defines the direction in which columns are ordered in Table. It can be either from left-to-right or from right-to-left." }, { "code": null, "e": 1304, "s": 1155, "text": "defaultColumnWidth: This property takes in TableComumnWidth class as the input parameter to set the default width of the column in the Table widget." }, { "code": null, "e": 1388, "s": 1304, "text": "key: This property decides how widgets will replace one another in the widget tree." }, { "code": null, "e": 1537, "s": 1388, "text": "border: This property takes TableBorder widget as the parameter and it sets the border of the table. By default, there is no border in Table widget." }, { "code": null, "e": 1694, "s": 1537, "text": "defaultVerticalAlignment: This property takes TableCellVerticalAlignment enum as the parameter value to sets the alignment of cells vertically in the table." }, { "code": null, "e": 1875, "s": 1694, "text": "textBaseline: This property takes TextBaseline enum as the parameter. Using this property we can specify a horizontal line uses to align text on the screen inside the Table widget." }, { "code": null, "e": 1904, "s": 1875, "text": "Example: The main.dart file." }, { "code": null, "e": 1909, "s": 1904, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root // of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Table', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); }} class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title:Text(\"GeeksforGeeks\"), backgroundColor: Colors.green, ), body: Column( children:<Widget>[ Padding( padding: const EdgeInsets.all(8.0), child: Text(\"Table\",textScaleFactor: 2,style: TextStyle(fontWeight:FontWeight.bold),), ), Padding( padding: const EdgeInsets.all(8.0), child: Table( // textDirection: TextDirection.rtl, // defaultVerticalAlignment: TableCellVerticalAlignment.bottom, // border:TableBorder.all(width: 2.0,color: Colors.red), children: [ TableRow( children: [ Text(\"Education\",textScaleFactor: 1.5,), Text(\"Institution name\",textScaleFactor: 1.5), Text(\"University\",textScaleFactor: 1.5), ] ), TableRow( children: [ Text(\"B.Tech\",textScaleFactor: 1.5), Text(\"ABESEC\",textScaleFactor: 1.5), Text(\"AKTU\",textScaleFactor: 1.5), ] ), TableRow( children: [ Text(\"12th\",textScaleFactor: 1.5), Text(\"Delhi Public School\",textScaleFactor: 1.5), Text(\"CBSE\",textScaleFactor: 1.5), ] ), TableRow( children: [ Text(\"High School\",textScaleFactor: 1.5), Text(\"SFS\",textScaleFactor: 1.5), Text(\"ICSE\",textScaleFactor: 1.5), ] ), ], ), ), ] ), ); }}", "e": 4246, "s": 1909, "text": null }, { "code": null, "e": 4254, "s": 4246, "text": "Output:" }, { "code": null, "e": 4305, "s": 4254, "text": "If we make the below changes to the above example:" }, { "code": null, "e": 4392, "s": 4305, "text": "textDirection: TextDirection.ltr,\nborder:TableBorder.all(width: 1.0,color: Colors.red)" }, { "code": null, "e": 4433, "s": 4392, "text": "The resultant will be as depicted below:" }, { "code": null, "e": 4484, "s": 4433, "text": "If we make the below changes to the above example:" }, { "code": null, "e": 4633, "s": 4484, "text": "textDirection: TextDirection.ltr,\ndefaultVerticalAlignment: TableCellVerticalAlignment.bottom,\nborder:TableBorder.all(width: 1.0,color: Colors.red)," }, { "code": null, "e": 4674, "s": 4633, "text": "The resultant will be as depicted below:" }, { "code": null, "e": 4725, "s": 4674, "text": "If we make the below changes to the above example:" }, { "code": null, "e": 4813, "s": 4725, "text": "textDirection: TextDirection.rtl,\nborder:TableBorder.all(width: 1.0,color: Colors.red)," }, { "code": null, "e": 4854, "s": 4813, "text": "The resultant will be as depicted below:" }, { "code": null, "e": 4905, "s": 4854, "text": "If we make the below changes to the above example:" }, { "code": null, "e": 5054, "s": 4905, "text": "textDirection: TextDirection.ltr,\ndefaultVerticalAlignment: TableCellVerticalAlignment.middle,\nborder:TableBorder.all(width: 1.5,color: Colors.red)," }, { "code": null, "e": 5095, "s": 5054, "text": "The resultant will be as depicted below:" }, { "code": null, "e": 5202, "s": 5095, "text": "For the complete code, you can refer to https://github.com/singhteekam/Flutter-Data-Table-and-Table-Widget" }, { "code": null, "e": 5215, "s": 5202, "text": "ankit_kumar_" }, { "code": null, "e": 5230, "s": 5215, "text": "sagartomar9927" }, { "code": null, "e": 5238, "s": 5230, "text": "Flutter" }, { "code": null, "e": 5243, "s": 5238, "text": "Dart" }, { "code": null, "e": 5341, "s": 5243, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5380, "s": 5341, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 5406, "s": 5380, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 5432, "s": 5406, "text": "ListView Class in Flutter" }, { "code": null, "e": 5455, "s": 5432, "text": "Flutter - Stack Widget" }, { "code": null, "e": 5476, "s": 5455, "text": "Flutter - Search Bar" }, { "code": null, "e": 5507, "s": 5476, "text": "Flutter - FutureBuilder Widget" }, { "code": null, "e": 5525, "s": 5507, "text": "Operators in Dart" }, { "code": null, "e": 5543, "s": 5525, "text": "Flutter - Dialogs" }, { "code": null, "e": 5569, "s": 5543, "text": "Flutter - Flexible Widget" } ]
How to make background image transparent using Python?
24 Jan, 2021 In this article, the task is to create a background transparent of the image in Python Library Required : First Install pillow library on your Python Application before going ahead. Python Imaging Library is a free and open-source additional library for the Python programming language that adds support for opening, manipulating, and saving many image file formats. Pillow library is necessary for this mentioned program. You can install pillow library in Python using the code pip install pillow Method : Read the image.Convert the image into RGBA format.Change the white pixels of the image into a transparent formSave the newly edited image Read the image. Convert the image into RGBA format. Change the white pixels of the image into a transparent form Save the newly edited image Example : Python3 from PIL import Image def convertImage(): img = Image.open("./image.png") img = img.convert("RGBA") datas = img.getdata() newData = [] for items in datas: if item[0] == 255 and item[1] == 255 and item[2] == 255: newData.append((255, 255, 255, 0)) else: newData.append(item) img.putdata(newData) img.save("./New.png", "PNG") print("Successful") convertImage() Output: Image-Processing Picked 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 Python OOPs Concepts Iterate over a list in Python Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jan, 2021" }, { "code": null, "e": 115, "s": 28, "text": "In this article, the task is to create a background transparent of the image in Python" }, { "code": null, "e": 134, "s": 115, "text": "Library Required :" }, { "code": null, "e": 507, "s": 134, "text": "First Install pillow library on your Python Application before going ahead. Python Imaging Library is a free and open-source additional library for the Python programming language that adds support for opening, manipulating, and saving many image file formats. Pillow library is necessary for this mentioned program. You can install pillow library in Python using the code" }, { "code": null, "e": 526, "s": 507, "text": "pip install pillow" }, { "code": null, "e": 535, "s": 526, "text": "Method :" }, { "code": null, "e": 673, "s": 535, "text": "Read the image.Convert the image into RGBA format.Change the white pixels of the image into a transparent formSave the newly edited image" }, { "code": null, "e": 689, "s": 673, "text": "Read the image." }, { "code": null, "e": 725, "s": 689, "text": "Convert the image into RGBA format." }, { "code": null, "e": 786, "s": 725, "text": "Change the white pixels of the image into a transparent form" }, { "code": null, "e": 814, "s": 786, "text": "Save the newly edited image" }, { "code": null, "e": 824, "s": 814, "text": "Example :" }, { "code": null, "e": 832, "s": 824, "text": "Python3" }, { "code": "from PIL import Image def convertImage(): img = Image.open(\"./image.png\") img = img.convert(\"RGBA\") datas = img.getdata() newData = [] for items in datas: if item[0] == 255 and item[1] == 255 and item[2] == 255: newData.append((255, 255, 255, 0)) else: newData.append(item) img.putdata(newData) img.save(\"./New.png\", \"PNG\") print(\"Successful\") convertImage()", "e": 1261, "s": 832, "text": null }, { "code": null, "e": 1269, "s": 1261, "text": "Output:" }, { "code": null, "e": 1286, "s": 1269, "text": "Image-Processing" }, { "code": null, "e": 1293, "s": 1286, "text": "Picked" }, { "code": null, "e": 1300, "s": 1293, "text": "Python" }, { "code": null, "e": 1398, "s": 1300, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1416, "s": 1398, "text": "Python Dictionary" }, { "code": null, "e": 1458, "s": 1416, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1480, "s": 1458, "text": "Enumerate() in Python" }, { "code": null, "e": 1506, "s": 1480, "text": "Python String | replace()" }, { "code": null, "e": 1538, "s": 1506, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1567, "s": 1538, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1594, "s": 1567, "text": "Python Classes and Objects" }, { "code": null, "e": 1615, "s": 1594, "text": "Python OOPs Concepts" }, { "code": null, "e": 1645, "s": 1615, "text": "Iterate over a list in Python" } ]
Tetranacci Numbers
03 Jun, 2021 The tetranacci numbers are a generalization of the Fibonacci numbers defined by the recurrence relation T(n) = T(n-1) + T(n-2) + T(n-3) + T(n-4) with T(0)=0, T(1)=1, T(2)=1, T(3)=2, For n>=4. They represent the n=4 case of the Fibonacci n-step numbers. The first few terms for n=0, 1, ... are 0, 1, 1, 2, 4, 8, 15, 29, 56, 108, 208, ... Given a number N. The task is to find the N-th tetranacci number. Examples: Input: 5 Output: 4 Input: 9 Output: 108 A naive approach is to follow the recurrence for finding the number and use recursion to solve it.Below is the implementation of the above approach. C++ Java Python3 C# PHP Javascript // A simple recursive CPP program to print// the nth tetranacci numbers.#include <iostream>using namespace std; // Function to return the// N-th tetranacci numberint printTetraRec(int n){ // base cases if (n == 0) return 0; // base cases if (n == 1 || n == 2) return 1; // base cases if (n == 3) return 2; else return printTetraRec(n - 1) + printTetraRec(n - 2) + printTetraRec(n - 3) + printTetraRec(n - 4);} // function to print the nth tetranacci numbervoid printTetra(int n){ cout << printTetraRec(n) << " ";} // Driver codeint main(){ int n = 10; printTetra(n); return 0;} // A simple recursive Java// program to print the nth// tetranacci numbers.class GFG{// Function to return the// N-th tetranacci numberstatic int printTetraRec(int n){ // base cases if (n == 0) return 0; // base cases if (n == 1 || n == 2) return 1; // base cases if (n == 3) return 2; else return printTetraRec(n - 1) + printTetraRec(n - 2) + printTetraRec(n - 3) + printTetraRec(n - 4);} // function to print the// Nth tetranacci numberstatic void printTetra(int n){ System.out.println(printTetraRec(n) + " ");} // Driver codepublic static void main(String[] args){ int n = 10; printTetra(n);}} // This code is contributed by mits # A simple recursive Python3 program# to print the nth tetranacci numbers. # Function to return the# N-th tetranacci numberdef printTetraRec(n): # base cases if (n == 0): return 0; # base cases if (n == 1 or n == 2): return 1; # base cases if (n == 3): return 2; else: return (printTetraRec(n - 1) + printTetraRec(n - 2) + printTetraRec(n - 3) + printTetraRec(n - 4)); # function to print the# nth tetranacci numberdef printTetra(n): print(printTetraRec(n), end = " "); # Driver coden = 10;printTetra(n); # This code is contributed# by mits // A simple recursive C#// program to print the nth// tetranacci numbers.class GFG{ // Function to return the// N-th tetranacci numberstatic int printTetraRec(int n){ // base cases if (n == 0) return 0; // base cases if (n == 1 || n == 2) return 1; // base cases if (n == 3) return 2; else return printTetraRec(n - 1) + printTetraRec(n - 2) + printTetraRec(n - 3) + printTetraRec(n - 4);} // function to print the// Nth tetranacci numberstatic void printTetra(int n){ System.Console.WriteLine( printTetraRec(n) + " ");} // Driver codestatic void Main(){ int n = 10; printTetra(n);}} // This code is contributed by mits <?php// A simple recursive PHP program// to print the nth tetranacci numbers. // Function to return the// N-th tetranacci numberfunction printTetraRec($n){ // base cases if ($n == 0) return 0; // base cases if ($n == 1 || $n == 2) return 1; // base cases if ($n == 3) return 2; else return printTetraRec($n - 1) + printTetraRec($n - 2) + printTetraRec($n - 3) + printTetraRec($n - 4);} // function to print the// nth tetranacci numberfunction printTetra($n){ echo printTetraRec($n) . " ";} // Driver code$n = 10;printTetra($n); // This code is contributed// by Abby_akku?> <script> // A simple recursive Javascript // program to print the nth // tetranacci numbers. // Function to return the // N-th tetranacci number function printTetraRec(n) { // base cases if (n == 0) return 0; // base cases if (n == 1 || n == 2) return 1; // base cases if (n == 3) return 2; else return printTetraRec(n - 1) + printTetraRec(n - 2) + printTetraRec(n - 3) + printTetraRec(n - 4); } // function to print the // Nth tetranacci number function printTetra(n) { document.write(printTetraRec(n) + " " + "</br>"); } let n = 10; printTetra(n); </script> 208 Time Complexity: O(4N) A better solution is to use Dynamic Programming (memoization) as there are multiple overlaps.Given below is the recursive tree for N=10. rec(10) / / \ \ rec(9) rec(8) rec(7) rec(6) / / \ \ rec(8) rec(7) rec(6) rec(5) In the above partial recursion tree, rec(8), rec(7), rec(6) have been solved twice. In drawing the complete recursion tree, it has been observed that there are many subproblems that are solved again and again. So this problem has overlapping Substructure property and recomputation of same subproblems can be avoided by either using Memoization or Tabulation.Below is the implementation of the above approach. C++ Java Python3 C# PHP Javascript // A DP based CPP// program to print// the nth tetranacci number#include <iostream>using namespace std; // Function to print the// N-th tetranacci numberint printTetra(int n){ int dp[n + 5]; // base cases dp[0] = 0; dp[1] = dp[2] = 1; dp[3] = 2; for (int i = 4; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3] + dp[i - 4]; cout << dp[n];} // Driver codeint main(){ int n = 10; printTetra(n); return 0;} // A DP based Java// program to print// the nth tetranacci number class GFG{// Function to print the// N-th tetranacci numberstatic void printTetra(int n){ int[] dp=new int[n + 5]; // base cases dp[0] = 0; dp[1] = dp[2] = 1; dp[3] = 2; for (int i = 4; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3] + dp[i - 4]; System.out.print(dp[n]);} // Driver codepublic static void main(String[] args){ int n = 10; printTetra(n);}}// This code is contributed by mits # A DP based Python3 program to print# the nth tetranacci number # Function to print the# N-th tetranacci numberdef printTetra(n): dp = [0] * (n + 5); # base cases dp[0] = 0; dp[1] = 1; dp[2] = 1; dp[3] = 2; for i in range(4, n + 1): dp[i] = (dp[i - 1] + dp[i - 2] + dp[i - 3] + dp[i - 4]); print(dp[n]); # Driver coden = 10;printTetra(n); # This code is contributed by mits // A DP based C#// program to print// the nth tetranacci number class GFG{// Function to print the// N-th tetranacci numberstatic void printTetra(int n){ int[] dp=new int[n + 5]; // base cases dp[0] = 0; dp[1] = dp[2] = 1; dp[3] = 2; for (int i = 4; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3] + dp[i - 4]; System.Console.WriteLine(dp[n]);} // Driver codestatic void Main(){ int n = 10; printTetra(n);}}// This code is contributed by mits <?php// A DP based PHP// program to print// the nth tetranacci number // Function to print the// N-th tetranacci numberfunction printTetra($n){ $dp = array_fill(0, $n + 5, 0); // base cases $dp[0] = 0; $dp[1] = $dp[2] = 1; $dp[3] = 2; for ($i = 4; $i <= $n; $i++) $dp[$i] = $dp[$i - 1] + $dp[$i - 2] + $dp[$i - 3] + $dp[$i - 4]; echo $dp[$n];} // Driver code$n = 10;printTetra($n); // This code is contributed by mits?> <script> // A DP based Javascript // program to print // the nth tetranacci number // Function to print the // N-th tetranacci number function printTetra(n) { let dp=new Array(n + 5); // base cases dp[0] = 0; dp[1] = dp[2] = 1; dp[3] = 2; for (let i = 4; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3] + dp[i - 4]; document.write(dp[n]); } let n = 10; printTetra(n); </script> 208 Time Complexity: O(N) Auxiliary Space: O(N) The time complexity above is linear, but it requires extra space. Space used can be optimized in the above solution by using four variables to keep track of the previous four numbers.Below is the implementation of the above approach. C++ Java Python3 C# PHP Javascript // A space optimized// based CPP program to// print the nth tetranacci number#include <iostream>using namespace std; // Function to print the// N-th tetranacci numbervoid printTetra(int n){ if (n < 0) return; // Initialize first // four numbers to base cases int first = 0, second = 1; int third = 1, fourth = 2; // declare a current variable int curr; if (n == 0) cout << first; else if (n == 1 || n == 2) cout << second; else if (n == 3) cout << fourth; else { // Loop to add previous // four numbers for // each number starting // from 4 and then assign // first, second, third // to second, third, fourth and // curr to fourth respectively for (int i = 4; i <= n; i++) { curr = first + second + third + fourth; first = second; second = third; third = fourth; fourth = curr; } cout << curr; }} // Driver codeint main(){ int n = 10; printTetra(n); return 0;} // A space optimized// based Java program to// print the nth tetranacci numberimport java.io.*;import java.util.*;import java.lang.*; class GFG{// Function to print the// N-th tetranacci numberstatic void printTetra(int n){ if (n < 0) return; // Initialize first // four numbers to base cases int first = 0, second = 1; int third = 1, fourth = 2; // declare a current variable int curr = 0; if (n == 0) System.out.print(first); else if (n == 1 || n == 2) System.out.print(second); else if (n == 3) System.out.print(fourth); else { // Loop to add previous // four numbers for // each number starting // from 4 and then assign // first, second, third // to second, third, fourth and // curr to fourth respectively for (int i = 4; i <= n; i++) { curr = first + second + third + fourth; first = second; second = third; third = fourth; fourth = curr; } System.out.print(curr); }} // Driver codepublic static void main(String[] args){ int n = 10; printTetra(n);}} // This code is contributed// by Akanksha Rai(Abby_akku) # A space optimized based Python3 program# to print the nth tetranacci number # Function to print the N-th# tetranacci numberdef printTetra(n): if (n < 0): return; # Initialize first four # numbers to base cases first = 0; second = 1; third = 1; fourth = 2; # declare a current variable curr = 0; if (n == 0): print(first); elif (n == 1 or n == 2): print(second); elif (n == 3): print(fourth); else: # Loop to add previous four numbers # for each number starting from 4 # and then assign first, second, # third to second, third, fourth # and curr to fourth respectively for i in range(4, n + 1): curr = first + second + third + fourth; first = second; second = third; third = fourth; fourth = curr; print(curr); # Driver coden = 10;printTetra(n); # This code is contributed by mits // A space optimized based C# program to// print the nth tetranacci numberusing System; class GFG{ // Function to print the// N-th tetranacci numberstatic void printTetra(int n){ if (n < 0) return; // Initialize first // four numbers to base cases int first = 0, second = 1; int third = 1, fourth = 2; // declare a current variable int curr = 0; if (n == 0) Console.Write(first); else if (n == 1 || n == 2) Console.Write(second); else if (n == 3) Console.Write(fourth); else { // Loop to add previous // four numbers for // each number starting // from 4 and then assign // first, second, third // to second, third, fourth and // curr to fourth respectively for (int i = 4; i <= n; i++) { curr = first + second + third + fourth; first = second; second = third; third = fourth; fourth = curr; } Console.Write(curr); }} // Driver code static public void Main () { int n = 10; printTetra(n); }} // This code is contributed ajit <?php// A space optimized based PHP program// to print the nth tetranacci number // Function to print the N-th// tetranacci number function printTetra($n){ if ($n < 0) return; // Initialize first four // numbers to base cases $first = 0; $second = 1; $third = 1; $fourth = 2; // declare a current variable $curr; if ($n == 0) echo $first; else if ($n == 1 || $n == 2) echo $second; else if ($n == 3) echo $fourth; else { // Loop to add previous four // numbers for each number // starting from 4 and then // assign first, second, third // to second, third, fourth and // curr to fourth respectively for ($i = 4; $i <= $n; $i++) { $curr = $first + $second + $third + $fourth; $first = $second; $second = $third; $third = $fourth; $fourth = $curr; } echo $curr; }} // Driver code$n = 10;printTetra($n); // This code is contributed by ajit?> <script> // A space optimized// based Javascript program to// print the nth tetranacci number // Function to print the// N-th tetranacci numberfunction printTetra(n){ if (n < 0) return; // Initialize first // four numbers to base cases var first = 0, second = 1; var third = 1, fourth = 2; // declare a current variable var curr; if (n == 0) cout << first; else if (n == 1 || n == 2) cout << second; else if (n == 3) cout << fourth; else { // Loop to add previous // four numbers for // each number starting // from 4 and then assign // first, second, third // to second, third, fourth and // curr to fourth respectively for (var i = 4; i <= n; i++) { curr = first + second + third + fourth; first = second; second = third; third = fourth; fourth = curr; } document.write( curr); }} // Driver codevar n = 10;printTetra(n); </script> 208 Time Complexity: O(N) Auxiliary Space: O(1) Mithun Kumar Akanksha_Rai jit_t nidhi_biet divyeshrabadiya07 decode2207 rutvik_56 Algorithms-Dynamic Programming Fibonacci Numbers Dynamic Programming Dynamic Programming Fibonacci Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Longest Palindromic Substring | Set 1 Floyd Warshall Algorithm | DP-16 Matrix Chain Multiplication | DP-8 Sieve of Eratosthenes Bellman–Ford Algorithm | DP-23 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Find if there is a path between two vertices in an undirected graph Minimum number of jumps to reach end Tabulation vs Memoization Longest Common Substring | DP-29
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Jun, 2021" }, { "code": null, "e": 157, "s": 52, "text": "The tetranacci numbers are a generalization of the Fibonacci numbers defined by the recurrence relation " }, { "code": null, "e": 236, "s": 157, "text": "T(n) = T(n-1) + T(n-2) + T(n-3) + T(n-4) with T(0)=0, T(1)=1, T(2)=1, T(3)=2, " }, { "code": null, "e": 458, "s": 236, "text": "For n>=4. They represent the n=4 case of the Fibonacci n-step numbers. The first few terms for n=0, 1, ... are 0, 1, 1, 2, 4, 8, 15, 29, 56, 108, 208, ... Given a number N. The task is to find the N-th tetranacci number. " }, { "code": null, "e": 469, "s": 458, "text": "Examples: " }, { "code": null, "e": 511, "s": 469, "text": "Input: 5\nOutput: 4\n\nInput: 9\nOutput: 108 " }, { "code": null, "e": 661, "s": 511, "text": "A naive approach is to follow the recurrence for finding the number and use recursion to solve it.Below is the implementation of the above approach. " }, { "code": null, "e": 665, "s": 661, "text": "C++" }, { "code": null, "e": 670, "s": 665, "text": "Java" }, { "code": null, "e": 678, "s": 670, "text": "Python3" }, { "code": null, "e": 681, "s": 678, "text": "C#" }, { "code": null, "e": 685, "s": 681, "text": "PHP" }, { "code": null, "e": 696, "s": 685, "text": "Javascript" }, { "code": "// A simple recursive CPP program to print// the nth tetranacci numbers.#include <iostream>using namespace std; // Function to return the// N-th tetranacci numberint printTetraRec(int n){ // base cases if (n == 0) return 0; // base cases if (n == 1 || n == 2) return 1; // base cases if (n == 3) return 2; else return printTetraRec(n - 1) + printTetraRec(n - 2) + printTetraRec(n - 3) + printTetraRec(n - 4);} // function to print the nth tetranacci numbervoid printTetra(int n){ cout << printTetraRec(n) << \" \";} // Driver codeint main(){ int n = 10; printTetra(n); return 0;}", "e": 1350, "s": 696, "text": null }, { "code": "// A simple recursive Java// program to print the nth// tetranacci numbers.class GFG{// Function to return the// N-th tetranacci numberstatic int printTetraRec(int n){ // base cases if (n == 0) return 0; // base cases if (n == 1 || n == 2) return 1; // base cases if (n == 3) return 2; else return printTetraRec(n - 1) + printTetraRec(n - 2) + printTetraRec(n - 3) + printTetraRec(n - 4);} // function to print the// Nth tetranacci numberstatic void printTetra(int n){ System.out.println(printTetraRec(n) + \" \");} // Driver codepublic static void main(String[] args){ int n = 10; printTetra(n);}} // This code is contributed by mits", "e": 2084, "s": 1350, "text": null }, { "code": "# A simple recursive Python3 program# to print the nth tetranacci numbers. # Function to return the# N-th tetranacci numberdef printTetraRec(n): # base cases if (n == 0): return 0; # base cases if (n == 1 or n == 2): return 1; # base cases if (n == 3): return 2; else: return (printTetraRec(n - 1) + printTetraRec(n - 2) + printTetraRec(n - 3) + printTetraRec(n - 4)); # function to print the# nth tetranacci numberdef printTetra(n): print(printTetraRec(n), end = \" \"); # Driver coden = 10;printTetra(n); # This code is contributed# by mits", "e": 2746, "s": 2084, "text": null }, { "code": "// A simple recursive C#// program to print the nth// tetranacci numbers.class GFG{ // Function to return the// N-th tetranacci numberstatic int printTetraRec(int n){ // base cases if (n == 0) return 0; // base cases if (n == 1 || n == 2) return 1; // base cases if (n == 3) return 2; else return printTetraRec(n - 1) + printTetraRec(n - 2) + printTetraRec(n - 3) + printTetraRec(n - 4);} // function to print the// Nth tetranacci numberstatic void printTetra(int n){ System.Console.WriteLine( printTetraRec(n) + \" \");} // Driver codestatic void Main(){ int n = 10; printTetra(n);}} // This code is contributed by mits", "e": 3480, "s": 2746, "text": null }, { "code": "<?php// A simple recursive PHP program// to print the nth tetranacci numbers. // Function to return the// N-th tetranacci numberfunction printTetraRec($n){ // base cases if ($n == 0) return 0; // base cases if ($n == 1 || $n == 2) return 1; // base cases if ($n == 3) return 2; else return printTetraRec($n - 1) + printTetraRec($n - 2) + printTetraRec($n - 3) + printTetraRec($n - 4);} // function to print the// nth tetranacci numberfunction printTetra($n){ echo printTetraRec($n) . \" \";} // Driver code$n = 10;printTetra($n); // This code is contributed// by Abby_akku?>", "e": 4166, "s": 3480, "text": null }, { "code": "<script> // A simple recursive Javascript // program to print the nth // tetranacci numbers. // Function to return the // N-th tetranacci number function printTetraRec(n) { // base cases if (n == 0) return 0; // base cases if (n == 1 || n == 2) return 1; // base cases if (n == 3) return 2; else return printTetraRec(n - 1) + printTetraRec(n - 2) + printTetraRec(n - 3) + printTetraRec(n - 4); } // function to print the // Nth tetranacci number function printTetra(n) { document.write(printTetraRec(n) + \" \" + \"</br>\"); } let n = 10; printTetra(n); </script>", "e": 4942, "s": 4166, "text": null }, { "code": null, "e": 4946, "s": 4942, "text": "208" }, { "code": null, "e": 4973, "s": 4948, "text": "Time Complexity: O(4N) " }, { "code": null, "e": 5111, "s": 4973, "text": "A better solution is to use Dynamic Programming (memoization) as there are multiple overlaps.Given below is the recursive tree for N=10. " }, { "code": null, "e": 5383, "s": 5111, "text": " rec(10)\n\n / / \\ \\\n\n rec(9) rec(8) rec(7) rec(6)\n\n / / \\ \\\n \n rec(8) rec(7) rec(6) rec(5)" }, { "code": null, "e": 5795, "s": 5383, "text": "In the above partial recursion tree, rec(8), rec(7), rec(6) have been solved twice. In drawing the complete recursion tree, it has been observed that there are many subproblems that are solved again and again. So this problem has overlapping Substructure property and recomputation of same subproblems can be avoided by either using Memoization or Tabulation.Below is the implementation of the above approach. " }, { "code": null, "e": 5799, "s": 5795, "text": "C++" }, { "code": null, "e": 5804, "s": 5799, "text": "Java" }, { "code": null, "e": 5812, "s": 5804, "text": "Python3" }, { "code": null, "e": 5815, "s": 5812, "text": "C#" }, { "code": null, "e": 5819, "s": 5815, "text": "PHP" }, { "code": null, "e": 5830, "s": 5819, "text": "Javascript" }, { "code": "// A DP based CPP// program to print// the nth tetranacci number#include <iostream>using namespace std; // Function to print the// N-th tetranacci numberint printTetra(int n){ int dp[n + 5]; // base cases dp[0] = 0; dp[1] = dp[2] = 1; dp[3] = 2; for (int i = 4; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3] + dp[i - 4]; cout << dp[n];} // Driver codeint main(){ int n = 10; printTetra(n); return 0;}", "e": 6294, "s": 5830, "text": null }, { "code": "// A DP based Java// program to print// the nth tetranacci number class GFG{// Function to print the// N-th tetranacci numberstatic void printTetra(int n){ int[] dp=new int[n + 5]; // base cases dp[0] = 0; dp[1] = dp[2] = 1; dp[3] = 2; for (int i = 4; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3] + dp[i - 4]; System.out.print(dp[n]);} // Driver codepublic static void main(String[] args){ int n = 10; printTetra(n);}}// This code is contributed by mits", "e": 6809, "s": 6294, "text": null }, { "code": "# A DP based Python3 program to print# the nth tetranacci number # Function to print the# N-th tetranacci numberdef printTetra(n): dp = [0] * (n + 5); # base cases dp[0] = 0; dp[1] = 1; dp[2] = 1; dp[3] = 2; for i in range(4, n + 1): dp[i] = (dp[i - 1] + dp[i - 2] + dp[i - 3] + dp[i - 4]); print(dp[n]); # Driver coden = 10;printTetra(n); # This code is contributed by mits", "e": 7238, "s": 6809, "text": null }, { "code": "// A DP based C#// program to print// the nth tetranacci number class GFG{// Function to print the// N-th tetranacci numberstatic void printTetra(int n){ int[] dp=new int[n + 5]; // base cases dp[0] = 0; dp[1] = dp[2] = 1; dp[3] = 2; for (int i = 4; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3] + dp[i - 4]; System.Console.WriteLine(dp[n]);} // Driver codestatic void Main(){ int n = 10; printTetra(n);}}// This code is contributed by mits", "e": 7739, "s": 7238, "text": null }, { "code": "<?php// A DP based PHP// program to print// the nth tetranacci number // Function to print the// N-th tetranacci numberfunction printTetra($n){ $dp = array_fill(0, $n + 5, 0); // base cases $dp[0] = 0; $dp[1] = $dp[2] = 1; $dp[3] = 2; for ($i = 4; $i <= $n; $i++) $dp[$i] = $dp[$i - 1] + $dp[$i - 2] + $dp[$i - 3] + $dp[$i - 4]; echo $dp[$n];} // Driver code$n = 10;printTetra($n); // This code is contributed by mits?>", "e": 8211, "s": 7739, "text": null }, { "code": "<script> // A DP based Javascript // program to print // the nth tetranacci number // Function to print the // N-th tetranacci number function printTetra(n) { let dp=new Array(n + 5); // base cases dp[0] = 0; dp[1] = dp[2] = 1; dp[3] = 2; for (let i = 4; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3] + dp[i - 4]; document.write(dp[n]); } let n = 10; printTetra(n); </script>", "e": 8717, "s": 8211, "text": null }, { "code": null, "e": 8721, "s": 8717, "text": "208" }, { "code": null, "e": 8768, "s": 8723, "text": "Time Complexity: O(N) Auxiliary Space: O(N) " }, { "code": null, "e": 9003, "s": 8768, "text": "The time complexity above is linear, but it requires extra space. Space used can be optimized in the above solution by using four variables to keep track of the previous four numbers.Below is the implementation of the above approach. " }, { "code": null, "e": 9007, "s": 9003, "text": "C++" }, { "code": null, "e": 9012, "s": 9007, "text": "Java" }, { "code": null, "e": 9020, "s": 9012, "text": "Python3" }, { "code": null, "e": 9023, "s": 9020, "text": "C#" }, { "code": null, "e": 9027, "s": 9023, "text": "PHP" }, { "code": null, "e": 9038, "s": 9027, "text": "Javascript" }, { "code": "// A space optimized// based CPP program to// print the nth tetranacci number#include <iostream>using namespace std; // Function to print the// N-th tetranacci numbervoid printTetra(int n){ if (n < 0) return; // Initialize first // four numbers to base cases int first = 0, second = 1; int third = 1, fourth = 2; // declare a current variable int curr; if (n == 0) cout << first; else if (n == 1 || n == 2) cout << second; else if (n == 3) cout << fourth; else { // Loop to add previous // four numbers for // each number starting // from 4 and then assign // first, second, third // to second, third, fourth and // curr to fourth respectively for (int i = 4; i <= n; i++) { curr = first + second + third + fourth; first = second; second = third; third = fourth; fourth = curr; } cout << curr; }} // Driver codeint main(){ int n = 10; printTetra(n); return 0;}", "e": 10103, "s": 9038, "text": null }, { "code": "// A space optimized// based Java program to// print the nth tetranacci numberimport java.io.*;import java.util.*;import java.lang.*; class GFG{// Function to print the// N-th tetranacci numberstatic void printTetra(int n){ if (n < 0) return; // Initialize first // four numbers to base cases int first = 0, second = 1; int third = 1, fourth = 2; // declare a current variable int curr = 0; if (n == 0) System.out.print(first); else if (n == 1 || n == 2) System.out.print(second); else if (n == 3) System.out.print(fourth); else { // Loop to add previous // four numbers for // each number starting // from 4 and then assign // first, second, third // to second, third, fourth and // curr to fourth respectively for (int i = 4; i <= n; i++) { curr = first + second + third + fourth; first = second; second = third; third = fourth; fourth = curr; } System.out.print(curr); }} // Driver codepublic static void main(String[] args){ int n = 10; printTetra(n);}} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 11329, "s": 10103, "text": null }, { "code": "# A space optimized based Python3 program# to print the nth tetranacci number # Function to print the N-th# tetranacci numberdef printTetra(n): if (n < 0): return; # Initialize first four # numbers to base cases first = 0; second = 1; third = 1; fourth = 2; # declare a current variable curr = 0; if (n == 0): print(first); elif (n == 1 or n == 2): print(second); elif (n == 3): print(fourth); else: # Loop to add previous four numbers # for each number starting from 4 # and then assign first, second, # third to second, third, fourth # and curr to fourth respectively for i in range(4, n + 1): curr = first + second + third + fourth; first = second; second = third; third = fourth; fourth = curr; print(curr); # Driver coden = 10;printTetra(n); # This code is contributed by mits", "e": 12294, "s": 11329, "text": null }, { "code": "// A space optimized based C# program to// print the nth tetranacci numberusing System; class GFG{ // Function to print the// N-th tetranacci numberstatic void printTetra(int n){ if (n < 0) return; // Initialize first // four numbers to base cases int first = 0, second = 1; int third = 1, fourth = 2; // declare a current variable int curr = 0; if (n == 0) Console.Write(first); else if (n == 1 || n == 2) Console.Write(second); else if (n == 3) Console.Write(fourth); else { // Loop to add previous // four numbers for // each number starting // from 4 and then assign // first, second, third // to second, third, fourth and // curr to fourth respectively for (int i = 4; i <= n; i++) { curr = first + second + third + fourth; first = second; second = third; third = fourth; fourth = curr; } Console.Write(curr); }} // Driver code static public void Main () { int n = 10; printTetra(n); }} // This code is contributed ajit", "e": 13464, "s": 12294, "text": null }, { "code": "<?php// A space optimized based PHP program// to print the nth tetranacci number // Function to print the N-th// tetranacci number function printTetra($n){ if ($n < 0) return; // Initialize first four // numbers to base cases $first = 0; $second = 1; $third = 1; $fourth = 2; // declare a current variable $curr; if ($n == 0) echo $first; else if ($n == 1 || $n == 2) echo $second; else if ($n == 3) echo $fourth; else { // Loop to add previous four // numbers for each number // starting from 4 and then // assign first, second, third // to second, third, fourth and // curr to fourth respectively for ($i = 4; $i <= $n; $i++) { $curr = $first + $second + $third + $fourth; $first = $second; $second = $third; $third = $fourth; $fourth = $curr; } echo $curr; }} // Driver code$n = 10;printTetra($n); // This code is contributed by ajit?>", "e": 14522, "s": 13464, "text": null }, { "code": "<script> // A space optimized// based Javascript program to// print the nth tetranacci number // Function to print the// N-th tetranacci numberfunction printTetra(n){ if (n < 0) return; // Initialize first // four numbers to base cases var first = 0, second = 1; var third = 1, fourth = 2; // declare a current variable var curr; if (n == 0) cout << first; else if (n == 1 || n == 2) cout << second; else if (n == 3) cout << fourth; else { // Loop to add previous // four numbers for // each number starting // from 4 and then assign // first, second, third // to second, third, fourth and // curr to fourth respectively for (var i = 4; i <= n; i++) { curr = first + second + third + fourth; first = second; second = third; third = fourth; fourth = curr; } document.write( curr); }} // Driver codevar n = 10;printTetra(n); </script>", "e": 15550, "s": 14522, "text": null }, { "code": null, "e": 15554, "s": 15550, "text": "208" }, { "code": null, "e": 15601, "s": 15556, "text": "Time Complexity: O(N) Auxiliary Space: O(1) " }, { "code": null, "e": 15614, "s": 15601, "text": "Mithun Kumar" }, { "code": null, "e": 15627, "s": 15614, "text": "Akanksha_Rai" }, { "code": null, "e": 15633, "s": 15627, "text": "jit_t" }, { "code": null, "e": 15644, "s": 15633, "text": "nidhi_biet" }, { "code": null, "e": 15662, "s": 15644, "text": "divyeshrabadiya07" }, { "code": null, "e": 15673, "s": 15662, "text": "decode2207" }, { "code": null, "e": 15683, "s": 15673, "text": "rutvik_56" }, { "code": null, "e": 15714, "s": 15683, "text": "Algorithms-Dynamic Programming" }, { "code": null, "e": 15724, "s": 15714, "text": "Fibonacci" }, { "code": null, "e": 15732, "s": 15724, "text": "Numbers" }, { "code": null, "e": 15752, "s": 15732, "text": "Dynamic Programming" }, { "code": null, "e": 15772, "s": 15752, "text": "Dynamic Programming" }, { "code": null, "e": 15782, "s": 15772, "text": "Fibonacci" }, { "code": null, "e": 15790, "s": 15782, "text": "Numbers" }, { "code": null, "e": 15888, "s": 15790, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15926, "s": 15888, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 15959, "s": 15926, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 15994, "s": 15959, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 16016, "s": 15994, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 16047, "s": 16016, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 16115, "s": 16047, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 16183, "s": 16115, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 16220, "s": 16183, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 16246, "s": 16220, "text": "Tabulation vs Memoization" } ]
Semantic-UI | Container
21 Jun, 2020 Semantic UI open-source framework provides a container which helps to limit content up to greatest width. The framework uses jQuery and CSS to create interactive user interfaces. It is very much similar to bootstrap usage and has different elements for creating page structure of any website. Example: The following example shows the standard container. <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Container</h2> <div class="ui container"> <p> Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements. </p> </div> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></body> </html> Output: Example: The following example shows a text container. <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Text Container</h2> <div class="ui text container"> <p> Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements. </p> </div> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></body> </html> Output: Example: The following example shows the fluid type of container. <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Fluid Container</h2> </div> <div class="ui fluid container"> <p> Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements. </p> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></body> </html> Output: Example: The following example shows aligned container. <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Container</h2> </div> <div class="ui left aligned container"> <h3>Left Aligned</h3> <p> Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements. </p> </div> <br> <div class="ui center aligned container"> <h3>Center Aligned</h3> <p> Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements. </p> </div> <br> <div class="ui right aligned container"> <h3>Right Aligned</h3> <p> Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements. </p> </div> <br> <div class="ui justified container"> <h3>Justified</h3> <p> Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements. </p> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></body> </html> Output: Semantic-UI CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form 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": "\n21 Jun, 2020" }, { "code": null, "e": 321, "s": 28, "text": "Semantic UI open-source framework provides a container which helps to limit content up to greatest width. The framework uses jQuery and CSS to create interactive user interfaces. It is very much similar to bootstrap usage and has different elements for creating page structure of any website." }, { "code": null, "e": 382, "s": 321, "text": "Example: The following example shows the standard container." }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Container</h2> <div class=\"ui container\"> <p> Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements. </p> </div> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></body> </html>", "e": 1465, "s": 382, "text": null }, { "code": null, "e": 1473, "s": 1465, "text": "Output:" }, { "code": null, "e": 1528, "s": 1473, "text": "Example: The following example shows a text container." }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Text Container</h2> <div class=\"ui text container\"> <p> Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements. </p> </div> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></body> </html>", "e": 2621, "s": 1528, "text": null }, { "code": null, "e": 2629, "s": 2621, "text": "Output:" }, { "code": null, "e": 2695, "s": 2629, "text": "Example: The following example shows the fluid type of container." }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Fluid Container</h2> </div> <div class=\"ui fluid container\"> <p> Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements. </p> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></body> </html>", "e": 3741, "s": 2695, "text": null }, { "code": null, "e": 3749, "s": 3741, "text": "Output:" }, { "code": null, "e": 3805, "s": 3749, "text": "Example: The following example shows aligned container." }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Container</h2> </div> <div class=\"ui left aligned container\"> <h3>Left Aligned</h3> <p> Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements. </p> </div> <br> <div class=\"ui center aligned container\"> <h3>Center Aligned</h3> <p> Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements. </p> </div> <br> <div class=\"ui right aligned container\"> <h3>Right Aligned</h3> <p> Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements. </p> </div> <br> <div class=\"ui justified container\"> <h3>Justified</h3> <p> Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements. </p> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></body> </html>", "e": 6186, "s": 3805, "text": null }, { "code": null, "e": 6194, "s": 6186, "text": "Output:" }, { "code": null, "e": 6206, "s": 6194, "text": "Semantic-UI" }, { "code": null, "e": 6210, "s": 6206, "text": "CSS" }, { "code": null, "e": 6227, "s": 6210, "text": "Web Technologies" }, { "code": null, "e": 6325, "s": 6227, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6373, "s": 6325, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 6435, "s": 6373, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6485, "s": 6435, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 6543, "s": 6485, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 6593, "s": 6543, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 6655, "s": 6593, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6688, "s": 6655, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 6749, "s": 6688, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6799, "s": 6749, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
numpy.mean() in Python
28 Nov, 2018 numpy.mean(arr, axis = None) : Compute the arithmetic mean (average) of the given data (array elements) along the specified axis. Parameters :arr : [array_like]input array.axis : [int or tuples of int]axis along which we want to calculate the arithmetic mean. Otherwise, it will consider arr to be flattened(works on allthe axis). axis = 0 means along the column and axis = 1 means working along the row.out : [ndarray, optional]Different array in which we want to place the result. The array must have the same dimensions as expected output.dtype : [data-type, optional]Type we desire while computing mean. Results : Arithmetic mean of the array (a scalar value if axis is none) or array with mean values along specified axis. Code #1: # Python Program illustrating # numpy.mean() method import numpy as np # 1D array arr = [20, 2, 7, 1, 34] print("arr : ", arr) print("mean of arr : ", np.mean(arr)) Output : arr : [20, 2, 7, 1, 34] mean of arr : 12.8 Code #2: # Python Program illustrating # numpy.mean() method import numpy as np # 2D array arr = [[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4, ]] # mean of the flattened array print("\nmean of arr, axis = None : ", np.mean(arr)) # mean along the axis = 0 print("\nmean of arr, axis = 0 : ", np.mean(arr, axis = 0)) # mean along the axis = 1 print("\nmean of arr, axis = 1 : ", np.mean(arr, axis = 1)) out_arr = np.arange(3)print("\nout_arr : ", out_arr) print("mean of arr, axis = 1 : ", np.mean(arr, axis = 1, out = out_arr)) Output : mean of arr, axis = None : 18.6 mean of arr, axis = 0 : [17.33333333 8.33333333 31. 14. 22.33333333] mean of arr, axis = 1 : [24. 15. 16.8] out_arr : [0 1 2] mean of arr, axis = 1 : [24 15 16] Python numpy-Statistics Functions Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n28 Nov, 2018" }, { "code": null, "e": 183, "s": 53, "text": "numpy.mean(arr, axis = None) : Compute the arithmetic mean (average) of the given data (array elements) along the specified axis." }, { "code": null, "e": 661, "s": 183, "text": "Parameters :arr : [array_like]input array.axis : [int or tuples of int]axis along which we want to calculate the arithmetic mean. Otherwise, it will consider arr to be flattened(works on allthe axis). axis = 0 means along the column and axis = 1 means working along the row.out : [ndarray, optional]Different array in which we want to place the result. The array must have the same dimensions as expected output.dtype : [data-type, optional]Type we desire while computing mean." }, { "code": null, "e": 781, "s": 661, "text": "Results : Arithmetic mean of the array (a scalar value if axis is none) or array with mean values along specified axis." }, { "code": null, "e": 790, "s": 781, "text": "Code #1:" }, { "code": "# Python Program illustrating # numpy.mean() method import numpy as np # 1D array arr = [20, 2, 7, 1, 34] print(\"arr : \", arr) print(\"mean of arr : \", np.mean(arr)) ", "e": 962, "s": 790, "text": null }, { "code": null, "e": 971, "s": 962, "text": "Output :" }, { "code": null, "e": 1017, "s": 971, "text": "arr : [20, 2, 7, 1, 34]\nmean of arr : 12.8\n" }, { "code": null, "e": 1027, "s": 1017, "text": " Code #2:" }, { "code": "# Python Program illustrating # numpy.mean() method import numpy as np # 2D array arr = [[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4, ]] # mean of the flattened array print(\"\\nmean of arr, axis = None : \", np.mean(arr)) # mean along the axis = 0 print(\"\\nmean of arr, axis = 0 : \", np.mean(arr, axis = 0)) # mean along the axis = 1 print(\"\\nmean of arr, axis = 1 : \", np.mean(arr, axis = 1)) out_arr = np.arange(3)print(\"\\nout_arr : \", out_arr) print(\"mean of arr, axis = 1 : \", np.mean(arr, axis = 1, out = out_arr))", "e": 1600, "s": 1027, "text": null }, { "code": null, "e": 1609, "s": 1600, "text": "Output :" }, { "code": null, "e": 1830, "s": 1609, "text": "mean of arr, axis = None : 18.6\n\nmean of arr, axis = 0 : [17.33333333 8.33333333 31. 14. 22.33333333]\n\nmean of arr, axis = 1 : [24. 15. 16.8]\n\nout_arr : [0 1 2]\nmean of arr, axis = 1 : [24 15 16]\n" }, { "code": null, "e": 1864, "s": 1830, "text": "Python numpy-Statistics Functions" }, { "code": null, "e": 1877, "s": 1864, "text": "Python-numpy" }, { "code": null, "e": 1884, "s": 1877, "text": "Python" } ]
IntStream range() in Java
06 Dec, 2018 IntStream range(int startInclusive, int endExclusive) returns a sequential ordered IntStream from startInclusive (inclusive) to endExclusive (exclusive) by an incremental step of 1. Syntax : static IntStream range(int startInclusive, int endExclusive) Parameters : IntStream : A sequence of primitive int-valued elements. startInclusive : The inclusive initial value. endExclusive : The exclusive upper bound. Return Value : A sequential IntStream for the range of int elements. Example : // Implementation of IntStream range// (int startInclusive, int endExclusive)import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.range(6, 10); // Displaying the elements in range // including the lower bound but // excluding the upper bound stream.forEach(System.out::println); }} 6 7 8 9 Note : IntStream range(int startInclusive, int endExclusive) basically works like a for loop. An equivalent sequence of increasing values can be produced sequentially as : for (int i = startInclusive; i < endExclusive ; i++) { ... ... ... } Java - util package Java-Functions java-intstream java-stream Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Dec, 2018" }, { "code": null, "e": 236, "s": 54, "text": "IntStream range(int startInclusive, int endExclusive) returns a sequential ordered IntStream from startInclusive (inclusive) to endExclusive (exclusive) by an incremental step of 1." }, { "code": null, "e": 245, "s": 236, "text": "Syntax :" }, { "code": null, "e": 309, "s": 245, "text": "static IntStream range(int startInclusive, int endExclusive)\n" }, { "code": null, "e": 322, "s": 309, "text": "Parameters :" }, { "code": null, "e": 379, "s": 322, "text": "IntStream : A sequence of primitive int-valued elements." }, { "code": null, "e": 425, "s": 379, "text": "startInclusive : The inclusive initial value." }, { "code": null, "e": 467, "s": 425, "text": "endExclusive : The exclusive upper bound." }, { "code": null, "e": 536, "s": 467, "text": "Return Value : A sequential IntStream for the range of int elements." }, { "code": null, "e": 546, "s": 536, "text": "Example :" }, { "code": "// Implementation of IntStream range// (int startInclusive, int endExclusive)import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.range(6, 10); // Displaying the elements in range // including the lower bound but // excluding the upper bound stream.forEach(System.out::println); }}", "e": 1010, "s": 546, "text": null }, { "code": null, "e": 1019, "s": 1010, "text": "6\n7\n8\n9\n" }, { "code": null, "e": 1191, "s": 1019, "text": "Note : IntStream range(int startInclusive, int endExclusive) basically works like a for loop. An equivalent sequence of increasing values can be produced sequentially as :" }, { "code": null, "e": 1265, "s": 1191, "text": "for (int i = startInclusive; i < endExclusive ; i++) \n{\n ...\n ...\n ...\n}\n" }, { "code": null, "e": 1285, "s": 1265, "text": "Java - util package" }, { "code": null, "e": 1300, "s": 1285, "text": "Java-Functions" }, { "code": null, "e": 1315, "s": 1300, "text": "java-intstream" }, { "code": null, "e": 1327, "s": 1315, "text": "java-stream" }, { "code": null, "e": 1332, "s": 1327, "text": "Java" }, { "code": null, "e": 1337, "s": 1332, "text": "Java" } ]
Remove all characters other than alphabets from string
04 May, 2022 Given a string consisting of alphabets and others characters, remove all the characters other then alphabets and print the string so formed. Examples: Input : $Gee*k;s..fo, r'Ge^eks? Output : GeeksforGeeks Input : P&ra+$BHa;;t*ku, ma$r@@s#in}gh Output : PraBHatkumarsingh To remove all the characters other than alphabets(a-z) && (A-Z), we just compare the character with the ASCII value and the character whose value does not lie in the range of alphabets, we remove those character using string erase function. C++ Java Python3 C# Javascript // CPP program to remove all the// characters other then alphabets#include <bits/stdc++.h>using namespace std; // function to remove characters and// print new stringvoid removeSpecialCharacter(string s){ for (int i = 0; i < s.size(); i++) { // Finding the character whose // ASCII value fall under this // range if (s[i] < 'A' || s[i] > 'Z' && s[i] < 'a' || s[i] > 'z') { // erase function to erase // the character s.erase(i, 1); i--; } } cout << s;} // driver codeint main(){ string s = "$Gee*k;s..fo, r'Ge^eks?"; removeSpecialCharacter(s); return 0;} // Java program to remove all the characters// other then alphabets class GFG{ // function to remove characters and // print new string static void removeSpecialCharacter(String s) { for (int i = 0; i < s.length(); i++) { // Finding the character whose // ASCII value fall under this // range if (s.charAt(i) < 'A' || s.charAt(i) > 'Z' && s.charAt(i) < 'a' || s.charAt(i) > 'z') { // erase function to erase // the character s = s.substring(0, i) + s.substring(i + 1); i--; } } System.out.print(s); } // Driver code public static void main(String[] args) { String s = "$Gee*k;s..fo, r'Ge^eks?"; removeSpecialCharacter(s); }} // This code is contributed by Rajput-Ji # Python3 program to remove all the# characters other then alphabets # function to remove characters and# print new stringdef removeSpecialCharacter(s): i = 0 while i < len(s): # Finding the character whose # ASCII value fall under this # range if (ord(s[i]) < ord('A') or ord(s[i]) > ord('Z') and ord(s[i]) < ord('a') or ord(s[i]) > ord('z')): # erase function to erase # the character del s[i] i -= 1 i += 1 print("".join(s)) # Driver Codeif __name__ == '__main__': s = "$Gee*k;s..fo, r'Ge^eks?" s = [i for i in s] removeSpecialCharacter(s) # This code is contributed by Mohit Kumar // C# program to remove all the characters// other then alphabetsusing System; class GFG { // function to remove characters and // print new string static void removeSpecialCharacter(string s) { for (int i = 0; i < s.Length; i++) { // Finding the character whose // ASCII value fall under this // range if (s[i] < 'A' || s[i] > 'Z' && s[i] < 'a' || s[i] > 'z') { // erase function to erase // the character s = s.Remove(i,1); i--; } } Console.Write(s); } // Driver code public static void Main() { string s = "$Gee*k;s..fo, r'Ge^eks?"; removeSpecialCharacter(s); }} // This code is contributed by Sam007. <script>// Javascript program to remove all the characters// other then alphabets // function to remove characters and // print new string function removeSpecialCharacter(s) { for (let i = 0; i < s.length; i++) { // Finding the character whose // ASCII value fall under this // range if (s[i] < 'A' || s[i] > 'Z' && s[i] < 'a' || s[i] > 'z') { // erase function to erase // the character s = s.substring(0, i) + s.substring(i + 1); i--; } } document.write(s); } // Driver code let s = "$Gee*k;s..fo, r'Ge^eks?"; removeSpecialCharacter(s); // This code is contributed by unknown2108</script> Output: GeeksforGeeks Time complexity of above code is O(n*n) as erase() may take O(n) in worst case. We can optimize the solution by keeping track of two indexes. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English default, selected This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. C++ Java Python3 C# Javascript // CPP program to remove all the// characters other then alphabets#include <bits/stdc++.h>using namespace std; // function to remove characters and// print new stringvoid removeSpecialCharacter(string s){ int j = 0; for (int i = 0; i < s.size(); i++) { // Store only valid characters if ((s[i] >= 'A' && s[i] <= 'Z') || (s[i] >='a' && s[i] <= 'z')) { s[j] = s[i]; j++; } } cout << s.substr(0, j);} // driver codeint main(){ string s = "$Gee*k;s..fo, r'Ge^eks?"; removeSpecialCharacter(s); return 0;} // Java program to remove all the// characters other then alphabets class GFG { // function to remove characters and// print new string static void removeSpecialCharacter(String str) { char[] s = str.toCharArray(); int j = 0; for (int i = 0; i < s.length; i++) { // Store only valid characters if ((s[i] >= 'A' && s[i] <= 'Z') || (s[i] >= 'a' && s[i] <= 'z')) { s[j] = s[i]; j++; } } System.out.println(String.valueOf(s).substring(0, j)); } // driver code public static void main(String[] args) { String s = "$Gee*k;s..fo, r'Ge^eks?"; removeSpecialCharacter(s); }} // This code is contributed by 29AjayKumar # Python program to remove all the# characters other then alphabets # Function to remove special characters# and store it in another variabledef removeSpecialCharacter(s): t = "" for i in s: # Store only valid characters if (i >= 'A' and i <= 'Z') or (i >= 'a' and i <= 'z'): t += i print(t) # Driver codes = "$Gee*k;s..fo, r'Ge^eks?"removeSpecialCharacter(s) # This code is contributed by code_freak // C# program to remove all the// characters other then alphabetsusing System;public class GFG { // function to remove characters and// print new string static void removeSpecialCharacter(String str) { char[] s = str.ToCharArray(); int j = 0; for (int i = 0; i < s.Length; i++) { // Store only valid characters if ((s[i] >= 'A' && s[i] <= 'Z') || (s[i] >= 'a' && s[i] <= 'z')) { s[j] = s[i]; j++; } } Console.WriteLine(String.Join("",s).Substring(0, j)); } // driver code public static void Main() { String s = "$Gee*k;s..fo, r'Ge^eks?"; removeSpecialCharacter(s); }} //This code is contributed by PrinciRaj1992 <script> // JavaScript program to remove all the// characters other then alphabets // function to remove characters and// print new stringfunction removeSpecialCharacter(str){ let s = str.split(""); let j = 0; for (let i = 0; i < s.length; i++) { // Store only valid characters if ((s[i] >= 'A' && s[i] <= 'Z') || (s[i] >= 'a' && s[i] <= 'z')) { s[j] = s[i]; j++; } } document.write((s).join("").substring(0, j));} // driver codelet s = "$Gee*k;s..fo, r'Ge^eks?";removeSpecialCharacter(s); // This code is contributed by rag2127 </script> Output: GeeksforGeeks Time Complexity : O(n) Remove all characters other than alphabets in a string. | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersRemove all characters other than alphabets in a string. | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:32•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=xVe9qqjbSL4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Prabhat kumar singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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. Sam007 PraveenSharma4 29AjayKumar princiraj1992 Rajput-Ji code_freak mohit kumar 29 unknown2108 rag2127 surinderdawra388 Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Longest Palindromic Substring | Set 1 Length of the longest substring without repeating characters Check whether two strings are anagram of each other Top 50 String Coding Problems for Interviews Convert string to char array in C++ Reverse words in a given string What is Data Structure: Types, Classifications and Applications Print all the duplicates in the input string Reverse string in Python (6 different ways) Remove duplicates from a given string
[ { "code": null, "e": 52, "s": 24, "text": "\n04 May, 2022" }, { "code": null, "e": 205, "s": 52, "text": "Given a string consisting of alphabets and others characters, remove all the characters other then alphabets and print the string so formed. Examples: " }, { "code": null, "e": 327, "s": 205, "text": "Input : $Gee*k;s..fo, r'Ge^eks?\nOutput : GeeksforGeeks\n\nInput : P&ra+$BHa;;t*ku, ma$r@@s#in}gh\nOutput : PraBHatkumarsingh" }, { "code": null, "e": 572, "s": 329, "text": "To remove all the characters other than alphabets(a-z) && (A-Z), we just compare the character with the ASCII value and the character whose value does not lie in the range of alphabets, we remove those character using string erase function. " }, { "code": null, "e": 576, "s": 572, "text": "C++" }, { "code": null, "e": 581, "s": 576, "text": "Java" }, { "code": null, "e": 589, "s": 581, "text": "Python3" }, { "code": null, "e": 592, "s": 589, "text": "C#" }, { "code": null, "e": 603, "s": 592, "text": "Javascript" }, { "code": "// CPP program to remove all the// characters other then alphabets#include <bits/stdc++.h>using namespace std; // function to remove characters and// print new stringvoid removeSpecialCharacter(string s){ for (int i = 0; i < s.size(); i++) { // Finding the character whose // ASCII value fall under this // range if (s[i] < 'A' || s[i] > 'Z' && s[i] < 'a' || s[i] > 'z') { // erase function to erase // the character s.erase(i, 1); i--; } } cout << s;} // driver codeint main(){ string s = \"$Gee*k;s..fo, r'Ge^eks?\"; removeSpecialCharacter(s); return 0;}", "e": 1284, "s": 603, "text": null }, { "code": "// Java program to remove all the characters// other then alphabets class GFG{ // function to remove characters and // print new string static void removeSpecialCharacter(String s) { for (int i = 0; i < s.length(); i++) { // Finding the character whose // ASCII value fall under this // range if (s.charAt(i) < 'A' || s.charAt(i) > 'Z' && s.charAt(i) < 'a' || s.charAt(i) > 'z') { // erase function to erase // the character s = s.substring(0, i) + s.substring(i + 1); i--; } } System.out.print(s); } // Driver code public static void main(String[] args) { String s = \"$Gee*k;s..fo, r'Ge^eks?\"; removeSpecialCharacter(s); }} // This code is contributed by Rajput-Ji", "e": 2192, "s": 1284, "text": null }, { "code": "# Python3 program to remove all the# characters other then alphabets # function to remove characters and# print new stringdef removeSpecialCharacter(s): i = 0 while i < len(s): # Finding the character whose # ASCII value fall under this # range if (ord(s[i]) < ord('A') or ord(s[i]) > ord('Z') and ord(s[i]) < ord('a') or ord(s[i]) > ord('z')): # erase function to erase # the character del s[i] i -= 1 i += 1 print(\"\".join(s)) # Driver Codeif __name__ == '__main__': s = \"$Gee*k;s..fo, r'Ge^eks?\" s = [i for i in s] removeSpecialCharacter(s) # This code is contributed by Mohit Kumar", "e": 2928, "s": 2192, "text": null }, { "code": "// C# program to remove all the characters// other then alphabetsusing System; class GFG { // function to remove characters and // print new string static void removeSpecialCharacter(string s) { for (int i = 0; i < s.Length; i++) { // Finding the character whose // ASCII value fall under this // range if (s[i] < 'A' || s[i] > 'Z' && s[i] < 'a' || s[i] > 'z') { // erase function to erase // the character s = s.Remove(i,1); i--; } } Console.Write(s); } // Driver code public static void Main() { string s = \"$Gee*k;s..fo, r'Ge^eks?\"; removeSpecialCharacter(s); }} // This code is contributed by Sam007.", "e": 3784, "s": 2928, "text": null }, { "code": "<script>// Javascript program to remove all the characters// other then alphabets // function to remove characters and // print new string function removeSpecialCharacter(s) { for (let i = 0; i < s.length; i++) { // Finding the character whose // ASCII value fall under this // range if (s[i] < 'A' || s[i] > 'Z' && s[i] < 'a' || s[i] > 'z') { // erase function to erase // the character s = s.substring(0, i) + s.substring(i + 1); i--; } } document.write(s); } // Driver code let s = \"$Gee*k;s..fo, r'Ge^eks?\"; removeSpecialCharacter(s); // This code is contributed by unknown2108</script>", "e": 4606, "s": 3784, "text": null }, { "code": null, "e": 4616, "s": 4606, "text": "Output: " }, { "code": null, "e": 4630, "s": 4616, "text": "GeeksforGeeks" }, { "code": null, "e": 4774, "s": 4630, "text": "Time complexity of above code is O(n*n) as erase() may take O(n) in worst case. We can optimize the solution by keeping track of two indexes. " }, { "code": null, "e": 4783, "s": 4774, "text": "Chapters" }, { "code": null, "e": 4810, "s": 4783, "text": "descriptions off, selected" }, { "code": null, "e": 4860, "s": 4810, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 4883, "s": 4860, "text": "captions off, selected" }, { "code": null, "e": 4891, "s": 4883, "text": "English" }, { "code": null, "e": 4909, "s": 4891, "text": "default, selected" }, { "code": null, "e": 4933, "s": 4909, "text": "This is a modal window." }, { "code": null, "e": 5002, "s": 4933, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 5024, "s": 5002, "text": "End of dialog window." }, { "code": null, "e": 5028, "s": 5024, "text": "C++" }, { "code": null, "e": 5033, "s": 5028, "text": "Java" }, { "code": null, "e": 5041, "s": 5033, "text": "Python3" }, { "code": null, "e": 5044, "s": 5041, "text": "C#" }, { "code": null, "e": 5055, "s": 5044, "text": "Javascript" }, { "code": "// CPP program to remove all the// characters other then alphabets#include <bits/stdc++.h>using namespace std; // function to remove characters and// print new stringvoid removeSpecialCharacter(string s){ int j = 0; for (int i = 0; i < s.size(); i++) { // Store only valid characters if ((s[i] >= 'A' && s[i] <= 'Z') || (s[i] >='a' && s[i] <= 'z')) { s[j] = s[i]; j++; } } cout << s.substr(0, j);} // driver codeint main(){ string s = \"$Gee*k;s..fo, r'Ge^eks?\"; removeSpecialCharacter(s); return 0;}", "e": 5646, "s": 5055, "text": null }, { "code": "// Java program to remove all the// characters other then alphabets class GFG { // function to remove characters and// print new string static void removeSpecialCharacter(String str) { char[] s = str.toCharArray(); int j = 0; for (int i = 0; i < s.length; i++) { // Store only valid characters if ((s[i] >= 'A' && s[i] <= 'Z') || (s[i] >= 'a' && s[i] <= 'z')) { s[j] = s[i]; j++; } } System.out.println(String.valueOf(s).substring(0, j)); } // driver code public static void main(String[] args) { String s = \"$Gee*k;s..fo, r'Ge^eks?\"; removeSpecialCharacter(s); }} // This code is contributed by 29AjayKumar", "e": 6398, "s": 5646, "text": null }, { "code": "# Python program to remove all the# characters other then alphabets # Function to remove special characters# and store it in another variabledef removeSpecialCharacter(s): t = \"\" for i in s: # Store only valid characters if (i >= 'A' and i <= 'Z') or (i >= 'a' and i <= 'z'): t += i print(t) # Driver codes = \"$Gee*k;s..fo, r'Ge^eks?\"removeSpecialCharacter(s) # This code is contributed by code_freak", "e": 6842, "s": 6398, "text": null }, { "code": " // C# program to remove all the// characters other then alphabetsusing System;public class GFG { // function to remove characters and// print new string static void removeSpecialCharacter(String str) { char[] s = str.ToCharArray(); int j = 0; for (int i = 0; i < s.Length; i++) { // Store only valid characters if ((s[i] >= 'A' && s[i] <= 'Z') || (s[i] >= 'a' && s[i] <= 'z')) { s[j] = s[i]; j++; } } Console.WriteLine(String.Join(\"\",s).Substring(0, j)); } // driver code public static void Main() { String s = \"$Gee*k;s..fo, r'Ge^eks?\"; removeSpecialCharacter(s); }} //This code is contributed by PrinciRaj1992", "e": 7606, "s": 6842, "text": null }, { "code": "<script> // JavaScript program to remove all the// characters other then alphabets // function to remove characters and// print new stringfunction removeSpecialCharacter(str){ let s = str.split(\"\"); let j = 0; for (let i = 0; i < s.length; i++) { // Store only valid characters if ((s[i] >= 'A' && s[i] <= 'Z') || (s[i] >= 'a' && s[i] <= 'z')) { s[j] = s[i]; j++; } } document.write((s).join(\"\").substring(0, j));} // driver codelet s = \"$Gee*k;s..fo, r'Ge^eks?\";removeSpecialCharacter(s); // This code is contributed by rag2127 </script>", "e": 8261, "s": 7606, "text": null }, { "code": null, "e": 8271, "s": 8261, "text": "Output: " }, { "code": null, "e": 8285, "s": 8271, "text": "GeeksforGeeks" }, { "code": null, "e": 8310, "s": 8285, "text": "Time Complexity : O(n) " }, { "code": null, "e": 9240, "s": 8310, "text": "Remove all characters other than alphabets in a string. | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersRemove all characters other than alphabets in a string. | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:32•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=xVe9qqjbSL4\" 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": 9668, "s": 9240, "text": "This article is contributed by Prabhat kumar singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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": 9675, "s": 9668, "text": "Sam007" }, { "code": null, "e": 9690, "s": 9675, "text": "PraveenSharma4" }, { "code": null, "e": 9702, "s": 9690, "text": "29AjayKumar" }, { "code": null, "e": 9716, "s": 9702, "text": "princiraj1992" }, { "code": null, "e": 9726, "s": 9716, "text": "Rajput-Ji" }, { "code": null, "e": 9737, "s": 9726, "text": "code_freak" }, { "code": null, "e": 9752, "s": 9737, "text": "mohit kumar 29" }, { "code": null, "e": 9764, "s": 9752, "text": "unknown2108" }, { "code": null, "e": 9772, "s": 9764, "text": "rag2127" }, { "code": null, "e": 9789, "s": 9772, "text": "surinderdawra388" }, { "code": null, "e": 9797, "s": 9789, "text": "Strings" }, { "code": null, "e": 9805, "s": 9797, "text": "Strings" }, { "code": null, "e": 9903, "s": 9805, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9941, "s": 9903, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 10002, "s": 9941, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 10054, "s": 10002, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 10099, "s": 10054, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 10135, "s": 10099, "text": "Convert string to char array in C++" }, { "code": null, "e": 10167, "s": 10135, "text": "Reverse words in a given string" }, { "code": null, "e": 10231, "s": 10167, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 10276, "s": 10231, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 10320, "s": 10276, "text": "Reverse string in Python (6 different ways)" } ]
Insertion and Deletion in Heaps in Data Sturcture
Here we will see how to insert and delete elements from binary heap data structures. Suppose the initial tree is like below − insert(heap, n, item): Begin if heap is full, then exit else n := n + 1 for i := n, i > 1, set i := i / 2 in each iteration, do if item <= heap[i/2], then break heap[i] = heap[i/2] done end if heap[i] := item End Suppose we want to insert 30 into the heap − delete(heap, n): Begin if heap is empty, then exit else item := heap[1] last := heap[n] n := n – 1 for i := 1, j := 2, j <= n, set i := j and j := j * 2, do if j < n, then if heap[j] < heap[j + 1], then j := j + 1 end if if last >= heap[j], then break heap[i] := heap[j] done end if heap[i] := last End Suppose we want to delete 30 from the final heap −
[ { "code": null, "e": 1188, "s": 1062, "text": "Here we will see how to insert and delete elements from binary heap data structures. Suppose the initial tree is like below −" }, { "code": null, "e": 1449, "s": 1188, "text": "insert(heap, n, item):\nBegin\n if heap is full, then exit\n else\n n := n + 1\n for i := n, i > 1, set i := i / 2 in each iteration, do\n if item <= heap[i/2], then break\n heap[i] = heap[i/2]\n done\n end if\n heap[i] := item\nEnd" }, { "code": null, "e": 1494, "s": 1449, "text": "Suppose we want to insert 30 into the heap −" }, { "code": null, "e": 1887, "s": 1494, "text": "delete(heap, n):\nBegin\n if heap is empty, then exit\n else\n item := heap[1]\n last := heap[n]\n n := n – 1\n for i := 1, j := 2, j <= n, set i := j and j := j * 2, do\n if j < n, then\n if heap[j] < heap[j + 1], then j := j + 1\n end if\n if last >= heap[j], then break\n heap[i] := heap[j]\n done\n end if\n heap[i] := last\nEnd" }, { "code": null, "e": 1938, "s": 1887, "text": "Suppose we want to delete 30 from the final heap −" } ]
How to add JTable to Panel in Java Swing?
To add JTabel to Panel, let us first crerate a panel − JPanel panel = new JPanel(); Now, create JTable and add rows and columns with the records − String[][] rec = { { "1", "Steve", "AUS" }, { "2", "Virat", "IND" }, { "3", "Kane", "NZ" }, { "4", "David", "AUS" }, { "5", "Ben", "ENG" }, { "6", "Eion", "ENG" }, }; String[] header = { "Rank", "Player", "Country" }; JTable table = new JTable(rec, header); Add the above created table to panel − panel.add(new JScrollPane(table)); The following is an example to add JTabel to Panel in Java Swing − package my; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.border.TitledBorder; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame(); JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "ODI Rankings", TitledBorder.CENTER, TitledBorder.TOP)); String[][] rec = { { "1", "Steve", "AUS" }, { "2", "Virat", "IND" }, { "3", "Kane", "NZ" }, { "4", "David", "AUS" }, { "5", "Ben", "ENG" }, { "6", "Eion", "ENG" }, }; String[] header = { "Rank", "Player", "Country" }; JTable table = new JTable(rec, header); panel.add(new JScrollPane(table)); frame.add(panel); frame.setSize(550, 400); frame.setVisible(true); } } This will produce the following output −
[ { "code": null, "e": 1117, "s": 1062, "text": "To add JTabel to Panel, let us first crerate a panel −" }, { "code": null, "e": 1146, "s": 1117, "text": "JPanel panel = new JPanel();" }, { "code": null, "e": 1209, "s": 1146, "text": "Now, create JTable and add rows and columns with the records −" }, { "code": null, "e": 1485, "s": 1209, "text": "String[][] rec = {\n { \"1\", \"Steve\", \"AUS\" },\n { \"2\", \"Virat\", \"IND\" },\n { \"3\", \"Kane\", \"NZ\" },\n { \"4\", \"David\", \"AUS\" },\n { \"5\", \"Ben\", \"ENG\" },\n { \"6\", \"Eion\", \"ENG\" },\n};\nString[] header = { \"Rank\", \"Player\", \"Country\" };\nJTable table = new JTable(rec, header);" }, { "code": null, "e": 1524, "s": 1485, "text": "Add the above created table to panel −" }, { "code": null, "e": 1559, "s": 1524, "text": "panel.add(new JScrollPane(table));" }, { "code": null, "e": 1626, "s": 1559, "text": "The following is an example to add JTabel to Panel in Java Swing −" }, { "code": null, "e": 2585, "s": 1626, "text": "package my;\nimport javax.swing.BorderFactory;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.border.TitledBorder;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame();\n JPanel panel = new JPanel();\n panel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), \"ODI Rankings\", TitledBorder.CENTER, TitledBorder.TOP));\n String[][] rec = {\n { \"1\", \"Steve\", \"AUS\" },\n { \"2\", \"Virat\", \"IND\" },\n { \"3\", \"Kane\", \"NZ\" },\n { \"4\", \"David\", \"AUS\" },\n { \"5\", \"Ben\", \"ENG\" },\n { \"6\", \"Eion\", \"ENG\" },\n };\n String[] header = { \"Rank\", \"Player\", \"Country\" };\n JTable table = new JTable(rec, header);\n panel.add(new JScrollPane(table));\n frame.add(panel);\n frame.setSize(550, 400);\n frame.setVisible(true);\n }\n}" }, { "code": null, "e": 2626, "s": 2585, "text": "This will produce the following output −" } ]
Finding correlations in time series data | by Kemal Erdem (burnpiro) | Towards Data Science
If you’ve ever worked with data analysis it’s highly likely that you know about the idea of data correlation. There are many ways of calculating correlation within your data, and most of them are already implemented in popular data science toolkits. What I want to show you today is how to figure out a correlation between different length of time series vectors and target result (or any other value). This might come handy when trying to design models that rely on time series data. Let me give you an example. Imagine you’re dealing with weather data. Your goal is to predict the population at some point in the future. That population is not dependent on current weather conditions but rather on the past. Here we have a few samples from our dataset. It shows five consecutive time periods with some population numbers and the end of each period. Our goal is to predict a population in each time period. Usually to solve that problem we need to design some kind of model. The model itself doesn’t matter that much, important thing is to find what kind of features we should feed into it. We know that the current population doesn’t depend on current conditions but rather on the condition through its life cycle. We can search for publication on that subject and try to figure out the right amount of data. After a while, we decided that our population probably depends on temperature from the last 4 weeks, precipitation from 6 weeks, and humidity in the last 2 weeks. That’s ok but is there a better way to find that correlation in the data? Can we even check if our periods are correct? When thinking about data correlation we usually think about a correlation between a number, and the other number. Occasionally we might calculate correlations between categorical variables. This case is different. If we take under consideration a series of temperatures like that: [21,22,21,25,19] Order in which each number comes in is important. If we want to replace the whole series with some cumulative value (like an average or moving average) it’s not going to work. [21, 25, 19, 22, 21] This gives us the same average value but clearly shows a different situation. Another problem is to choose the right length of the vector. It’s not so easy to compare information gain when providing a longer vector. [16, 18, 22, 15, 17, 21, 22, 21, 25, 19] A common thing to do would be to provide a very long vector to the model and let it figure out a correlation by itself. That would work but in case of time series that usually we don’t have that much training data (and we cannot just create more). Even if we gather data from each day over the last 5 years, we have (on average) 1826 records. That’s way too low if you want to create a deep model with a very long input vector. Recently, a different idea is gaining popularity. It’s called Predictive Power Score (PPS) and is based on calculating predicting power for every property in the dataset. Predictive power is a measurement of the success of a Decision Tree model predicting a target variable with the help of a predictor variable. When you’re calculating PP for one variable (A) predicting another variable (B), we have to treat our variable B as the target, and A as the only feature. After that, we’re creating a Decision Tree (either Regressor or Classifier) and calculate meaningful metrics (e.g. MAE for regression problem or F1 for classification). Basically, you have to repeat that process for every pair of variables. Normalization of the score is optional because usually the raw score already has a meaning. In most cases, you don’t have to calculate PPS for all possible combinations of features. It’s enough to calculate only PPS between each feature and target. In our example, we would calculate PPS for pairs: (Temp, Population), (Perc, Population), (Humidity, Population). The only problem with this method is that it’s not solving our problem :) If we look at the standard PPS we’re able to check the predictive power of one variable. Our problem is a little different and let me show you how that looks like. Our target is Population and the standard PPS approach would show us scores for only one item from each feature. That’s ok, but we can do way better than this. Just try to find a correlation between the last x values of that vector and the target. Let’s start from the last row because for that one we have previous data. We still have a problem with the first 4 rows because we don’t have the previous 5 rows to get the data from. There are two solutions: Drop those rows Create data The first option is easy and usually, when you have >100 rows it shouldn’t affect the precision of the prediction. If you want to go with the second option you can use a moving average or other methods to populate that data. For now, we’re just going to go with the first option. To create DT we can use sklearn library and execute code like: from sklearn.tree import DecisionTreeRegressorfrom sklearn.model_selection import cross_val_scoreX = [ [22, 26, 29, 27, 22], [15, 22, 26, 29, 27], [19, 15, 22, 26, 29], [25, 19, 15, 22, 26]]Y = [76, 12, 53, 352]regressor = DecisionTreeRegressor(random_state=0)score = cross_val_score( regressor, X, Y, cv=2, #change that base on the data size scoring='neg_mean_absolute_error') As a result, we should get some value of negative MAE. Right now the question is “How many previous data points we should use to achieve the best score?”. We could create vectors with different lengths and compare scores for each of them. If we look on Temp feature only we should get datasets like Temp_five = [ [22, 26, 29, 27, 22], [15, 22, 26, 29, 27], [19, 15, 22, 26, 29], [25, 19, 15, 22, 26]]Temp_four = [ [26, 29, 27, 22], [22, 26, 29, 27], [15, 22, 26, 29], [19, 15, 22, 26]]Temp_three = [ [29, 27, 22], [26, 29, 27], [22, 26, 29], [15, 22, 26]]Temp_two = [ [27, 22], [29, 27], [26, 29], [22, 26]] Target always remains the same, the only thing that changes is a set of features. At this point, we’re calculating a score for each length and comparing the result to get the right length of the Temp vector. Let’s assume that the result looks like that: Base on this we can decide that the right length of the Temp vector is 4 (the lowest error). Now we perform a similar process for every single feature there is and come up with a final set of features. Bold selection shows a set of features for one training sample with a target of 76. When designing NN we can then assume 14 (4 x Temp + 2 x Perc + 8 x Humidity) input features. So our training set for bottom 3 samples will look like: X = [ [26, 29, 27, 22, 0, 0, 55, 88, 97, 75, 53, 40, 38, 36], [22, 26, 29, 27, 0, 0, 100, 55, 88, 97, 75, 53, 40, 38], [15, 22, 26, 29, 0, 0, 95, 100, 55, 88, 97, 75, 53, 40]]Y = [ 76, 12, 53] If you wonder how this method behaves on real-life data here is an example: Each column represents one feature and each row represents a different length of the vector constructed from this feature. In this example, I’ve calculated MAE for vectors between 3 and 51 elements for each feature. There are a couple of rules to select the right features. The first one (and the most obvious one) is to select features with the lowest MAE score. We can sort those columns and start selecting ones with the lowest values. The question is “How many columns?”. The answer might not surprise you, it depends :). When you have more training data you can allow your model to be larger and so, select more features. If you have only a handful of training data you cannot design a model with >200 features because you’re getting into the curse of dimensionality territory. Another thing if the length of each column. As you can see on this example reanalysis_specific_humidity_g_per_kg is a useful feature (one of the best we have) with 2 minimum values of MAE. When we have a case like this we usually selecting a shorter vector. So the decision is to select a vector length of 14 instead of 27, even if both have the same value of MAE (30). Another thing to discuss is the last column. Some of the columns shouldn’t be treated as a vector, instead they should be used as a single feature. weekofyear column contains a week number for a given training example. There is no point in sending a vector of week numbers to the model because it always increases by 1 for every week. But it's still important to look at this column because it clearly shows how length affects accuracy. Sometimes you might want to make some tradeoffs when selecting vector length. Look on feature 15 ( station_min_temp_c). It scores 35 MAE with a length of 3 and then beats that score with a length of 26. The difference between two scores is only 1 and we're adding 23 extra features just to get that 1 MAE. You have to remember that when building a model with multiple features, at the end length of your input vector is a sum of all vectors you've selected. Increasing input length by 23 forces you to have more training data and a larger model. In this case, I would personally select a 3 item vector rather than 26, or just test two different models. If the result won't improve when changing from 3 to 26 items you should use 3 because it produces a simpler hypothesis (according to the Occam's razor rule). The last thing I want to show you is how easy is to make a mistake when selecting features without this method. Let’s look at columns 4 ( reanalysis_dew_point_temp_k) and 11 ( reanalysis_tdtr_k). You can tell just by looking at them that column 4 has a better predicting capability. But if you were selecting the length of those vectors by hand (or random) you can make reanalysis_dew_point_temp_k worse than reanalysis_tdtr_k. Without any prior knowledge about this feature, you can select its length to be 3 which gives us MAE of 38 which is worse than 37 scored by column 11 in row 21. That way you've just made one of the best features you have as useful as one of the worst features you have. The extended version of PPS is a powerful tool to select a set of features while building your model. Sometimes it might lead to a deeper understanding of the data event without expert knowledge on the subject. Even if it might take a while to calculate all PPS for different lengths of input vectors it is a time well spent. EDA ( Exploratory Data Analysis) is still one of the most important parts of every Data Science/Machine Learning project, and you shouldn’t skip it or just limit yourself to the default set of tools. Originally published at https://erdem.pl. Some rights reserved
[ { "code": null, "e": 575, "s": 172, "text": "If you’ve ever worked with data analysis it’s highly likely that you know about the idea of data correlation. There are many ways of calculating correlation within your data, and most of them are already implemented in popular data science toolkits. What I want to show you today is how to figure out a correlation between different length of time series vectors and target result (or any other value)." }, { "code": null, "e": 882, "s": 575, "text": "This might come handy when trying to design models that rely on time series data. Let me give you an example. Imagine you’re dealing with weather data. Your goal is to predict the population at some point in the future. That population is not dependent on current weather conditions but rather on the past." }, { "code": null, "e": 1264, "s": 882, "text": "Here we have a few samples from our dataset. It shows five consecutive time periods with some population numbers and the end of each period. Our goal is to predict a population in each time period. Usually to solve that problem we need to design some kind of model. The model itself doesn’t matter that much, important thing is to find what kind of features we should feed into it." }, { "code": null, "e": 1766, "s": 1264, "text": "We know that the current population doesn’t depend on current conditions but rather on the condition through its life cycle. We can search for publication on that subject and try to figure out the right amount of data. After a while, we decided that our population probably depends on temperature from the last 4 weeks, precipitation from 6 weeks, and humidity in the last 2 weeks. That’s ok but is there a better way to find that correlation in the data? Can we even check if our periods are correct?" }, { "code": null, "e": 2047, "s": 1766, "text": "When thinking about data correlation we usually think about a correlation between a number, and the other number. Occasionally we might calculate correlations between categorical variables. This case is different. If we take under consideration a series of temperatures like that:" }, { "code": null, "e": 2064, "s": 2047, "text": "[21,22,21,25,19]" }, { "code": null, "e": 2240, "s": 2064, "text": "Order in which each number comes in is important. If we want to replace the whole series with some cumulative value (like an average or moving average) it’s not going to work." }, { "code": null, "e": 2261, "s": 2240, "text": "[21, 25, 19, 22, 21]" }, { "code": null, "e": 2477, "s": 2261, "text": "This gives us the same average value but clearly shows a different situation. Another problem is to choose the right length of the vector. It’s not so easy to compare information gain when providing a longer vector." }, { "code": null, "e": 2518, "s": 2477, "text": "[16, 18, 22, 15, 17, 21, 22, 21, 25, 19]" }, { "code": null, "e": 2946, "s": 2518, "text": "A common thing to do would be to provide a very long vector to the model and let it figure out a correlation by itself. That would work but in case of time series that usually we don’t have that much training data (and we cannot just create more). Even if we gather data from each day over the last 5 years, we have (on average) 1826 records. That’s way too low if you want to create a deep model with a very long input vector." }, { "code": null, "e": 3259, "s": 2946, "text": "Recently, a different idea is gaining popularity. It’s called Predictive Power Score (PPS) and is based on calculating predicting power for every property in the dataset. Predictive power is a measurement of the success of a Decision Tree model predicting a target variable with the help of a predictor variable." }, { "code": null, "e": 3583, "s": 3259, "text": "When you’re calculating PP for one variable (A) predicting another variable (B), we have to treat our variable B as the target, and A as the only feature. After that, we’re creating a Decision Tree (either Regressor or Classifier) and calculate meaningful metrics (e.g. MAE for regression problem or F1 for classification)." }, { "code": null, "e": 4018, "s": 3583, "text": "Basically, you have to repeat that process for every pair of variables. Normalization of the score is optional because usually the raw score already has a meaning. In most cases, you don’t have to calculate PPS for all possible combinations of features. It’s enough to calculate only PPS between each feature and target. In our example, we would calculate PPS for pairs: (Temp, Population), (Perc, Population), (Humidity, Population)." }, { "code": null, "e": 4092, "s": 4018, "text": "The only problem with this method is that it’s not solving our problem :)" }, { "code": null, "e": 4256, "s": 4092, "text": "If we look at the standard PPS we’re able to check the predictive power of one variable. Our problem is a little different and let me show you how that looks like." }, { "code": null, "e": 4369, "s": 4256, "text": "Our target is Population and the standard PPS approach would show us scores for only one item from each feature." }, { "code": null, "e": 4578, "s": 4369, "text": "That’s ok, but we can do way better than this. Just try to find a correlation between the last x values of that vector and the target. Let’s start from the last row because for that one we have previous data." }, { "code": null, "e": 4713, "s": 4578, "text": "We still have a problem with the first 4 rows because we don’t have the previous 5 rows to get the data from. There are two solutions:" }, { "code": null, "e": 4729, "s": 4713, "text": "Drop those rows" }, { "code": null, "e": 4741, "s": 4729, "text": "Create data" }, { "code": null, "e": 5021, "s": 4741, "text": "The first option is easy and usually, when you have >100 rows it shouldn’t affect the precision of the prediction. If you want to go with the second option you can use a moving average or other methods to populate that data. For now, we’re just going to go with the first option." }, { "code": null, "e": 5084, "s": 5021, "text": "To create DT we can use sklearn library and execute code like:" }, { "code": null, "e": 5489, "s": 5084, "text": "from sklearn.tree import DecisionTreeRegressorfrom sklearn.model_selection import cross_val_scoreX = [ [22, 26, 29, 27, 22], [15, 22, 26, 29, 27], [19, 15, 22, 26, 29], [25, 19, 15, 22, 26]]Y = [76, 12, 53, 352]regressor = DecisionTreeRegressor(random_state=0)score = cross_val_score( regressor, X, Y, cv=2, #change that base on the data size scoring='neg_mean_absolute_error')" }, { "code": null, "e": 5544, "s": 5489, "text": "As a result, we should get some value of negative MAE." }, { "code": null, "e": 5728, "s": 5544, "text": "Right now the question is “How many previous data points we should use to achieve the best score?”. We could create vectors with different lengths and compare scores for each of them." }, { "code": null, "e": 5788, "s": 5728, "text": "If we look on Temp feature only we should get datasets like" }, { "code": null, "e": 6145, "s": 5788, "text": "Temp_five = [ [22, 26, 29, 27, 22], [15, 22, 26, 29, 27], [19, 15, 22, 26, 29], [25, 19, 15, 22, 26]]Temp_four = [ [26, 29, 27, 22], [22, 26, 29, 27], [15, 22, 26, 29], [19, 15, 22, 26]]Temp_three = [ [29, 27, 22], [26, 29, 27], [22, 26, 29], [15, 22, 26]]Temp_two = [ [27, 22], [29, 27], [26, 29], [22, 26]]" }, { "code": null, "e": 6353, "s": 6145, "text": "Target always remains the same, the only thing that changes is a set of features. At this point, we’re calculating a score for each length and comparing the result to get the right length of the Temp vector." }, { "code": null, "e": 6399, "s": 6353, "text": "Let’s assume that the result looks like that:" }, { "code": null, "e": 6601, "s": 6399, "text": "Base on this we can decide that the right length of the Temp vector is 4 (the lowest error). Now we perform a similar process for every single feature there is and come up with a final set of features." }, { "code": null, "e": 6835, "s": 6601, "text": "Bold selection shows a set of features for one training sample with a target of 76. When designing NN we can then assume 14 (4 x Temp + 2 x Perc + 8 x Humidity) input features. So our training set for bottom 3 samples will look like:" }, { "code": null, "e": 7059, "s": 6835, "text": "X = [ [26, 29, 27, 22, 0, 0, 55, 88, 97, 75, 53, 40, 38, 36], [22, 26, 29, 27, 0, 0, 100, 55, 88, 97, 75, 53, 40, 38], [15, 22, 26, 29, 0, 0, 95, 100, 55, 88, 97, 75, 53, 40]]Y = [ 76, 12, 53]" }, { "code": null, "e": 7135, "s": 7059, "text": "If you wonder how this method behaves on real-life data here is an example:" }, { "code": null, "e": 7351, "s": 7135, "text": "Each column represents one feature and each row represents a different length of the vector constructed from this feature. In this example, I’ve calculated MAE for vectors between 3 and 51 elements for each feature." }, { "code": null, "e": 7918, "s": 7351, "text": "There are a couple of rules to select the right features. The first one (and the most obvious one) is to select features with the lowest MAE score. We can sort those columns and start selecting ones with the lowest values. The question is “How many columns?”. The answer might not surprise you, it depends :). When you have more training data you can allow your model to be larger and so, select more features. If you have only a handful of training data you cannot design a model with >200 features because you’re getting into the curse of dimensionality territory." }, { "code": null, "e": 8288, "s": 7918, "text": "Another thing if the length of each column. As you can see on this example reanalysis_specific_humidity_g_per_kg is a useful feature (one of the best we have) with 2 minimum values of MAE. When we have a case like this we usually selecting a shorter vector. So the decision is to select a vector length of 14 instead of 27, even if both have the same value of MAE (30)." }, { "code": null, "e": 8725, "s": 8288, "text": "Another thing to discuss is the last column. Some of the columns shouldn’t be treated as a vector, instead they should be used as a single feature. weekofyear column contains a week number for a given training example. There is no point in sending a vector of week numbers to the model because it always increases by 1 for every week. But it's still important to look at this column because it clearly shows how length affects accuracy." }, { "code": null, "e": 9536, "s": 8725, "text": "Sometimes you might want to make some tradeoffs when selecting vector length. Look on feature 15 ( station_min_temp_c). It scores 35 MAE with a length of 3 and then beats that score with a length of 26. The difference between two scores is only 1 and we're adding 23 extra features just to get that 1 MAE. You have to remember that when building a model with multiple features, at the end length of your input vector is a sum of all vectors you've selected. Increasing input length by 23 forces you to have more training data and a larger model. In this case, I would personally select a 3 item vector rather than 26, or just test two different models. If the result won't improve when changing from 3 to 26 items you should use 3 because it produces a simpler hypothesis (according to the Occam's razor rule)." }, { "code": null, "e": 10234, "s": 9536, "text": "The last thing I want to show you is how easy is to make a mistake when selecting features without this method. Let’s look at columns 4 ( reanalysis_dew_point_temp_k) and 11 ( reanalysis_tdtr_k). You can tell just by looking at them that column 4 has a better predicting capability. But if you were selecting the length of those vectors by hand (or random) you can make reanalysis_dew_point_temp_k worse than reanalysis_tdtr_k. Without any prior knowledge about this feature, you can select its length to be 3 which gives us MAE of 38 which is worse than 37 scored by column 11 in row 21. That way you've just made one of the best features you have as useful as one of the worst features you have." }, { "code": null, "e": 10760, "s": 10234, "text": "The extended version of PPS is a powerful tool to select a set of features while building your model. Sometimes it might lead to a deeper understanding of the data event without expert knowledge on the subject. Even if it might take a while to calculate all PPS for different lengths of input vectors it is a time well spent. EDA ( Exploratory Data Analysis) is still one of the most important parts of every Data Science/Machine Learning project, and you shouldn’t skip it or just limit yourself to the default set of tools." }, { "code": null, "e": 10802, "s": 10760, "text": "Originally published at https://erdem.pl." } ]
Removing strings from tuple in Python
When it is required to remove the strings froma tuple, the list comprehension and the 'type' method can be used. A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). A list of tuple basically contains tuples enclosed in a list. The list comprehension is a shorthand to iterate through the list and perform operations on it. The 'type' method returns the class of the iterable passed to it as an argument. Below is a demonstration for the same − Live Demo my_list = [('Hi', 45, 67), ('There', 45, 32), ('Jane', 59, 13)] print("The list is : ") print(my_list) my_result = [tuple([j for j in i if type(j) != str]) for i in my_list] print("The list of tuple after removing the string is : ") print(my_result) The list is : [('Hi', 45, 67), ('There', 45, 32), ('Jane', 59, 13)] The list of tuple after removing the string is : [(45, 67), (45, 32), (59, 13)] A list of tuple is defined, and is displayed on the console. It is iterated over, using list comprehension. It is checked to see for not being a string. It is then converted to a tuple, and then to a list again. This operation's data is stored in a variable. This variable is the output that is displayed on the console.
[ { "code": null, "e": 1176, "s": 1062, "text": "When it is required to remove the strings froma tuple, the list comprehension and the 'type' method can be used." }, { "code": null, "e": 1303, "s": 1176, "text": "A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on)." }, { "code": null, "e": 1365, "s": 1303, "text": "A list of tuple basically contains tuples enclosed in a list." }, { "code": null, "e": 1461, "s": 1365, "text": "The list comprehension is a shorthand to iterate through the list and perform operations on it." }, { "code": null, "e": 1542, "s": 1461, "text": "The 'type' method returns the class of the iterable passed to it as an argument." }, { "code": null, "e": 1582, "s": 1542, "text": "Below is a demonstration for the same −" }, { "code": null, "e": 1592, "s": 1582, "text": "Live Demo" }, { "code": null, "e": 1847, "s": 1592, "text": "my_list = [('Hi', 45, 67), ('There', 45, 32), ('Jane', 59, 13)]\n\nprint(\"The list is : \")\nprint(my_list)\n\nmy_result = [tuple([j for j in i if type(j) != str])\n for i in my_list]\nprint(\"The list of tuple after removing the string is : \")\nprint(my_result)" }, { "code": null, "e": 1995, "s": 1847, "text": "The list is :\n[('Hi', 45, 67), ('There', 45, 32), ('Jane', 59, 13)]\nThe list of tuple after removing the string is :\n[(45, 67), (45, 32), (59, 13)]" }, { "code": null, "e": 2056, "s": 1995, "text": "A list of tuple is defined, and is displayed on the console." }, { "code": null, "e": 2103, "s": 2056, "text": "It is iterated over, using list comprehension." }, { "code": null, "e": 2148, "s": 2103, "text": "It is checked to see for not being a string." }, { "code": null, "e": 2207, "s": 2148, "text": "It is then converted to a tuple, and then to a list again." }, { "code": null, "e": 2254, "s": 2207, "text": "This operation's data is stored in a variable." }, { "code": null, "e": 2316, "s": 2254, "text": "This variable is the output that is displayed on the console." } ]
Python | Progress Bar widget in kivy - GeeksforGeeks
18 Jan, 2022 Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. Kivy Tutorial – Learn Kivy with Examples. ProgressBar widget is used to visualize the progress of some task. Only the horizontal mode is currently supported: the vertical mode is not yet available.The progress bar has no interactive elements and is a display-only widget. To use it, simply assign a value to indicate the current progress: Python3 from kivy.uix.progressbar import ProgressBarpb = ProgressBar(max = 1000) # this will update the graphics automatically (75 % done)pb.value = 750 To work with the progressbar widget you must have to import it by the command: from kivy.uix.progressbar import ProgressBar The progress bar take takes two arguments: 1) max: Maximum value allowed for value. It is a Numericproperty and defaults to 100.2) value: Current Value for the slider Basic Approach: 1) import kivy 2) import kivyApp 3) import progressbar 4) import Boxlayout(according to need) 5) Set minimum version(optional) 6) Create Layout class: 7) Create App class 8) return Layout/widget/Class(according to requirement) 9) Run an instance of the class Note: This code is for a complete working progressbar and you need to focus only the creation and working of the progressbar no need to take stress on other properties I will be covering them in future.You first have to click on the button that is made in the file and then the progressbar will show. Implementation of the Approach: Python3 # Program to Show how to create a Progressbar in .kv file # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The ProgressBar widget is used to# visualize the progress of some taskfrom kivy.uix.progressbar import ProgressBar # BoxLayout arranges children in a vertical or horizontal box. # or help to put the children at the desired location. from kivy.uix.boxlayout import BoxLayout # The Clock object allows you to schedule a# function call in the futurefrom kivy.clock import Clock # The Button is a Label with associated actions # that is triggered when the button # is pressed (or released after a click / touch). from kivy.uix.button import Button # Popup widget is used to create popups. # By default, the popup will cover # the whole “parent” window. # When you are creating a popup, # you must at least set a Popup.title and Popup.content.from kivy.uix.popup import Popup # A Widget is the base building block# of GUI interfaces in Kivy.# It provides a Canvas that# can be used to draw on screen.from kivy.uix.widget import Widget # ObjectProperty is a specialised sub-class# of the Property class, so it has the same# initialisation parameters as it:# By default, a Property always takes a default# value[.] The default value must be a value# that agrees with the Property type.from kivy.properties import ObjectProperty # Create the widget classclass MyWidget(Widget): progress_bar = ObjectProperty() def __init__(self, **kwa): super(MyWidget, self).__init__(**kwa) self.progress_bar = ProgressBar() self.popup = Popup( title ='Download', content = self.progress_bar ) self.popup.bind(on_open = self.puopen) self.add_widget(Button(text ='Download', on_release = self.pop)) # the function which works when you click = k the button def pop(self, instance): self.progress_bar.value = 1 self.popup.open() # To continuously increasing the value of pb. def next(self, dt): if self.progress_bar.value>= 100: return False self.progress_bar.value += 1 def puopen(self, instance): Clock.schedule_interval(self.next, 1 / 25) # Create the App class class MyApp(App): def build(self): return MyWidget() # run the Appif __name__ in ("__main__"): MyApp().run() Output: Image 1: Image 2: domjanadam sooda367 sagar0719kumar saurabh1990aror Python-gui Python-kivy 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 How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace()
[ { "code": null, "e": 41137, "s": 41109, "text": "\n18 Jan, 2022" }, { "code": null, "e": 41373, "s": 41137, "text": "Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications." }, { "code": null, "e": 41416, "s": 41373, "text": " Kivy Tutorial – Learn Kivy with Examples." }, { "code": null, "e": 41646, "s": 41416, "text": "ProgressBar widget is used to visualize the progress of some task. Only the horizontal mode is currently supported: the vertical mode is not yet available.The progress bar has no interactive elements and is a display-only widget." }, { "code": null, "e": 41713, "s": 41646, "text": "To use it, simply assign a value to indicate the current progress:" }, { "code": null, "e": 41721, "s": 41713, "text": "Python3" }, { "code": "from kivy.uix.progressbar import ProgressBarpb = ProgressBar(max = 1000) # this will update the graphics automatically (75 % done)pb.value = 750", "e": 41867, "s": 41721, "text": null }, { "code": null, "e": 41946, "s": 41867, "text": "To work with the progressbar widget you must have to import it by the command:" }, { "code": null, "e": 41991, "s": 41946, "text": "from kivy.uix.progressbar import ProgressBar" }, { "code": null, "e": 42034, "s": 41991, "text": "The progress bar take takes two arguments:" }, { "code": null, "e": 42158, "s": 42034, "text": "1) max: Maximum value allowed for value. It is a Numericproperty and defaults to 100.2) value: Current Value for the slider" }, { "code": null, "e": 42434, "s": 42158, "text": "Basic Approach:\n\n1) import kivy\n2) import kivyApp\n3) import progressbar\n4) import Boxlayout(according to need)\n5) Set minimum version(optional)\n6) Create Layout class:\n7) Create App class\n8) return Layout/widget/Class(according to requirement)\n9) Run an instance of the class" }, { "code": null, "e": 42735, "s": 42434, "text": "Note: This code is for a complete working progressbar and you need to focus only the creation and working of the progressbar no need to take stress on other properties I will be covering them in future.You first have to click on the button that is made in the file and then the progressbar will show." }, { "code": null, "e": 42767, "s": 42735, "text": "Implementation of the Approach:" }, { "code": null, "e": 42775, "s": 42767, "text": "Python3" }, { "code": "# Program to Show how to create a Progressbar in .kv file # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The ProgressBar widget is used to# visualize the progress of some taskfrom kivy.uix.progressbar import ProgressBar # BoxLayout arranges children in a vertical or horizontal box. # or help to put the children at the desired location. from kivy.uix.boxlayout import BoxLayout # The Clock object allows you to schedule a# function call in the futurefrom kivy.clock import Clock # The Button is a Label with associated actions # that is triggered when the button # is pressed (or released after a click / touch). from kivy.uix.button import Button # Popup widget is used to create popups. # By default, the popup will cover # the whole “parent” window. # When you are creating a popup, # you must at least set a Popup.title and Popup.content.from kivy.uix.popup import Popup # A Widget is the base building block# of GUI interfaces in Kivy.# It provides a Canvas that# can be used to draw on screen.from kivy.uix.widget import Widget # ObjectProperty is a specialised sub-class# of the Property class, so it has the same# initialisation parameters as it:# By default, a Property always takes a default# value[.] The default value must be a value# that agrees with the Property type.from kivy.properties import ObjectProperty # Create the widget classclass MyWidget(Widget): progress_bar = ObjectProperty() def __init__(self, **kwa): super(MyWidget, self).__init__(**kwa) self.progress_bar = ProgressBar() self.popup = Popup( title ='Download', content = self.progress_bar ) self.popup.bind(on_open = self.puopen) self.add_widget(Button(text ='Download', on_release = self.pop)) # the function which works when you click = k the button def pop(self, instance): self.progress_bar.value = 1 self.popup.open() # To continuously increasing the value of pb. def next(self, dt): if self.progress_bar.value>= 100: return False self.progress_bar.value += 1 def puopen(self, instance): Clock.schedule_interval(self.next, 1 / 25) # Create the App class class MyApp(App): def build(self): return MyWidget() # run the Appif __name__ in (\"__main__\"): MyApp().run() ", "e": 45392, "s": 42775, "text": null }, { "code": null, "e": 45400, "s": 45392, "text": "Output:" }, { "code": null, "e": 45409, "s": 45400, "text": "Image 1:" }, { "code": null, "e": 45418, "s": 45409, "text": "Image 2:" }, { "code": null, "e": 45429, "s": 45418, "text": "domjanadam" }, { "code": null, "e": 45438, "s": 45429, "text": "sooda367" }, { "code": null, "e": 45453, "s": 45438, "text": "sagar0719kumar" }, { "code": null, "e": 45469, "s": 45453, "text": "saurabh1990aror" }, { "code": null, "e": 45480, "s": 45469, "text": "Python-gui" }, { "code": null, "e": 45492, "s": 45480, "text": "Python-kivy" }, { "code": null, "e": 45499, "s": 45492, "text": "Python" }, { "code": null, "e": 45597, "s": 45499, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45606, "s": 45597, "text": "Comments" }, { "code": null, "e": 45619, "s": 45606, "text": "Old Comments" }, { "code": null, "e": 45647, "s": 45619, "text": "Read JSON file using Python" }, { "code": null, "e": 45697, "s": 45647, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 45719, "s": 45697, "text": "Python map() function" }, { "code": null, "e": 45763, "s": 45719, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 45798, "s": 45763, "text": "Read a file line by line in Python" }, { "code": null, "e": 45820, "s": 45798, "text": "Enumerate() in Python" }, { "code": null, "e": 45852, "s": 45820, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 45882, "s": 45852, "text": "Iterate over a list in Python" }, { "code": null, "e": 45924, "s": 45882, "text": "Different ways to create Pandas Dataframe" } ]
Routing requests in Node.js
Routing http requests is important because we want to execute different business rules based on request url and the responses will be different for each routes. Earlier we saw, we can get the url by request.url in node. Simple example of user name input with routes is shown below − const http = require('http'); const server = http.createServer((req, res)=>{ const url = req.url; if(url === '/'){ res.write('<html>'); res.write('<head> <title> Hello TutorialsPoint </title> </head>'); res.write(' <body> <form action="/username" method="POST"> <input type="text" name="user"/> <button type="submit">Submit</button> </body>'); res.write('</html>'); return res.end(); } }); server.listen(3000); Run it on terminal: node App.js Open browser and navigate to localhost:3000/ you will see below output − We checked if url is matching with ‘/’, then only sending a response to display a input box with submit button to client. Here in code, we used return res.end() to avoid any change in response object once end() function is called. If the url is different than just ‘/’ then we can display other messages. We used form action ‘/username’ and method is post. Also we have input box with name attribute as user. This name attribute will be passed in the post request for further use. Complete App.js file is − const http = require('http'); const server = http.createServer((req, res)=>{ const url = req.url; if(url === '/'){ res.write('<html>'); res.write('<head> <title> Hello TutorialsPoint </title> </head>'); res.write(' <body> <form action="/username" method="POST"> <input type="text" name="username"/> <button type="submit">Submit</button> </body>'); res.write('</html>'); return res.end(); } res.write('<html>'); res.write('<head> <title> Hello TutorialsPoint </title> </head>'); res.write(' <body> Hello </body>'); res.write('</html>'); res.end(); }); server.listen(3000); The outputs screen once username is entered and send is clicked − We can see here, the url is changed to /username, it is because we added form action in earlier response. In the second res.end(), we have not added a return statement because there is no code after that so we don’t need to bother about it. With url /username, our code does not execute the if block containing code for form input but instead will execute the code below the if block.
[ { "code": null, "e": 1223, "s": 1062, "text": "Routing http requests is important because we want to execute different business rules based on request url and the responses will be different for each routes." }, { "code": null, "e": 1345, "s": 1223, "text": "Earlier we saw, we can get the url by request.url in node. Simple example of user name input with routes is shown below −" }, { "code": null, "e": 1807, "s": 1345, "text": "const http = require('http');\nconst server = http.createServer((req, res)=>{\n const url = req.url;\n if(url === '/'){\n res.write('<html>');\n res.write('<head> <title> Hello TutorialsPoint </title> </head>');\n res.write(' <body> <form action=\"/username\" method=\"POST\">\n <input type=\"text\" name=\"user\"/>\n <button type=\"submit\">Submit</button> </body>');\n res.write('</html>');\n return res.end();\n }\n});\nserver.listen(3000);" }, { "code": null, "e": 1839, "s": 1807, "text": "Run it on terminal: node App.js" }, { "code": null, "e": 1912, "s": 1839, "text": "Open browser and navigate to localhost:3000/ you will see below output −" }, { "code": null, "e": 2143, "s": 1912, "text": "We checked if url is matching with ‘/’, then only sending a response to display a input box with submit button to client. Here in code, we used return res.end() to avoid any change in response object once end() function is called." }, { "code": null, "e": 2393, "s": 2143, "text": "If the url is different than just ‘/’ then we can display other messages. We used form action ‘/username’ and method is post. Also we have input box with name attribute as user. This name attribute will be passed in the post request for further use." }, { "code": null, "e": 2419, "s": 2393, "text": "Complete App.js file is −" }, { "code": null, "e": 3051, "s": 2419, "text": "const http = require('http');\nconst server = http.createServer((req, res)=>{\n const url = req.url;\n if(url === '/'){\n res.write('<html>');\n res.write('<head> <title> Hello TutorialsPoint </title> </head>');\n res.write(' <body> <form action=\"/username\" method=\"POST\"> <input type=\"text\" name=\"username\"/> <button type=\"submit\">Submit</button> </body>');\n res.write('</html>');\n return res.end();\n }\n res.write('<html>');\n res.write('<head> <title> Hello TutorialsPoint </title> </head>');\n res.write(' <body> Hello </body>');\n res.write('</html>');\n res.end();\n});\nserver.listen(3000);" }, { "code": null, "e": 3117, "s": 3051, "text": "The outputs screen once username is entered and send is clicked −" }, { "code": null, "e": 3223, "s": 3117, "text": "We can see here, the url is changed to /username, it is because we added form action in earlier response." }, { "code": null, "e": 3358, "s": 3223, "text": "In the second res.end(), we have not added a return statement because there is no code after that so we don’t need to bother about it." }, { "code": null, "e": 3502, "s": 3358, "text": "With url /username, our code does not execute the if block containing code for form input but instead will execute the code below the if block." } ]
C++ boost::dynamic_bitset Class with Examples - GeeksforGeeks
22 Oct, 2021 The boost has more than 150 libraries in it, where a couple of most frequently used libraries were already included in C++ standard library. The dynamic_bitset is a powerful library used for bit manipulation. The dynamic_bitset class is used to represent a set of bits in either 0(reset) or 1(set) form. dynamic_bitset is an improvement over bitset (std::bitset and boost::bitset) which allocates any required length of bits at runtime, contrary to bitset whose bit’s length has to be determined at compile time.The dynamic_bitset if found under the boost header boost/dynamic_bitset.hpp. Syntax: boost::dynamic_bitset <uint8_t> B (N, num); The parameters of the constructors are N which signifies the required number of bits in the set. num signifies any integral value whose bits will be stored. uint8_t signifies the block size (8 here, it can also be empty if we don’t need to specify block size). Each individual bits of the dynamic_bitset can be accessed similar to bitset indexing operator []. Please note that bit representation of a number B in dynamic_bitset of length n is represented as: B[n-1] B[n-2] ... B[1] B[0] In other words, the indexing in dynamic_bitset works in reverse order (similar to bitset). Each bit in dynamic_bitset takes exactly 1-bit space because of its optimization thus making operations faster than boolean vector.Member Functions: The basic member functions that can be performed on dynamic_bitset are listed below: set(): It assigns every bit with 1 reset(): It assigns nth bit with 0 if the n is passed in argument, else it clears the entire bitset object. flip(): It inverts any given bit i.e. toggle 0 to 1 or vice-versa size(): It returns the size of the dynamic_bitset object resize(): It is used to increase or decrease the size of the object push_back(): It increases the size of dynamic_bitset object by one and pushes the value at MSB pop_back(): It removes one bit from MSB num_blocks(): It returns the number of blocks in bitset append: It appends the bits at the most-significant bit. This increases the size of the bitset by bits_per_block. For i in the range [0, bits_per_block), the bit at position (size + i) is set to ((value >> i) & 1) empty(): It returns true if the length of dynamic_bitset is 0, else it returns false. count(): It returns the number of set bits in dynamic_bitset. all(): It tests if all of the bits in dynamic_bitset are set, if they are it returns true else false. any(): It tests if atleast one of the bit in dynamic_bitset is set, if they are it returns true else false. none(): It tests if none of the bits in dynamic_bitset are set, if none of them are set then it returns true else false. test(): It tests if the ith bit is set or not. If set it returns true else false. Example 1: CPP #include <boost/dynamic_bitset.hpp>#include <iostream> using namespace std; int main(int argc, char* argv[]){ int bit_size = 8; // B1 is initialized with size 0 // with all bits 0 boost::dynamic_bitset<> B1; // B2 is initialized with size // bit_size with all bits 0 boost::dynamic_bitset<> B2(bit_size); // B3 is initialized with size // bit_size and value 14 boost::dynamic_bitset<> B3(bit_size, 14); // B4 is initialized with size // bit_size, value 14 and // block_size of 8 bits boost::dynamic_bitset<uint8_t> B4(16, 84); // Empty cout << "Content of B1 is: " << B1 << endl; // 00000000 cout << "Content of B2 is: " << B2 << endl; cout << "Binary representation of 14 in 8 bit: " << B3 << endl; cout << "Content of B4 is: " << B4 << endl << endl; // Setting 1 st of B2 to 1 cout << "Content of B2 before set(): " << B2 << endl; B2.set(0); cout << "Content of B2 after set(0): " << B2 << endl; // Setting every bits of B22 to 1 B2.set(); cout << "Content of B2 after set(): " << B2 << endl; // Resetting 2nd bit to 0 B2.reset(1); cout << "After resetting 2nd bit of B2: " << B2<< endl; // Resetting every bit to 0 B2.reset(); cout << "After resetting every bit of B2: " << B2 << endl; // Flipping first bit of B3 cout << "Content of B3 before flip(): " << B3 << endl; B3.flip(0); cout << "Content of B3 after flip(0): " << B3 << endl; // Flipping every bits of B3 B3.flip(); cout << "Content of B3 after flip(): " << B3 << endl << endl; // Size of B1, B2, B3, B4 cout << "Size of B1 is: " << B1.size() << endl; cout << "Size of B2 is: " << B2.size() << endl; cout << "Size of B3 is: " << B3.size() << endl; cout << "Size of B4 is: " << B4.size() << endl << endl; // Resizing B1 to size 4, // default bit-value 0 B1.resize(4); cout << "B1 after increasing size to 4 bits: " << B1 << endl; // Resizing B1 to size 8, bit-value 1. // If num_bits > size() then the bits // in the range [0, size()) remain the same, // and the bits in [size(), num_bits) // are all set to value (here 1). B1.resize(8, 1); cout << "B1 after increasing size to 8 bits: " << B1 << endl; // Resizing B1 to size 1 i.e. // slicing [1, B1.size()-1) B1.resize(1); cout << "B1 after decreasing size to 1 bit: " << B1 << endl << endl; // Pushing a set bit at MSB in B1 B1.push_back(1); cout << "B1 after push(1) operation: " << B1 << endl; // Pushing a reset bit at MSB in B1 B1.push_back(0); cout << "B1 after push(0) operation : " << B1 << endl << endl; // Poping 1 bit from MSB in B1 cout << "B1 before pop operation: " << B1 << endl; B1.pop_back(); cout << "B1 after pop operation: " << B1 << endl << endl; // Number of blocks = number of bits / block size cout << "Number of blocks in B4: " << B4.num_blocks() << endl << endl; // Checking if any bitset is empty cout << "B1 is " << (B1.empty() ? "empty" : "not empty") << endl; cout << "B2 is " << (B2.empty() ? "empty" : "not empty") << endl; // Resizing B3 to 0 B3.resize(0); cout << "B3 is " << (B3.empty() ? "empty" : "not empty") << endl << endl; // Counting number of set bits in B4 cout << "Content of B4 is: " << B4 << endl; cout << "Number of set bits in it are: " << B4.count() << endl << endl; // Checking if all of the bits of B2 is set B2.set(); // B2 => 11111111 cout << "All bits in B2 are " << (B2.all() ? "set" : "not set") << endl; B2.reset(2); // B2 => 11111011 cout << "All bits in B2 are " << (B2.all() ? "set" : "not set") << endl << endl; // Checking if any of the bits of B2 is set cout << (B2.any() ? "Atleast one" : "No") << " bit in B2 is set " << endl; B2.reset(); // B2 => 00000000 cout << (B2.any() ? "Atleast one" : "No") << " bit in B2 is set " << endl << endl; // Checking if none of the bits of B2 are set // B2 => 00000000 if (B2.none()) cout << "None of the bits in B2 is set"; else cout << "Atleast one bit in B2 is set"; cout << endl << endl; // Testing if 1st bit of B1 is set or not cout << "Content of B1 is: " << B1 << endl; if (B1.test(1)) cout << "B1[1] is set"; else cout << "B1[1] is reset"; return 0;} Content of B1 is: Content of B2 is: 00000000 Binary representation of 14 in 8 bit: 00001110 Content of B4 is: 0000000001010100 Content of B2 before set(): 00000000 Content of B2 after set(0): 00000001 Content of B2 after set(): 11111111 After resetting 2nd bit of B2: 11111101 After resetting every bit of B2: 00000000 Content of B3 before flip(): 00001110 Content of B3 after flip(0): 00001111 Content of B3 after flip(): 11110000 Size of B1 is: 0 Size of B2 is: 8 Size of B3 is: 8 Size of B4 is: 16 B1 after increasing size to 4 bits: 0000 B1 after increasing size to 8 bits: 11110000 B1 after decreasing size to 1 bit: 0 B1 after push(1) operation: 10 B1 after push(0) operation : 010 B1 before pop operation: 010 B1 after pop operation: 10 Number of blocks in B4: 2 B1 is not empty B2 is not empty B3 is empty Content of B4 is: 0000000001010100 Number of set bits in it are: 3 All bits in B2 are set All bits in B2 are not set Atleast one bit in B2 is set No bit in B2 is set None of the bits in B2 is set Content of B1 is: 10 B1[1] is set Operators: Some of the operators that can be helpful for bit manipulation: operator[]: It returns a reference of nth bit. operator&=(): It performs bitwise-AND with current bitset object and bitset object passed in argument. Eg. B1.operator&=(B2); bitwise-AND of B1 and B2 i.e. B1 & B2 (B1 and B2 must have same number of bits). operator|=(): It performs bitwise-OR with current bitset object and bitset object passed in argument. Eg. B1.operator|=(B2); bitwise-OR of B1 and B2 i.e. B1 | B2 (B1 and B2 must have same number of bits). operator^=(): It performs bitwise-XOR with current bitset object and bitset object passed in argument. Eg. B1.operator^=(B2); bitwise-XOR of B1 and B2 i.e. B1 ^ B2 (B1 and B2 must have same number of bits). operator-=(): It performs set difference with current bitset object and bitset object passed in argument. Eg. B1.operator-=(B2); set difference of B1 and B2 i.e. B1 – B2 (B1 and B2 must have same number of bits). operator=(): It assigns current bitset object with object passed in parameter. operator==(): It validates if current bitset object is exactly equal to that of passed as parameter. operator!=(): It validates if current bitset object is not equal to that of passed as parameter. operator<(): It returns true if current bitset is lexicographically less than the bitet object passed as parameter, else it returns false. operator>(): It returns true if current bitset is lexicographically greater than the bitet object passed as parameter, else it returns false. operator<=(): It returns true if current bitset is lexicographically less than or equal to the bitet object passed as parameter, else it returns false. operator>=(): It returns true if current bitset is lexicographically greater than or equal to the bitet object passed as parameter, else it returns false. operator~(): It creates a copy of the current bitset with all of its bits flipped. operator<<(): It creates a copy of the current bitset object which is shifted to the left by n bits. operator>>(): It creates a copy of the current bitset object which is shifted to the right by n bits. operator<<=(): It shifts the current bitset object to left by n bits. operator>>=(): It shifts the current bitset object to right by n bits. Example 2: CPP #include <boost/dynamic_bitset.hpp>#include <iostream>using namespace std; int main(int argc, char* argv[]){ int n_bits = 8; boost::dynamic_bitset<> B1(n_bits, 123); boost::dynamic_bitset<> B2(n_bits, 206); boost::dynamic_bitset<> temp(4, 3); cout << "Binary representation of 123: " << B1 << endl; cout << "Binary representation of 206: " << B2 << endl << endl; // Operator[] is used to access an individual index // It is a reference of the nth bit. It can be used for // assignment of a boolean value at nth bit cout << "4th bit of B1 consist: " << B1[3] << endl; B1[3] = 0; cout << "Assigning 0 to 4th bit of B1: " << B1 << endl << endl; // Operator= assigns on current bitset object cout << "temp before assignment: " << temp << endl; temp.operator=(B1); cout << "temp after assignment with B1: " << temp << endl << endl; // Operator&= performs bitwise-AND cout << "B1 consist of: " << B1 << endl; cout << "B2 consist of: " << B2 << endl; temp.operator=(B1); temp.operator&=(B2); cout << "B1 AND B2 is : & " << temp << endl << endl; // Operator|= performs bitwise-OR cout << "B1 consist of: " << B1 << endl; cout << "B2 consist of: " << B2 << endl; temp.operator=(B1); temp.operator|=(B2); cout << "B1 OR B2 is : | " << temp << endl << endl; // Operator^= performs bitwise-XOR cout << "B1 consist of: " << B1 << endl; cout << "B2 consist of: " << B2 << endl; temp.operator=(B1); temp.operator^=(B2); cout << "B1 XOR B2 is : ^ " << temp << endl << endl; // Operator-= performs set difference cout << "B1 consist of: " << B1 << endl; cout << "B2 consist of: " << B2 << endl; temp.operator=(B1); temp.operator-=(B2); cout << "Set differ is: " << temp << endl << endl; // Operator== checks if bitset object is equal to // another one, bit length has to be same for true cout << "dynamic_bitset B1 and B2 are " << (operator==(B1, B2) ? "equal" : "not equal") << endl; boost::dynamic_bitset<> B3(2, 0), B4(3, 0); cout << "Content of B3: " << B3 << endl << "Content of B4: " << B4 << endl << "dynamic_bitset B3 and B4 are " << (operator==(B3, B4) ? "equal" : "not equal") << endl; B3.operator=(B4); cout << "dynamic_bitset B3 and B4 are: " << (operator==(B3, B4) ? "equal" : "not equal") << endl << endl; // Operator!= checks if bitset object is unequal cout << "dynamic_bitset B1 and B2 are "; cout << (operator!=(B1, B2) ? "not equal" : "equal") << endl << endl; // Operator< checks if first bitset object is // lexicographically less than second one cout << "B1 consist of: " << B1 << endl; cout << "B2 consist of: " << B2 << endl; if (operator<(B1, B2)) cout << "B1 is lexicographically less than B2"; else cout << "B2 is lexicographically greater than B2"; cout << endl << endl; // Operator> checks if first bitset object is // lexicographically greater than second one cout << "B1 consist of: " << B1 << endl; boost::dynamic_bitset<> B5(8, 0); cout << "B5 consist of: " << B5 << endl; if (operator>(B1, B5)) cout << "B1 is lexicographically greater than B5"; else cout << "B1 is lexicographically less than B5"; cout << endl << endl; // Operator<= checks if first bitset object is // lexicographically less than or equal to second one cout << "B3 is lexicographically "; if (operator<=(B3, B3)) cout << "less than or equal to B3" << endl << endl; else cout << "greater than B3" << endl << endl; // Operator>= cout << "B5 consist of: " << B5 << endl; cout << "B2 consist of: " << B2 << endl; cout << "B5 is lexicographically "; if (operator>=(B5, B2)) cout << "greater than or equal to B2"; else cout << "less than B2"; cout << endl << endl; // Operator~ creates a copy of flipped bitset object cout << "Value of dynamic_bitset B4 : " << B4 << endl; cout << "Creating flipped copy of B4: "; cout << B4.operator~() << endl << endl; // Operator<< creates a copy of current bitset object // which is shifted to left by n times cout << "Value of dynamic_bitset B2: " << B2 << endl; cout << "Copy of B2 left shift 3 times is : "; cout << B2.operator<<(3) << endl; // Operator>> creates a copy of current bitset object // which is shifted to right by n times value of B2 // is not changed, the copy is displayed cout << "Copy of B2 right shift 1 time is : "; cout << B2.operator>>(1) << endl << endl; // Operator<<= shifts the current bitset object // n times to left cout << "Value of dynamic_bitset B2: " << B2 << endl; cout << "B2 left shift 3 times is : "; cout << B2.operator<<=(2) << endl; // Operator>>= shifts current bitset object // n times value to right cout << "B2 right shift 1 time is : "; cout << B2.operator>>=(3); return 0;} Binary representation of 123: 01111011 Binary representation of 206: 11001110 4th bit of B1 consist: 1 Assigning 0 to 4th bit of B1: 01110011 temp before assignment: 0011 temp after assignment with B1: 01110011 B1 consist of: 01110011 B2 consist of: 11001110 B1 AND B2 is : & 01000010 B1 consist of: 01110011 B2 consist of: 11001110 B1 OR B2 is : | 11111111 B1 consist of: 01110011 B2 consist of: 11001110 B1 XOR B2 is : ^ 10111101 B1 consist of: 01110011 B2 consist of: 11001110 Set differ is: 00110001 dynamic_bitset B1 and B2 are not equal Content of B3: 00 Content of B4: 000 dynamic_bitset B3 and B4 are not equal dynamic_bitset B3 and B4 are: equal dynamic_bitset B1 and B2 are not equal B1 consist of: 01110011 B2 consist of: 11001110 B1 is lexicographically less than B2 B1 consist of: 01110011 B5 consist of: 00000000 B1 is lexicographically greater than B5 B3 is lexicographically less than or equal to B3 B5 consist of: 00000000 B2 consist of: 11001110 B5 is lexicographically less than B2 Value of dynamic_bitset B4 : 000 Creating flipped copy of B4: 111 Value of dynamic_bitset B2: 11001110 Copy of B2 left shift 3 times is : 01110000 Copy of B2 right shift 1 time is : 01100111 Value of dynamic_bitset B2: 11001110 B2 left shift 3 times is : 00111000 B2 right shift 1 time is : 00000111 Applications: dynamic_bitset can be effectively used to represent a subset of a finite set. Each bit represents whether an element of the finite set is in the subset or not. Sieve of Eratosthenes for finding all prime numbers below an integer N. Reference: https://www.boost.org/doc/libs/1_36_0/libs/dynamic_bitset/dynamic_bitset.html anikakapoor anikaseth98 cpp-boost C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Virtual Function in C++ Templates in C++ with Examples Constructors in C++ Operator Overloading in C++ Socket Programming in C/C++ vector erase() and clear() in C++ Object Oriented Programming in C++
[ { "code": null, "e": 26089, "s": 26061, "text": "\n22 Oct, 2021" }, { "code": null, "e": 26678, "s": 26089, "text": "The boost has more than 150 libraries in it, where a couple of most frequently used libraries were already included in C++ standard library. The dynamic_bitset is a powerful library used for bit manipulation. The dynamic_bitset class is used to represent a set of bits in either 0(reset) or 1(set) form. dynamic_bitset is an improvement over bitset (std::bitset and boost::bitset) which allocates any required length of bits at runtime, contrary to bitset whose bit’s length has to be determined at compile time.The dynamic_bitset if found under the boost header boost/dynamic_bitset.hpp." }, { "code": null, "e": 26688, "s": 26678, "text": "Syntax: " }, { "code": null, "e": 26732, "s": 26688, "text": "boost::dynamic_bitset <uint8_t> B (N, num);" }, { "code": null, "e": 26773, "s": 26732, "text": "The parameters of the constructors are " }, { "code": null, "e": 26831, "s": 26773, "text": "N which signifies the required number of bits in the set." }, { "code": null, "e": 26891, "s": 26831, "text": "num signifies any integral value whose bits will be stored." }, { "code": null, "e": 26995, "s": 26891, "text": "uint8_t signifies the block size (8 here, it can also be empty if we don’t need to specify block size)." }, { "code": null, "e": 27195, "s": 26995, "text": "Each individual bits of the dynamic_bitset can be accessed similar to bitset indexing operator []. Please note that bit representation of a number B in dynamic_bitset of length n is represented as: " }, { "code": null, "e": 27223, "s": 27195, "text": "B[n-1] B[n-2] ... B[1] B[0]" }, { "code": null, "e": 27549, "s": 27223, "text": "In other words, the indexing in dynamic_bitset works in reverse order (similar to bitset). Each bit in dynamic_bitset takes exactly 1-bit space because of its optimization thus making operations faster than boolean vector.Member Functions: The basic member functions that can be performed on dynamic_bitset are listed below: " }, { "code": null, "e": 27584, "s": 27549, "text": "set(): It assigns every bit with 1" }, { "code": null, "e": 27692, "s": 27584, "text": "reset(): It assigns nth bit with 0 if the n is passed in argument, else it clears the entire bitset object." }, { "code": null, "e": 27758, "s": 27692, "text": "flip(): It inverts any given bit i.e. toggle 0 to 1 or vice-versa" }, { "code": null, "e": 27815, "s": 27758, "text": "size(): It returns the size of the dynamic_bitset object" }, { "code": null, "e": 27883, "s": 27815, "text": "resize(): It is used to increase or decrease the size of the object" }, { "code": null, "e": 27978, "s": 27883, "text": "push_back(): It increases the size of dynamic_bitset object by one and pushes the value at MSB" }, { "code": null, "e": 28018, "s": 27978, "text": "pop_back(): It removes one bit from MSB" }, { "code": null, "e": 28074, "s": 28018, "text": "num_blocks(): It returns the number of blocks in bitset" }, { "code": null, "e": 28288, "s": 28074, "text": "append: It appends the bits at the most-significant bit. This increases the size of the bitset by bits_per_block. For i in the range [0, bits_per_block), the bit at position (size + i) is set to ((value >> i) & 1)" }, { "code": null, "e": 28374, "s": 28288, "text": "empty(): It returns true if the length of dynamic_bitset is 0, else it returns false." }, { "code": null, "e": 28436, "s": 28374, "text": "count(): It returns the number of set bits in dynamic_bitset." }, { "code": null, "e": 28538, "s": 28436, "text": "all(): It tests if all of the bits in dynamic_bitset are set, if they are it returns true else false." }, { "code": null, "e": 28646, "s": 28538, "text": "any(): It tests if atleast one of the bit in dynamic_bitset is set, if they are it returns true else false." }, { "code": null, "e": 28767, "s": 28646, "text": "none(): It tests if none of the bits in dynamic_bitset are set, if none of them are set then it returns true else false." }, { "code": null, "e": 28849, "s": 28767, "text": "test(): It tests if the ith bit is set or not. If set it returns true else false." }, { "code": null, "e": 28860, "s": 28849, "text": "Example 1:" }, { "code": null, "e": 28864, "s": 28860, "text": "CPP" }, { "code": "#include <boost/dynamic_bitset.hpp>#include <iostream> using namespace std; int main(int argc, char* argv[]){ int bit_size = 8; // B1 is initialized with size 0 // with all bits 0 boost::dynamic_bitset<> B1; // B2 is initialized with size // bit_size with all bits 0 boost::dynamic_bitset<> B2(bit_size); // B3 is initialized with size // bit_size and value 14 boost::dynamic_bitset<> B3(bit_size, 14); // B4 is initialized with size // bit_size, value 14 and // block_size of 8 bits boost::dynamic_bitset<uint8_t> B4(16, 84); // Empty cout << \"Content of B1 is: \" << B1 << endl; // 00000000 cout << \"Content of B2 is: \" << B2 << endl; cout << \"Binary representation of 14 in 8 bit: \" << B3 << endl; cout << \"Content of B4 is: \" << B4 << endl << endl; // Setting 1 st of B2 to 1 cout << \"Content of B2 before set(): \" << B2 << endl; B2.set(0); cout << \"Content of B2 after set(0): \" << B2 << endl; // Setting every bits of B22 to 1 B2.set(); cout << \"Content of B2 after set(): \" << B2 << endl; // Resetting 2nd bit to 0 B2.reset(1); cout << \"After resetting 2nd bit of B2: \" << B2<< endl; // Resetting every bit to 0 B2.reset(); cout << \"After resetting every bit of B2: \" << B2 << endl; // Flipping first bit of B3 cout << \"Content of B3 before flip(): \" << B3 << endl; B3.flip(0); cout << \"Content of B3 after flip(0): \" << B3 << endl; // Flipping every bits of B3 B3.flip(); cout << \"Content of B3 after flip(): \" << B3 << endl << endl; // Size of B1, B2, B3, B4 cout << \"Size of B1 is: \" << B1.size() << endl; cout << \"Size of B2 is: \" << B2.size() << endl; cout << \"Size of B3 is: \" << B3.size() << endl; cout << \"Size of B4 is: \" << B4.size() << endl << endl; // Resizing B1 to size 4, // default bit-value 0 B1.resize(4); cout << \"B1 after increasing size to 4 bits: \" << B1 << endl; // Resizing B1 to size 8, bit-value 1. // If num_bits > size() then the bits // in the range [0, size()) remain the same, // and the bits in [size(), num_bits) // are all set to value (here 1). B1.resize(8, 1); cout << \"B1 after increasing size to 8 bits: \" << B1 << endl; // Resizing B1 to size 1 i.e. // slicing [1, B1.size()-1) B1.resize(1); cout << \"B1 after decreasing size to 1 bit: \" << B1 << endl << endl; // Pushing a set bit at MSB in B1 B1.push_back(1); cout << \"B1 after push(1) operation: \" << B1 << endl; // Pushing a reset bit at MSB in B1 B1.push_back(0); cout << \"B1 after push(0) operation : \" << B1 << endl << endl; // Poping 1 bit from MSB in B1 cout << \"B1 before pop operation: \" << B1 << endl; B1.pop_back(); cout << \"B1 after pop operation: \" << B1 << endl << endl; // Number of blocks = number of bits / block size cout << \"Number of blocks in B4: \" << B4.num_blocks() << endl << endl; // Checking if any bitset is empty cout << \"B1 is \" << (B1.empty() ? \"empty\" : \"not empty\") << endl; cout << \"B2 is \" << (B2.empty() ? \"empty\" : \"not empty\") << endl; // Resizing B3 to 0 B3.resize(0); cout << \"B3 is \" << (B3.empty() ? \"empty\" : \"not empty\") << endl << endl; // Counting number of set bits in B4 cout << \"Content of B4 is: \" << B4 << endl; cout << \"Number of set bits in it are: \" << B4.count() << endl << endl; // Checking if all of the bits of B2 is set B2.set(); // B2 => 11111111 cout << \"All bits in B2 are \" << (B2.all() ? \"set\" : \"not set\") << endl; B2.reset(2); // B2 => 11111011 cout << \"All bits in B2 are \" << (B2.all() ? \"set\" : \"not set\") << endl << endl; // Checking if any of the bits of B2 is set cout << (B2.any() ? \"Atleast one\" : \"No\") << \" bit in B2 is set \" << endl; B2.reset(); // B2 => 00000000 cout << (B2.any() ? \"Atleast one\" : \"No\") << \" bit in B2 is set \" << endl << endl; // Checking if none of the bits of B2 are set // B2 => 00000000 if (B2.none()) cout << \"None of the bits in B2 is set\"; else cout << \"Atleast one bit in B2 is set\"; cout << endl << endl; // Testing if 1st bit of B1 is set or not cout << \"Content of B1 is: \" << B1 << endl; if (B1.test(1)) cout << \"B1[1] is set\"; else cout << \"B1[1] is reset\"; return 0;}", "e": 33590, "s": 28864, "text": null }, { "code": null, "e": 34655, "s": 33590, "text": "Content of B1 is: \nContent of B2 is: 00000000\nBinary representation of 14 in 8 bit: 00001110\nContent of B4 is: 0000000001010100\n\nContent of B2 before set(): 00000000\nContent of B2 after set(0): 00000001\nContent of B2 after set(): 11111111\nAfter resetting 2nd bit of B2: 11111101\nAfter resetting every bit of B2: 00000000\nContent of B3 before flip(): 00001110\nContent of B3 after flip(0): 00001111\nContent of B3 after flip(): 11110000\n\nSize of B1 is: 0\nSize of B2 is: 8\nSize of B3 is: 8\nSize of B4 is: 16\n\nB1 after increasing size to 4 bits: 0000\nB1 after increasing size to 8 bits: 11110000\nB1 after decreasing size to 1 bit: 0\n\nB1 after push(1) operation: 10\nB1 after push(0) operation : 010\n\nB1 before pop operation: 010\nB1 after pop operation: 10\n\nNumber of blocks in B4: 2\n\nB1 is not empty\nB2 is not empty\nB3 is empty\n\nContent of B4 is: 0000000001010100\nNumber of set bits in it are: 3\n\nAll bits in B2 are set\nAll bits in B2 are not set\n\nAtleast one bit in B2 is set \nNo bit in B2 is set \n\nNone of the bits in B2 is set\n\nContent of B1 is: 10\nB1[1] is set" }, { "code": null, "e": 34730, "s": 34655, "text": "Operators: Some of the operators that can be helpful for bit manipulation:" }, { "code": null, "e": 34777, "s": 34730, "text": "operator[]: It returns a reference of nth bit." }, { "code": null, "e": 34984, "s": 34777, "text": "operator&=(): It performs bitwise-AND with current bitset object and bitset object passed in argument. Eg. B1.operator&=(B2); bitwise-AND of B1 and B2 i.e. B1 & B2 (B1 and B2 must have same number of bits)." }, { "code": null, "e": 35189, "s": 34984, "text": "operator|=(): It performs bitwise-OR with current bitset object and bitset object passed in argument. Eg. B1.operator|=(B2); bitwise-OR of B1 and B2 i.e. B1 | B2 (B1 and B2 must have same number of bits)." }, { "code": null, "e": 35396, "s": 35189, "text": "operator^=(): It performs bitwise-XOR with current bitset object and bitset object passed in argument. Eg. B1.operator^=(B2); bitwise-XOR of B1 and B2 i.e. B1 ^ B2 (B1 and B2 must have same number of bits)." }, { "code": null, "e": 35609, "s": 35396, "text": "operator-=(): It performs set difference with current bitset object and bitset object passed in argument. Eg. B1.operator-=(B2); set difference of B1 and B2 i.e. B1 – B2 (B1 and B2 must have same number of bits)." }, { "code": null, "e": 35688, "s": 35609, "text": "operator=(): It assigns current bitset object with object passed in parameter." }, { "code": null, "e": 35789, "s": 35688, "text": "operator==(): It validates if current bitset object is exactly equal to that of passed as parameter." }, { "code": null, "e": 35886, "s": 35789, "text": "operator!=(): It validates if current bitset object is not equal to that of passed as parameter." }, { "code": null, "e": 36025, "s": 35886, "text": "operator<(): It returns true if current bitset is lexicographically less than the bitet object passed as parameter, else it returns false." }, { "code": null, "e": 36167, "s": 36025, "text": "operator>(): It returns true if current bitset is lexicographically greater than the bitet object passed as parameter, else it returns false." }, { "code": null, "e": 36319, "s": 36167, "text": "operator<=(): It returns true if current bitset is lexicographically less than or equal to the bitet object passed as parameter, else it returns false." }, { "code": null, "e": 36474, "s": 36319, "text": "operator>=(): It returns true if current bitset is lexicographically greater than or equal to the bitet object passed as parameter, else it returns false." }, { "code": null, "e": 36557, "s": 36474, "text": "operator~(): It creates a copy of the current bitset with all of its bits flipped." }, { "code": null, "e": 36658, "s": 36557, "text": "operator<<(): It creates a copy of the current bitset object which is shifted to the left by n bits." }, { "code": null, "e": 36760, "s": 36658, "text": "operator>>(): It creates a copy of the current bitset object which is shifted to the right by n bits." }, { "code": null, "e": 36830, "s": 36760, "text": "operator<<=(): It shifts the current bitset object to left by n bits." }, { "code": null, "e": 36901, "s": 36830, "text": "operator>>=(): It shifts the current bitset object to right by n bits." }, { "code": null, "e": 36913, "s": 36901, "text": "Example 2: " }, { "code": null, "e": 36917, "s": 36913, "text": "CPP" }, { "code": "#include <boost/dynamic_bitset.hpp>#include <iostream>using namespace std; int main(int argc, char* argv[]){ int n_bits = 8; boost::dynamic_bitset<> B1(n_bits, 123); boost::dynamic_bitset<> B2(n_bits, 206); boost::dynamic_bitset<> temp(4, 3); cout << \"Binary representation of 123: \" << B1 << endl; cout << \"Binary representation of 206: \" << B2 << endl << endl; // Operator[] is used to access an individual index // It is a reference of the nth bit. It can be used for // assignment of a boolean value at nth bit cout << \"4th bit of B1 consist: \" << B1[3] << endl; B1[3] = 0; cout << \"Assigning 0 to 4th bit of B1: \" << B1 << endl << endl; // Operator= assigns on current bitset object cout << \"temp before assignment: \" << temp << endl; temp.operator=(B1); cout << \"temp after assignment with B1: \" << temp << endl << endl; // Operator&= performs bitwise-AND cout << \"B1 consist of: \" << B1 << endl; cout << \"B2 consist of: \" << B2 << endl; temp.operator=(B1); temp.operator&=(B2); cout << \"B1 AND B2 is : & \" << temp << endl << endl; // Operator|= performs bitwise-OR cout << \"B1 consist of: \" << B1 << endl; cout << \"B2 consist of: \" << B2 << endl; temp.operator=(B1); temp.operator|=(B2); cout << \"B1 OR B2 is : | \" << temp << endl << endl; // Operator^= performs bitwise-XOR cout << \"B1 consist of: \" << B1 << endl; cout << \"B2 consist of: \" << B2 << endl; temp.operator=(B1); temp.operator^=(B2); cout << \"B1 XOR B2 is : ^ \" << temp << endl << endl; // Operator-= performs set difference cout << \"B1 consist of: \" << B1 << endl; cout << \"B2 consist of: \" << B2 << endl; temp.operator=(B1); temp.operator-=(B2); cout << \"Set differ is: \" << temp << endl << endl; // Operator== checks if bitset object is equal to // another one, bit length has to be same for true cout << \"dynamic_bitset B1 and B2 are \" << (operator==(B1, B2) ? \"equal\" : \"not equal\") << endl; boost::dynamic_bitset<> B3(2, 0), B4(3, 0); cout << \"Content of B3: \" << B3 << endl << \"Content of B4: \" << B4 << endl << \"dynamic_bitset B3 and B4 are \" << (operator==(B3, B4) ? \"equal\" : \"not equal\") << endl; B3.operator=(B4); cout << \"dynamic_bitset B3 and B4 are: \" << (operator==(B3, B4) ? \"equal\" : \"not equal\") << endl << endl; // Operator!= checks if bitset object is unequal cout << \"dynamic_bitset B1 and B2 are \"; cout << (operator!=(B1, B2) ? \"not equal\" : \"equal\") << endl << endl; // Operator< checks if first bitset object is // lexicographically less than second one cout << \"B1 consist of: \" << B1 << endl; cout << \"B2 consist of: \" << B2 << endl; if (operator<(B1, B2)) cout << \"B1 is lexicographically less than B2\"; else cout << \"B2 is lexicographically greater than B2\"; cout << endl << endl; // Operator> checks if first bitset object is // lexicographically greater than second one cout << \"B1 consist of: \" << B1 << endl; boost::dynamic_bitset<> B5(8, 0); cout << \"B5 consist of: \" << B5 << endl; if (operator>(B1, B5)) cout << \"B1 is lexicographically greater than B5\"; else cout << \"B1 is lexicographically less than B5\"; cout << endl << endl; // Operator<= checks if first bitset object is // lexicographically less than or equal to second one cout << \"B3 is lexicographically \"; if (operator<=(B3, B3)) cout << \"less than or equal to B3\" << endl << endl; else cout << \"greater than B3\" << endl << endl; // Operator>= cout << \"B5 consist of: \" << B5 << endl; cout << \"B2 consist of: \" << B2 << endl; cout << \"B5 is lexicographically \"; if (operator>=(B5, B2)) cout << \"greater than or equal to B2\"; else cout << \"less than B2\"; cout << endl << endl; // Operator~ creates a copy of flipped bitset object cout << \"Value of dynamic_bitset B4 : \" << B4 << endl; cout << \"Creating flipped copy of B4: \"; cout << B4.operator~() << endl << endl; // Operator<< creates a copy of current bitset object // which is shifted to left by n times cout << \"Value of dynamic_bitset B2: \" << B2 << endl; cout << \"Copy of B2 left shift 3 times is : \"; cout << B2.operator<<(3) << endl; // Operator>> creates a copy of current bitset object // which is shifted to right by n times value of B2 // is not changed, the copy is displayed cout << \"Copy of B2 right shift 1 time is : \"; cout << B2.operator>>(1) << endl << endl; // Operator<<= shifts the current bitset object // n times to left cout << \"Value of dynamic_bitset B2: \" << B2 << endl; cout << \"B2 left shift 3 times is : \"; cout << B2.operator<<=(2) << endl; // Operator>>= shifts current bitset object // n times value to right cout << \"B2 right shift 1 time is : \"; cout << B2.operator>>=(3); return 0;}", "e": 42236, "s": 36917, "text": null }, { "code": null, "e": 43559, "s": 42236, "text": "Binary representation of 123: 01111011\nBinary representation of 206: 11001110\n\n4th bit of B1 consist: 1\nAssigning 0 to 4th bit of B1: 01110011\n\ntemp before assignment: 0011\ntemp after assignment with B1: 01110011\n\nB1 consist of: 01110011\nB2 consist of: 11001110\nB1 AND B2 is : & 01000010\n\nB1 consist of: 01110011\nB2 consist of: 11001110\nB1 OR B2 is : | 11111111\n\nB1 consist of: 01110011\nB2 consist of: 11001110\nB1 XOR B2 is : ^ 10111101\n\nB1 consist of: 01110011\nB2 consist of: 11001110\nSet differ is: 00110001\n\ndynamic_bitset B1 and B2 are not equal\nContent of B3: 00\nContent of B4: 000\ndynamic_bitset B3 and B4 are not equal\ndynamic_bitset B3 and B4 are: equal\n\ndynamic_bitset B1 and B2 are not equal\n\nB1 consist of: 01110011\nB2 consist of: 11001110\nB1 is lexicographically less than B2\n\nB1 consist of: 01110011\nB5 consist of: 00000000\nB1 is lexicographically greater than B5\n\nB3 is lexicographically less than or equal to B3\n\nB5 consist of: 00000000\nB2 consist of: 11001110\nB5 is lexicographically less than B2\n\nValue of dynamic_bitset B4 : 000\nCreating flipped copy of B4: 111\n\nValue of dynamic_bitset B2: 11001110\nCopy of B2 left shift 3 times is : 01110000\nCopy of B2 right shift 1 time is : 01100111\n\nValue of dynamic_bitset B2: 11001110\nB2 left shift 3 times is : 00111000\nB2 right shift 1 time is : 00000111" }, { "code": null, "e": 43575, "s": 43561, "text": "Applications:" }, { "code": null, "e": 43735, "s": 43575, "text": "dynamic_bitset can be effectively used to represent a subset of a finite set. Each bit represents whether an element of the finite set is in the subset or not." }, { "code": null, "e": 43807, "s": 43735, "text": "Sieve of Eratosthenes for finding all prime numbers below an integer N." }, { "code": null, "e": 43896, "s": 43807, "text": "Reference: https://www.boost.org/doc/libs/1_36_0/libs/dynamic_bitset/dynamic_bitset.html" }, { "code": null, "e": 43908, "s": 43896, "text": "anikakapoor" }, { "code": null, "e": 43920, "s": 43908, "text": "anikaseth98" }, { "code": null, "e": 43930, "s": 43920, "text": "cpp-boost" }, { "code": null, "e": 43934, "s": 43930, "text": "C++" }, { "code": null, "e": 43938, "s": 43934, "text": "CPP" }, { "code": null, "e": 44036, "s": 43938, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44055, "s": 44036, "text": "Inheritance in C++" }, { "code": null, "e": 44098, "s": 44055, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 44122, "s": 44098, "text": "C++ Classes and Objects" }, { "code": null, "e": 44146, "s": 44122, "text": "Virtual Function in C++" }, { "code": null, "e": 44177, "s": 44146, "text": "Templates in C++ with Examples" }, { "code": null, "e": 44197, "s": 44177, "text": "Constructors in C++" }, { "code": null, "e": 44225, "s": 44197, "text": "Operator Overloading in C++" }, { "code": null, "e": 44253, "s": 44225, "text": "Socket Programming in C/C++" }, { "code": null, "e": 44287, "s": 44253, "text": "vector erase() and clear() in C++" } ]
How to change the list item bg-color individually using ngFor in Angular 2+ ? - GeeksforGeeks
07 Sep, 2020 Introduction:We can solve this using *ngFor directive and attribute binding for binding the background colour. Approach:Using *ngFor directive iterate through a list of items in .html file.By using attribute binding, bind the background color for every item in the list.By default use an array which consists of false boolean value in .ts file.Use a on click event handler to toggle the background color of the item in the list.Once the implementation is done then serve the project using below command.ng serve --open Using *ngFor directive iterate through a list of items in .html file. By using attribute binding, bind the background color for every item in the list. By default use an array which consists of false boolean value in .ts file. Use a on click event handler to toggle the background color of the item in the list. Once the implementation is done then serve the project using below command.ng serve --open ng serve --open Implementation by code:app.component.html: <ul> <li (click)="changeColor[i]=!changeColor[i]" // we are toggling the background // colour on click event handler [style.background-color] = "changeColor[i] ? 'red' : 'green'" *ngFor="let item of list ; let i = index"> {{item.name}} </li> </ul> app.component.ts: import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]})export class AppComponent { changeColor= [false, false, false]; list = [ { name : 'GeeksForGeeks' }, { name : 'Google' }, { name : 'HackerRank'} ];} Output:Before clicking on any item: After clicking on any item: AngularJS-Misc Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event Angular PrimeNG Messages Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26354, "s": 26326, "text": "\n07 Sep, 2020" }, { "code": null, "e": 26465, "s": 26354, "text": "Introduction:We can solve this using *ngFor directive and attribute binding for binding the background colour." }, { "code": null, "e": 26873, "s": 26465, "text": "Approach:Using *ngFor directive iterate through a list of items in .html file.By using attribute binding, bind the background color for every item in the list.By default use an array which consists of false boolean value in .ts file.Use a on click event handler to toggle the background color of the item in the list.Once the implementation is done then serve the project using below command.ng serve --open" }, { "code": null, "e": 26943, "s": 26873, "text": "Using *ngFor directive iterate through a list of items in .html file." }, { "code": null, "e": 27025, "s": 26943, "text": "By using attribute binding, bind the background color for every item in the list." }, { "code": null, "e": 27100, "s": 27025, "text": "By default use an array which consists of false boolean value in .ts file." }, { "code": null, "e": 27185, "s": 27100, "text": "Use a on click event handler to toggle the background color of the item in the list." }, { "code": null, "e": 27276, "s": 27185, "text": "Once the implementation is done then serve the project using below command.ng serve --open" }, { "code": null, "e": 27292, "s": 27276, "text": "ng serve --open" }, { "code": null, "e": 27336, "s": 27292, "text": "Implementation by code:app.component.html: " }, { "code": "<ul> <li (click)=\"changeColor[i]=!changeColor[i]\" // we are toggling the background // colour on click event handler [style.background-color] = \"changeColor[i] ? 'red' : 'green'\" *ngFor=\"let item of list ; let i = index\"> {{item.name}} </li> </ul>", "e": 27692, "s": 27336, "text": null }, { "code": null, "e": 27711, "s": 27692, "text": "app.component.ts: " }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]})export class AppComponent { changeColor= [false, false, false]; list = [ { name : 'GeeksForGeeks' }, { name : 'Google' }, { name : 'HackerRank'} ];}", "e": 28028, "s": 27711, "text": null }, { "code": null, "e": 28064, "s": 28028, "text": "Output:Before clicking on any item:" }, { "code": null, "e": 28092, "s": 28064, "text": "After clicking on any item:" }, { "code": null, "e": 28107, "s": 28092, "text": "AngularJS-Misc" }, { "code": null, "e": 28114, "s": 28107, "text": "Picked" }, { "code": null, "e": 28124, "s": 28114, "text": "AngularJS" }, { "code": null, "e": 28141, "s": 28124, "text": "Web Technologies" }, { "code": null, "e": 28239, "s": 28141, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28274, "s": 28239, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 28309, "s": 28274, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 28333, "s": 28309, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 28368, "s": 28333, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 28421, "s": 28368, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 28461, "s": 28421, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28494, "s": 28461, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28539, "s": 28494, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28582, "s": 28539, "text": "How to fetch data from an API in ReactJS ?" } ]
SQL Query to Check Given Format of a Date - GeeksforGeeks
11 Aug, 2021 Here, we are going to see how to find the SQL Query to check whether the date passed to query is the date of the given format or not. In this article, we will be making use of the Microsoft SQL Server as our database. Here, we will first create a database named “geeks” then we will create a table “department” in that database. After, that we will execute our query on that table. Creating Database: CREATE DATABASE geeks; Using the Database: USE geeks; Table Definition: We have the following table named as department in our geeks database. CREATE TABLE department ( ID int, SALARY int, NAME Varchar(20), JoinDate datetime ); Adding value into the table: INSERT INTO department VALUES (1, 34000, 'Neha', '09-24-2013') INSERT INTO department VALUES (2, 33000, 'Hema', '02-02-2015') INSERT INTO department VALUES (3, 36000, 'Jaya', '09-09-2017') INSERT INTO department VALUES (4, 35000, 'Priya', '05-18-2018') INSERT INTO department VALUES (5, 34000, 'Ketan', '02-25-2019') To verify the contents of the table use the following SQL query: SELECT * FROM department; Checking whether the date passed to query is the date of the given format or not: SQL has IsDate() function which is used to check the passed value is date or not of specified format, it returns 1(true) when the specified value is date otherwise it return 0(false). Syntax: SELECT ISDATE(‘Date’) AS “Format”; OR SELECT *, ISDATE(‘ColumnName’) AS “Format” FROM TABLENAME ; Example: SELECT TOP 1000 [ID] ,[SALARY] ,[NAME] ,[JoinDate], ISDATE(JoinDate) as Format FROM [department] kk773572498 Picked SQL-Query SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Subquery What is Temporary Table in SQL? How to Create a Table With Multiple Foreign Keys in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server?
[ { "code": null, "e": 25513, "s": 25485, "text": "\n11 Aug, 2021" }, { "code": null, "e": 25731, "s": 25513, "text": "Here, we are going to see how to find the SQL Query to check whether the date passed to query is the date of the given format or not. In this article, we will be making use of the Microsoft SQL Server as our database." }, { "code": null, "e": 25895, "s": 25731, "text": "Here, we will first create a database named “geeks” then we will create a table “department” in that database. After, that we will execute our query on that table." }, { "code": null, "e": 25914, "s": 25895, "text": "Creating Database:" }, { "code": null, "e": 25937, "s": 25914, "text": "CREATE DATABASE geeks;" }, { "code": null, "e": 25957, "s": 25937, "text": "Using the Database:" }, { "code": null, "e": 25968, "s": 25957, "text": "USE geeks;" }, { "code": null, "e": 25986, "s": 25968, "text": "Table Definition:" }, { "code": null, "e": 26057, "s": 25986, "text": "We have the following table named as department in our geeks database." }, { "code": null, "e": 26159, "s": 26057, "text": "CREATE TABLE department\n(\n ID int,\n SALARY int,\n NAME Varchar(20),\n JoinDate datetime \n);" }, { "code": null, "e": 26188, "s": 26159, "text": "Adding value into the table:" }, { "code": null, "e": 26505, "s": 26188, "text": "INSERT INTO department VALUES (1, 34000, 'Neha', '09-24-2013')\nINSERT INTO department VALUES (2, 33000, 'Hema', '02-02-2015')\nINSERT INTO department VALUES (3, 36000, 'Jaya', '09-09-2017')\nINSERT INTO department VALUES (4, 35000, 'Priya', '05-18-2018')\nINSERT INTO department VALUES (5, 34000, 'Ketan', '02-25-2019')" }, { "code": null, "e": 26570, "s": 26505, "text": "To verify the contents of the table use the following SQL query:" }, { "code": null, "e": 26596, "s": 26570, "text": "SELECT * FROM department;" }, { "code": null, "e": 26678, "s": 26596, "text": "Checking whether the date passed to query is the date of the given format or not:" }, { "code": null, "e": 26862, "s": 26678, "text": "SQL has IsDate() function which is used to check the passed value is date or not of specified format, it returns 1(true) when the specified value is date otherwise it return 0(false)." }, { "code": null, "e": 26870, "s": 26862, "text": "Syntax:" }, { "code": null, "e": 26905, "s": 26870, "text": "SELECT ISDATE(‘Date’) AS “Format”;" }, { "code": null, "e": 26908, "s": 26905, "text": "OR" }, { "code": null, "e": 26968, "s": 26908, "text": "SELECT *, ISDATE(‘ColumnName’) AS “Format” FROM TABLENAME ;" }, { "code": null, "e": 26978, "s": 26968, "text": "Example: " }, { "code": null, "e": 27092, "s": 26978, "text": "SELECT TOP 1000 [ID]\n ,[SALARY]\n ,[NAME]\n ,[JoinDate], ISDATE(JoinDate) as Format \n FROM [department]" }, { "code": null, "e": 27104, "s": 27092, "text": "kk773572498" }, { "code": null, "e": 27111, "s": 27104, "text": "Picked" }, { "code": null, "e": 27121, "s": 27111, "text": "SQL-Query" }, { "code": null, "e": 27125, "s": 27121, "text": "SQL" }, { "code": null, "e": 27129, "s": 27125, "text": "SQL" }, { "code": null, "e": 27227, "s": 27129, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27293, "s": 27227, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27308, "s": 27293, "text": "SQL | Subquery" }, { "code": null, "e": 27340, "s": 27308, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27397, "s": 27340, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 27475, "s": 27397, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 27492, "s": 27475, "text": "SQL using Python" }, { "code": null, "e": 27528, "s": 27492, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 27559, "s": 27528, "text": "SQL Query to Compare Two Dates" }, { "code": null, "e": 27625, "s": 27559, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" } ]
Project Idea | Anonymous Message Prank Game in PHP - GeeksforGeeks
20 Jan, 2022 In this article, we are going to learn concepts of database, how to make a simple game using PHP and MySQL, how can we implement a database in which we send secret messages for a particular user, how to arrange tables in the database and Also we learn some security issues that how can we save our web apps from these security issues. Domain: Web application using PHP and MySQL database. Features: Sign Up Login Secret Messages to a particular user by using a URL provided by Sign up user Sending messages by Ajax Requests Database It is a simple game in which users send secret messages for a particular user by using a link. Through this game we learn a lot of things like how to sign up and login to a user by creating a session and destroying session, How can we store data of users and secret messages in the database for a particular user who has created a link for his name. Tools and Technologies: Front-End: BOOTSTRAP CDNHTML and CSS BOOTSTRAP CDN HTML and CSS Back-End: PHPJQueryDatabase – MySQL PHP JQuery Database – MySQL Tools: XAMP Server ( for creating server on Localhost ) XAMP Server ( for creating server on Localhost ) Project Implementation: Make an empty Folder and create files According to this File structure File structure Assets folder: First, let us start from the assets folder. So we create this folder because of assets that we use in a project like images, videos, global CSS, and js file which is attached to all files in our project. we also create an index.php file for all folders because if someone is trying to access this folder then he sees only an index page not our directory if index.php file is not created then anyone can see our file structure of the whole project if index.php is not created in all folders After creating index.php in all folders assets PHP HTML <!-- filename - assets/index.php --> <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Error</title></head><body> 403 - Forbidden Error</body></html> <!-- filename - assets/css/style.css --> .content { min-height: calc(93vh - 70px);}.footer { background-color: black; color: white; text-align: center; height: 40px;} .cont{ height: 300px; overflow-y: auto;} Utils Folder – make filename as protectXss.php – This file is Basically used to protect our web App from Cross-Site Scripting attacks. PHP <?php function protectxss($string) { $string=iconv(mb_detect_encoding( $string, mb_detect_order(), true), "UTF-8", $string ); $string=addcslashes($string,"'"); $string=addcslashes($string,'"'); return htmlspecialchars($string);}?> Partials Folder and make files according to file structure as shown: partials Inside the partials folder make a folder named as modals to place all modals in it Source Code PHP PHP PHP PHP PHP PHP PHP <?php// Filename partials/action.php // Including all necessary files include "dbConnect.php";include "../utils/protectXss.php"; // Signup handler for storing only names of usersif (isset($_POST['startBtn'])) { $name=protectxss($_POST['name']); $trimname=trim($name); $strreplace=str_replace(" ","_",$trimname); // Assigning them username and password $userName=$strreplace."@".time(); $password = rand(); // Converting to hash format $passhash=password_hash($password,PASSWORD_DEFAULT); $sql="INSERT INTO `an_users` (`an_id`, `an_name`, `an_username`, `an_password`, `timestamp`) VALUES (NULL, '$trimname', '$userName', '$passhash', current_timestamp())"; $result=mysqli_query($conn,$sql); if ($result) { // Creating a session for a user session_start(); $_SESSION['loggedinUser']=$userName; $_SESSION['userPass']=$password; $_SESSION['name']=$name; header("location:../welcome.php"); }else{ echo "error"; } } // Login handleif (isset($_POST['loginBtn'])) { $username=protectxss($_POST['username']); $password=protectxss($_POST['password']); $sql="SELECT `an_password`,`an_name` FROM `an_users` WHERE `an_username`='$username'"; $result=mysqli_query($conn,$sql); $row=mysqli_fetch_assoc($result); if (password_verify($password,$row['an_password'])) { session_start(); $_SESSION['loggedinUser']=$username; $_SESSION['userPass']=$password; $_SESSION['name']=$row['an_name']; header("location:../welcome.php"); } else { header("location:../index.php"); } } // Message Button for sending messagesif (isset($_POST['sendBtn'])) { $message=protectxss($_POST['message2']); $mycode=protectxss($_POST['mycode2']); // Inserting messages into another table $sql="INSERT INTO `an_messages` (`msg_id`, `msg_text`, `an_id`, `timestamp`) VALUES (NULL, '$message', '$mycode', current_timestamp())"; $result=mysqli_query($conn,$sql); if ($result) { echo "Message sent"; }else{ echo "try Again Later !"; } } ?> <?php// Filename - partials/dbConnect.php $hostname="127.0.0.1";$_username="root";$password="";$database="anonymousdb";$conn=mysqli_connect($hostname,$_username,$password,$database);?> <!-- filename - partials/footer.php --> <footer class="footer"> <p class="mt-3">Anonymous Prank</p> </footer> </body></html> <!-- filename - partials/header.php --> <!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> <link rel="stylesheet" href="assets/css/style.css"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"> </script></head> <body> <!-- filename - partials/index.php --> <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Document</title></head><body> 403 - fobidden error</body></html> <!-- filename - partials/navbar.php --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="index.php"> Anonymous Prank ???????? </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"></ul> <form class="d-flex"> <?php // Checking a user if he is login or // not then showing him logout button if (isset($_SESSION['loggedinUser'])) { echo '<a href="logout.php" class="btn btn-outline-danger"> Logout </a>'; } // Checking if a user is sending // message to other user else if (isset($_GET['abcNum'])) { echo '<a class="btn btn-danger" href="index.php"> Sign Up </a>'; } // If above conditions are false // then showing him login button else { echo '<button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#loginmodal"> login </button>'; } ?> </form> </div> </div></nav> <!-- filename - partials/modals/loginmodal.php --> <div class="modal fade" id="loginmodal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel"> Sign In </h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"> </button> </div> <div class="modal-body"> <form action="partials/action.php" method="POST"> <div class="mb-3"> <label for="exampleInputEmail1" class="form-label"> Username </label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="username"> </div> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label"> Password </label> <input type="password" class="form-control" id="exampleInputPassword1" name="password"> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-bs-dismiss="modal"> Close </button> <button type="submit" class="btn btn-primary" name="loginBtn"> Login </button> </div> </form> </div> </div> </div></div> Root Folder: Make files according to this structure. Root folder Filename – index.php Create index.php which is the main page of the web app. In this page, we are creating a form that takes the name of the user as input to start the game. PHP <?phpsession_start(); // Checking if a user is logged in or notif (isset($_SESSION['loggedinUser'])) { header("location:welcome.php");} // Including header and dbConnectinclude "partials/header.php";include "partials/dbConnect.php"; ?> // Navbar and login modal <?php include "partials/navbar.php" ?><?php include "partials/modals/loginmodal.php" ?> // Container <div class="content"> <div class="container"> <div class="p-5 mb-4 bg-light rounded-3 my-3"> <div class="container-fluid py-5 text-center"> <h1 class="display-5 fw-bold"> Anonymous message Prank Game </h1> <p class="fs-4"> Prank Your Friends by Sending Secret Messages to them They dont able to know who send message to them ???????? Enter Your Name to get Started </p> <div class="container"> <!-- Form to submit the name of a user who is creating quiz for him --> <form class="row" style="float:right;" action="partials/action.php" method="POST"> <div class="col-auto"> <label for="staticEmail2" class="visually-hidden"> Name </label> <label readonly class="form-control-plaintext"> Your Name to Get started </label> </div> <div class="col-auto"> <label for="inputPassword2" class="visually-hidden"> Name </label> <input type="text" class="form-control" name="name" placeholder="Name.."> </div> <div class="col-auto"> <button type="submit" class="btn btn-primary mb-3" name="startBtn"> Start </button> </div> </form> </div> </div> </div> </div></div> // Including footer<?php include "partials/footer.php" ?> We are creating this file for seeing messages that are come from other users and providing username and password to the signup user. Along with the username and password a link is also provided so that the signup user shares it with others and others send him anonymous messages. welcome.php PHP <?phpinclude "partials/dbConnect.php";session_start(); // Checking for a user if he is login or notif (!isset($_SESSION['loggedinUser'])) { header("location:index.php");}else{ $user_name=$_SESSION['loggedinUser'];} include "partials/header.php";?> <?php include "partials/navbar.php" ?> <!-- Main Content --> <div class="content"> <div class="container"> <div class="p-5 mb-4 bg-light rounded-3 my-3"> <div class="container-fluid py-5 text-center"> <!-- All these values are coming from index.php when user sign up --> <h1 class="display-5 fw-bold"> Hey????????, <?php echo $_SESSION['name'] ?> </h1> <h4 class="fw-bold"> Your Username - <?php echo $_SESSION['loggedinUser'] ?> </h4> <h4 class="fw-bold"> Password - <?php echo $_SESSION['userPass'] ?> </h4> <p class="fs-4"> Use these crediantials when you login again save them for future reference </p> <p class="fs-5 text-info"> Reload the page to Load new messages </p> <p class="fs-6"> Share this URL with your friends so that they can send you messages </p> <!-- Creating a Link for other so that others send messages to this user through this Link using base 64 encoding to encode username of user in Link --> <p class="fs-6 text-success"> Link - <?php echo $_SERVER['HTTP_HOST'] . "/anonymousprank/anonymous.php?abcNum=" . base64_encode($user_name) ?> </p> </div> </div> </div> <h4 class="fw-bold container">Messages</h4> <div class="container cont"> <div class="row"> <?php // Fetching all the messages from the // messages table for this particular // user only $__username=$_SESSION['loggedinUser']; $_sql="SELECT `an_id` FROM `an_users` WHERE `an_username`='$__username'"; $_result = mysqli_query($conn, $_sql); $_row = mysqli_fetch_assoc($_result); $an_u_id=$_row['an_id']; $sql = "SELECT `msg_text`,`timestamp` FROM `an_messages` WHERE `an_id`='$an_u_id'"; $result = mysqli_query($conn, $sql); // displaying messages on the page while($row = mysqli_fetch_assoc($result)){ echo ' <div class="card mx-3 my-2" style="width: 18rem;border-radius:21px; border: solid aqua 6px;"> <div class="card-body"> <p class="card-text">'.$row['msg_text'].'</p> <p class="card-text" style="float:right"> '.$row['timestamp'].' </p> </div> </div>'; } ?> </div> </div></div><?php include "partials/footer.php" ?> We are creating this file for URL which we provided to our sign up users so that they share that URL with their friends and directing friends to this file using that URL anonymous.php PHP <?phpinclude "partials/dbConnect.php";include "partials/header.php"; if (isset($_GET['abcNum'])) { // Decoding username of signup // user passed inside the url $_username = base64_decode($_GET['abcNum']);} ?><?php include "partials/navbar.php" ?> <div class="content"> <div class="container"> <div class="p-5 mb-4 bg-light rounded-3 my-3"> <div class="container-fluid py-5 text-center"> <h1 class="display-5 fw-bold"> Hey ????, Anonymous Send a Secret message to <?php // Fetching the name of the user from database $sql = "SELECT `an_name`,an_id FROM `an_users` WHERE `an_username`='$_username'"; $result = mysqli_query($conn, $sql); $record = mysqli_num_rows($result); // If find then showing page otherwise // redirecting to main page if ($record>0) { $row = mysqli_fetch_assoc($result); echo $row['an_name']; }else { header("location:index.php"); } ?> </h1> <h3 id="log" class="my-4 text-success"></h3> <div class="mb-3"> <!-- form to send messages to the sign up user --> <form method="POST" id="sendForm"> <textarea class="form-control" id="message" rows="3" name="message" required> </textarea> <input type="hidden" value= <?php echo $row['an_id']?> name="mycode" id="mycode"> <button type="submit" class="btn btn-primary my-4 btn-lg" name="sendBtn" id="sendBtn"> Send </button> </form> </div> </div> </div> </div></div> <!-- including jquery -- > <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <?php include "partials/footer.php" ?> <script> // jQuery $(document).ready(function() { /* Targeting form to send a message using ajax and pass data in the form of object and getting response*/ $("#sendForm").submit(function(e){ e.preventDefault(); let mycode = $("#mycode").val(); let message = $("#message").val(); $.post("partials/action.php", { sendBtn:true, mycode2: mycode, message2: message }, (data)=>{ $("#log").html(data) setTimeout(() => { $("#log").html("") }, 2000); $("#message").val("") }); });}); </script> To logout users and destroying sessions. PHP <?phpsession_start();session_destroy();session_unset(); header("location:index.php")?> Database: Start XAMP Server Xamp Server Strat apache and mySQL Go to browser and type 127.0.0.1 in the addressbar Go to phpmyadmin and create a new database named as “anonymousdb” Make tables according to this below structures shown To make a column unique click on “more” near “drop” and select “unique” an_users an_messages arorakashish0911 avtarkumar719 ProGeek 2021 Project-Ideas PHP ProGeek Project Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? How to create admin login page using PHP? PHP str_replace() Function How to pass form variables from one page to other page in PHP ? Different ways for passing data to view in Laravel E-commerce Website using Django College Management System using Django - Python Project How to Build a Simple Note Android App using MVVM and Room Database? Handwritten Digit Recognition using Neural Network AI Driven Snake Game using Deep Q Learning
[ { "code": null, "e": 26243, "s": 26215, "text": "\n20 Jan, 2022" }, { "code": null, "e": 26579, "s": 26243, "text": "In this article, we are going to learn concepts of database, how to make a simple game using PHP and MySQL, how can we implement a database in which we send secret messages for a particular user, how to arrange tables in the database and Also we learn some security issues that how can we save our web apps from these security issues. " }, { "code": null, "e": 26633, "s": 26579, "text": "Domain: Web application using PHP and MySQL database." }, { "code": null, "e": 26643, "s": 26633, "text": "Features:" }, { "code": null, "e": 26651, "s": 26643, "text": "Sign Up" }, { "code": null, "e": 26657, "s": 26651, "text": "Login" }, { "code": null, "e": 26734, "s": 26657, "text": "Secret Messages to a particular user by using a URL provided by Sign up user" }, { "code": null, "e": 26768, "s": 26734, "text": "Sending messages by Ajax Requests" }, { "code": null, "e": 26777, "s": 26768, "text": "Database" }, { "code": null, "e": 27127, "s": 26777, "text": "It is a simple game in which users send secret messages for a particular user by using a link. Through this game we learn a lot of things like how to sign up and login to a user by creating a session and destroying session, How can we store data of users and secret messages in the database for a particular user who has created a link for his name." }, { "code": null, "e": 27151, "s": 27127, "text": "Tools and Technologies:" }, { "code": null, "e": 27163, "s": 27151, "text": "Front-End: " }, { "code": null, "e": 27189, "s": 27163, "text": "BOOTSTRAP CDNHTML and CSS" }, { "code": null, "e": 27203, "s": 27189, "text": "BOOTSTRAP CDN" }, { "code": null, "e": 27216, "s": 27203, "text": "HTML and CSS" }, { "code": null, "e": 27227, "s": 27216, "text": "Back-End: " }, { "code": null, "e": 27253, "s": 27227, "text": "PHPJQueryDatabase – MySQL" }, { "code": null, "e": 27257, "s": 27253, "text": "PHP" }, { "code": null, "e": 27264, "s": 27257, "text": "JQuery" }, { "code": null, "e": 27281, "s": 27264, "text": "Database – MySQL" }, { "code": null, "e": 27289, "s": 27281, "text": "Tools: " }, { "code": null, "e": 27338, "s": 27289, "text": "XAMP Server ( for creating server on Localhost )" }, { "code": null, "e": 27387, "s": 27338, "text": "XAMP Server ( for creating server on Localhost )" }, { "code": null, "e": 27485, "s": 27387, "text": "Project Implementation: Make an empty Folder and create files According to this File structure " }, { "code": null, "e": 27501, "s": 27485, "text": "File structure " }, { "code": null, "e": 27871, "s": 27501, "text": "Assets folder: First, let us start from the assets folder. So we create this folder because of assets that we use in a project like images, videos, global CSS, and js file which is attached to all files in our project. we also create an index.php file for all folders because if someone is trying to access this folder then he sees only an index page not our directory " }, { "code": null, "e": 27965, "s": 27871, "text": "if index.php file is not created then anyone can see our file structure of the whole project " }, { "code": null, "e": 28009, "s": 27965, "text": "if index.php is not created in all folders " }, { "code": null, "e": 28050, "s": 28009, "text": "After creating index.php in all folders " }, { "code": null, "e": 28057, "s": 28050, "text": "assets" }, { "code": null, "e": 28061, "s": 28057, "text": "PHP" }, { "code": null, "e": 28066, "s": 28061, "text": "HTML" }, { "code": "<!-- filename - assets/index.php --> <!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Error</title></head><body> 403 - Forbidden Error</body></html>", "e": 28382, "s": 28066, "text": null }, { "code": "<!-- filename - assets/css/style.css --> .content { min-height: calc(93vh - 70px);}.footer { background-color: black; color: white; text-align: center; height: 40px;} .cont{ height: 300px; overflow-y: auto;}", "e": 28597, "s": 28382, "text": null }, { "code": null, "e": 28733, "s": 28597, "text": "Utils Folder – make filename as protectXss.php – This file is Basically used to protect our web App from Cross-Site Scripting attacks. " }, { "code": null, "e": 28737, "s": 28733, "text": "PHP" }, { "code": "<?php function protectxss($string) { $string=iconv(mb_detect_encoding( $string, mb_detect_order(), true), \"UTF-8\", $string ); $string=addcslashes($string,\"'\"); $string=addcslashes($string,'\"'); return htmlspecialchars($string);}?>", "e": 29000, "s": 28737, "text": null }, { "code": null, "e": 29070, "s": 29000, "text": "Partials Folder and make files according to file structure as shown: " }, { "code": null, "e": 29079, "s": 29070, "text": "partials" }, { "code": null, "e": 29162, "s": 29079, "text": "Inside the partials folder make a folder named as modals to place all modals in it" }, { "code": null, "e": 29175, "s": 29162, "text": "Source Code " }, { "code": null, "e": 29179, "s": 29175, "text": "PHP" }, { "code": null, "e": 29183, "s": 29179, "text": "PHP" }, { "code": null, "e": 29187, "s": 29183, "text": "PHP" }, { "code": null, "e": 29191, "s": 29187, "text": "PHP" }, { "code": null, "e": 29195, "s": 29191, "text": "PHP" }, { "code": null, "e": 29199, "s": 29195, "text": "PHP" }, { "code": null, "e": 29203, "s": 29199, "text": "PHP" }, { "code": "<?php// Filename partials/action.php // Including all necessary files include \"dbConnect.php\";include \"../utils/protectXss.php\"; // Signup handler for storing only names of usersif (isset($_POST['startBtn'])) { $name=protectxss($_POST['name']); $trimname=trim($name); $strreplace=str_replace(\" \",\"_\",$trimname); // Assigning them username and password $userName=$strreplace.\"@\".time(); $password = rand(); // Converting to hash format $passhash=password_hash($password,PASSWORD_DEFAULT); $sql=\"INSERT INTO `an_users` (`an_id`, `an_name`, `an_username`, `an_password`, `timestamp`) VALUES (NULL, '$trimname', '$userName', '$passhash', current_timestamp())\"; $result=mysqli_query($conn,$sql); if ($result) { // Creating a session for a user session_start(); $_SESSION['loggedinUser']=$userName; $_SESSION['userPass']=$password; $_SESSION['name']=$name; header(\"location:../welcome.php\"); }else{ echo \"error\"; } } // Login handleif (isset($_POST['loginBtn'])) { $username=protectxss($_POST['username']); $password=protectxss($_POST['password']); $sql=\"SELECT `an_password`,`an_name` FROM `an_users` WHERE `an_username`='$username'\"; $result=mysqli_query($conn,$sql); $row=mysqli_fetch_assoc($result); if (password_verify($password,$row['an_password'])) { session_start(); $_SESSION['loggedinUser']=$username; $_SESSION['userPass']=$password; $_SESSION['name']=$row['an_name']; header(\"location:../welcome.php\"); } else { header(\"location:../index.php\"); } } // Message Button for sending messagesif (isset($_POST['sendBtn'])) { $message=protectxss($_POST['message2']); $mycode=protectxss($_POST['mycode2']); // Inserting messages into another table $sql=\"INSERT INTO `an_messages` (`msg_id`, `msg_text`, `an_id`, `timestamp`) VALUES (NULL, '$message', '$mycode', current_timestamp())\"; $result=mysqli_query($conn,$sql); if ($result) { echo \"Message sent\"; }else{ echo \"try Again Later !\"; } } ?>", "e": 31351, "s": 29203, "text": null }, { "code": "<?php// Filename - partials/dbConnect.php $hostname=\"127.0.0.1\";$_username=\"root\";$password=\"\";$database=\"anonymousdb\";$conn=mysqli_connect($hostname,$_username,$password,$database);?>", "e": 31538, "s": 31351, "text": null }, { "code": "<!-- filename - partials/footer.php --> <footer class=\"footer\"> <p class=\"mt-3\">Anonymous Prank</p> </footer> </body></html>", "e": 31669, "s": 31538, "text": null }, { "code": "<!-- filename - partials/header.php --> <!doctype html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x\" crossorigin=\"anonymous\"> <link rel=\"stylesheet\" href=\"assets/css/style.css\"> <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js\" integrity=\"sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4\" crossorigin=\"anonymous\"> </script></head> <body>", "e": 32383, "s": 31669, "text": null }, { "code": "<!-- filename - partials/index.php --> <!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Document</title></head><body> 403 - fobidden error</body></html>", "e": 32705, "s": 32383, "text": null }, { "code": "<!-- filename - partials/navbar.php --> <nav class=\"navbar navbar-expand-lg navbar-dark bg-dark\"> <div class=\"container-fluid\"> <a class=\"navbar-brand\" href=\"index.php\"> Anonymous Prank ???????? </a> <button class=\"navbar-toggler\" type=\"button\" data-bs-toggle=\"collapse\" data-bs-target=\"#navbarSupportedContent\" aria-controls=\"navbarSupportedContent\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> <span class=\"navbar-toggler-icon\"></span> </button> <div class=\"collapse navbar-collapse\" id=\"navbarSupportedContent\"> <ul class=\"navbar-nav me-auto mb-2 mb-lg-0\"></ul> <form class=\"d-flex\"> <?php // Checking a user if he is login or // not then showing him logout button if (isset($_SESSION['loggedinUser'])) { echo '<a href=\"logout.php\" class=\"btn btn-outline-danger\"> Logout </a>'; } // Checking if a user is sending // message to other user else if (isset($_GET['abcNum'])) { echo '<a class=\"btn btn-danger\" href=\"index.php\"> Sign Up </a>'; } // If above conditions are false // then showing him login button else { echo '<button type=\"button\" class=\"btn btn-outline-primary\" data-bs-toggle=\"modal\" data-bs-target=\"#loginmodal\"> login </button>'; } ?> </form> </div> </div></nav>", "e": 34641, "s": 32705, "text": null }, { "code": "<!-- filename - partials/modals/loginmodal.php --> <div class=\"modal fade\" id=\"loginmodal\" tabindex=\"-1\" aria-labelledby=\"exampleModalLabel\" aria-hidden=\"true\"> <div class=\"modal-dialog\"> <div class=\"modal-content\"> <div class=\"modal-header\"> <h5 class=\"modal-title\" id=\"exampleModalLabel\"> Sign In </h5> <button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"> </button> </div> <div class=\"modal-body\"> <form action=\"partials/action.php\" method=\"POST\"> <div class=\"mb-3\"> <label for=\"exampleInputEmail1\" class=\"form-label\"> Username </label> <input type=\"email\" class=\"form-control\" id=\"exampleInputEmail1\" aria-describedby=\"emailHelp\" name=\"username\"> </div> <div class=\"mb-3\"> <label for=\"exampleInputPassword1\" class=\"form-label\"> Password </label> <input type=\"password\" class=\"form-control\" id=\"exampleInputPassword1\" name=\"password\"> </div> <div class=\"modal-footer\"> <button type=\"button\" class=\"btn btn-danger\" data-bs-dismiss=\"modal\"> Close </button> <button type=\"submit\" class=\"btn btn-primary\" name=\"loginBtn\"> Login </button> </div> </form> </div> </div> </div></div>", "e": 36921, "s": 34641, "text": null }, { "code": null, "e": 36974, "s": 36921, "text": "Root Folder: Make files according to this structure." }, { "code": null, "e": 36986, "s": 36974, "text": "Root folder" }, { "code": null, "e": 37007, "s": 36986, "text": "Filename – index.php" }, { "code": null, "e": 37160, "s": 37007, "text": "Create index.php which is the main page of the web app. In this page, we are creating a form that takes the name of the user as input to start the game." }, { "code": null, "e": 37164, "s": 37160, "text": "PHP" }, { "code": "<?phpsession_start(); // Checking if a user is logged in or notif (isset($_SESSION['loggedinUser'])) { header(\"location:welcome.php\");} // Including header and dbConnectinclude \"partials/header.php\";include \"partials/dbConnect.php\"; ?> // Navbar and login modal <?php include \"partials/navbar.php\" ?><?php include \"partials/modals/loginmodal.php\" ?> // Container <div class=\"content\"> <div class=\"container\"> <div class=\"p-5 mb-4 bg-light rounded-3 my-3\"> <div class=\"container-fluid py-5 text-center\"> <h1 class=\"display-5 fw-bold\"> Anonymous message Prank Game </h1> <p class=\"fs-4\"> Prank Your Friends by Sending Secret Messages to them They dont able to know who send message to them ???????? Enter Your Name to get Started </p> <div class=\"container\"> <!-- Form to submit the name of a user who is creating quiz for him --> <form class=\"row\" style=\"float:right;\" action=\"partials/action.php\" method=\"POST\"> <div class=\"col-auto\"> <label for=\"staticEmail2\" class=\"visually-hidden\"> Name </label> <label readonly class=\"form-control-plaintext\"> Your Name to Get started </label> </div> <div class=\"col-auto\"> <label for=\"inputPassword2\" class=\"visually-hidden\"> Name </label> <input type=\"text\" class=\"form-control\" name=\"name\" placeholder=\"Name..\"> </div> <div class=\"col-auto\"> <button type=\"submit\" class=\"btn btn-primary mb-3\" name=\"startBtn\"> Start </button> </div> </form> </div> </div> </div> </div></div> // Including footer<?php include \"partials/footer.php\" ?>", "e": 39805, "s": 37164, "text": null }, { "code": null, "e": 40086, "s": 39805, "text": "We are creating this file for seeing messages that are come from other users and providing username and password to the signup user. Along with the username and password a link is also provided so that the signup user shares it with others and others send him anonymous messages. " }, { "code": null, "e": 40098, "s": 40086, "text": "welcome.php" }, { "code": null, "e": 40102, "s": 40098, "text": "PHP" }, { "code": "<?phpinclude \"partials/dbConnect.php\";session_start(); // Checking for a user if he is login or notif (!isset($_SESSION['loggedinUser'])) { header(\"location:index.php\");}else{ $user_name=$_SESSION['loggedinUser'];} include \"partials/header.php\";?> <?php include \"partials/navbar.php\" ?> <!-- Main Content --> <div class=\"content\"> <div class=\"container\"> <div class=\"p-5 mb-4 bg-light rounded-3 my-3\"> <div class=\"container-fluid py-5 text-center\"> <!-- All these values are coming from index.php when user sign up --> <h1 class=\"display-5 fw-bold\"> Hey????????, <?php echo $_SESSION['name'] ?> </h1> <h4 class=\"fw-bold\"> Your Username - <?php echo $_SESSION['loggedinUser'] ?> </h4> <h4 class=\"fw-bold\"> Password - <?php echo $_SESSION['userPass'] ?> </h4> <p class=\"fs-4\"> Use these crediantials when you login again save them for future reference </p> <p class=\"fs-5 text-info\"> Reload the page to Load new messages </p> <p class=\"fs-6\"> Share this URL with your friends so that they can send you messages </p> <!-- Creating a Link for other so that others send messages to this user through this Link using base 64 encoding to encode username of user in Link --> <p class=\"fs-6 text-success\"> Link - <?php echo $_SERVER['HTTP_HOST'] . \"/anonymousprank/anonymous.php?abcNum=\" . base64_encode($user_name) ?> </p> </div> </div> </div> <h4 class=\"fw-bold container\">Messages</h4> <div class=\"container cont\"> <div class=\"row\"> <?php // Fetching all the messages from the // messages table for this particular // user only $__username=$_SESSION['loggedinUser']; $_sql=\"SELECT `an_id` FROM `an_users` WHERE `an_username`='$__username'\"; $_result = mysqli_query($conn, $_sql); $_row = mysqli_fetch_assoc($_result); $an_u_id=$_row['an_id']; $sql = \"SELECT `msg_text`,`timestamp` FROM `an_messages` WHERE `an_id`='$an_u_id'\"; $result = mysqli_query($conn, $sql); // displaying messages on the page while($row = mysqli_fetch_assoc($result)){ echo ' <div class=\"card mx-3 my-2\" style=\"width: 18rem;border-radius:21px; border: solid aqua 6px;\"> <div class=\"card-body\"> <p class=\"card-text\">'.$row['msg_text'].'</p> <p class=\"card-text\" style=\"float:right\"> '.$row['timestamp'].' </p> </div> </div>'; } ?> </div> </div></div><?php include \"partials/footer.php\" ?>", "e": 43403, "s": 40102, "text": null }, { "code": null, "e": 43573, "s": 43403, "text": "We are creating this file for URL which we provided to our sign up users so that they share that URL with their friends and directing friends to this file using that URL" }, { "code": null, "e": 43587, "s": 43573, "text": "anonymous.php" }, { "code": null, "e": 43591, "s": 43587, "text": "PHP" }, { "code": "<?phpinclude \"partials/dbConnect.php\";include \"partials/header.php\"; if (isset($_GET['abcNum'])) { // Decoding username of signup // user passed inside the url $_username = base64_decode($_GET['abcNum']);} ?><?php include \"partials/navbar.php\" ?> <div class=\"content\"> <div class=\"container\"> <div class=\"p-5 mb-4 bg-light rounded-3 my-3\"> <div class=\"container-fluid py-5 text-center\"> <h1 class=\"display-5 fw-bold\"> Hey ????, Anonymous Send a Secret message to <?php // Fetching the name of the user from database $sql = \"SELECT `an_name`,an_id FROM `an_users` WHERE `an_username`='$_username'\"; $result = mysqli_query($conn, $sql); $record = mysqli_num_rows($result); // If find then showing page otherwise // redirecting to main page if ($record>0) { $row = mysqli_fetch_assoc($result); echo $row['an_name']; }else { header(\"location:index.php\"); } ?> </h1> <h3 id=\"log\" class=\"my-4 text-success\"></h3> <div class=\"mb-3\"> <!-- form to send messages to the sign up user --> <form method=\"POST\" id=\"sendForm\"> <textarea class=\"form-control\" id=\"message\" rows=\"3\" name=\"message\" required> </textarea> <input type=\"hidden\" value= <?php echo $row['an_id']?> name=\"mycode\" id=\"mycode\"> <button type=\"submit\" class=\"btn btn-primary my-4 btn-lg\" name=\"sendBtn\" id=\"sendBtn\"> Send </button> </form> </div> </div> </div> </div></div> <!-- including jquery -- > <script src=\"https://code.jquery.com/jquery-3.6.0.min.js\" integrity=\"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=\" crossorigin=\"anonymous\"></script> <?php include \"partials/footer.php\" ?> <script> // jQuery $(document).ready(function() { /* Targeting form to send a message using ajax and pass data in the form of object and getting response*/ $(\"#sendForm\").submit(function(e){ e.preventDefault(); let mycode = $(\"#mycode\").val(); let message = $(\"#message\").val(); $.post(\"partials/action.php\", { sendBtn:true, mycode2: mycode, message2: message }, (data)=>{ $(\"#log\").html(data) setTimeout(() => { $(\"#log\").html(\"\") }, 2000); $(\"#message\").val(\"\") }); });}); </script>", "e": 46804, "s": 43591, "text": null }, { "code": null, "e": 46845, "s": 46804, "text": "To logout users and destroying sessions." }, { "code": null, "e": 46849, "s": 46845, "text": "PHP" }, { "code": "<?phpsession_start();session_destroy();session_unset(); header(\"location:index.php\")?>", "e": 46936, "s": 46849, "text": null }, { "code": null, "e": 46964, "s": 46936, "text": "Database: Start XAMP Server" }, { "code": null, "e": 46999, "s": 46964, "text": "Xamp Server Strat apache and mySQL" }, { "code": null, "e": 47050, "s": 46999, "text": "Go to browser and type 127.0.0.1 in the addressbar" }, { "code": null, "e": 47117, "s": 47050, "text": "Go to phpmyadmin and create a new database named as “anonymousdb” " }, { "code": null, "e": 47171, "s": 47117, "text": "Make tables according to this below structures shown " }, { "code": null, "e": 47243, "s": 47171, "text": "To make a column unique click on “more” near “drop” and select “unique”" }, { "code": null, "e": 47252, "s": 47243, "text": "an_users" }, { "code": null, "e": 47264, "s": 47252, "text": "an_messages" }, { "code": null, "e": 47281, "s": 47264, "text": "arorakashish0911" }, { "code": null, "e": 47295, "s": 47281, "text": "avtarkumar719" }, { "code": null, "e": 47308, "s": 47295, "text": "ProGeek 2021" }, { "code": null, "e": 47322, "s": 47308, "text": "Project-Ideas" }, { "code": null, "e": 47326, "s": 47322, "text": "PHP" }, { "code": null, "e": 47334, "s": 47326, "text": "ProGeek" }, { "code": null, "e": 47342, "s": 47334, "text": "Project" }, { "code": null, "e": 47359, "s": 47342, "text": "Web Technologies" }, { "code": null, "e": 47363, "s": 47359, "text": "PHP" }, { "code": null, "e": 47461, "s": 47363, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47543, "s": 47461, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 47585, "s": 47543, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 47612, "s": 47585, "text": "PHP str_replace() Function" }, { "code": null, "e": 47676, "s": 47612, "text": "How to pass form variables from one page to other page in PHP ?" }, { "code": null, "e": 47727, "s": 47676, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 47759, "s": 47727, "text": "E-commerce Website using Django" }, { "code": null, "e": 47815, "s": 47759, "text": "College Management System using Django - Python Project" }, { "code": null, "e": 47884, "s": 47815, "text": "How to Build a Simple Note Android App using MVVM and Room Database?" }, { "code": null, "e": 47935, "s": 47884, "text": "Handwritten Digit Recognition using Neural Network" } ]
TimePicker in Kotlin - GeeksforGeeks
19 Feb, 2021 Android TimePicker is a user interface control for selecting the time in either 24-hour format or AM/PM mode. It is used to ensure that users pick the valid time for the day in our application. In android, TimePicker is available in two modes first one is clock mode and another one is spinner mode. We can use TimePicker manually in XML layout or we can create it programmatically in Kotlin file. In this article, we should use TimePicker widget in XML Layout. First we create a new project by following the below steps: Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish. Click on File, then New => New Project. After that include the Kotlin support and click on next. Select the minimum SDK as per convenience and click next button. Then select the Empty activity => next => finish. We can use android:timePickerMode to show only clock view. In the below example, we are using the TimePicker in clock mode. <TimePicker android:id="@+id/timePicker1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:timePickerMode="clock"/> The above code of TimePicker can be seen in android application like this We can also use the TimePicker in spinner format by using android:timePickerMode attribute. <TimePicker android:id="@+id/timePicker1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:timePickerMode="spinner"/> The above code of TimePicker can be seen in android application like this In this file, we will add the TimePicker and TextView widget and set their attributes so that it can be accessed in the kotlin file. <?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"> <TimePicker android:id="@+id/timePicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_margin="@dimen/padding" android:timePickerMode="clock"/> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/timePicker" android:textSize="18dp" android:paddingLeft="80dp" /> </RelativeLayout> In this file, we will add the TimePicker and TextView widget and set their attributes so that it can be accessed in the kotlin file. <?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"> <TimePicker android:id="@+id/timePicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_margin="@dimen/padding" android:timePickerMode="spinner"/> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/timePicker" android:textSize="18dp" android:paddingLeft="80dp" /> </RelativeLayout> Here, we will specify the name of the activity. <resources> <string name="app_name">TimePickerInKotlin</string></resources> First of all, we define a function OnClickTime() and called from MainActivity. private fun OnClickTime() then, we declare two variables textView and timePicker to access the widgets from the XML layout using their id’s. val textView = findViewById(R.id.textView) val timePicker = findViewById(R.id.timePicker) package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.ViewGroupimport android.widget.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) OnClickTime() } private fun OnClickTime() { val textView = findViewById<TextView>(R.id.textView) val timePicker = findViewById<TimePicker>(R.id.timePicker) timePicker.setOnTimeChangedListener { _, hour, minute -> var hour = hour var am_pm = "" // AM_PM decider logic when {hour == 0 -> { hour += 12 am_pm = "AM" } hour == 12 -> am_pm = "PM" hour > 12 -> { hour -= 12 am_pm = "PM" } else -> am_pm = "AM" } if (textView != null) { val hour = if (hour < 10) "0" + hour else hour val min = if (minute < 10) "0" + minute else minute // display format of time val msg = "Time is: $hour : $min $am_pm" textView.text = msg textView.visibility = ViewGroup.VISIBLE } } }} <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.geeksforgeeks.myfirstkotlinapp"> <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> Android-Date-time Kotlin Android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android Project folder Structure Broadcast Receiver in Android With Example Different Ways to Change the Project Name in Android Studio Fix “SDK tools directory is missing” Error in Android Studio How to Retrieve Data from the Firebase Realtime Database in Android? Android UI Layouts Broadcast Receiver in Android With Example Content Providers in Android with Example Kotlin Hashmap How to Change the Color of Status Bar in an Android App?
[ { "code": null, "e": 25283, "s": 25255, "text": "\n19 Feb, 2021" }, { "code": null, "e": 25477, "s": 25283, "text": "Android TimePicker is a user interface control for selecting the time in either 24-hour format or AM/PM mode. It is used to ensure that users pick the valid time for the day in our application." }, { "code": null, "e": 25583, "s": 25477, "text": "In android, TimePicker is available in two modes first one is clock mode and another one is spinner mode." }, { "code": null, "e": 25745, "s": 25583, "text": "We can use TimePicker manually in XML layout or we can create it programmatically in Kotlin file. In this article, we should use TimePicker widget in XML Layout." }, { "code": null, "e": 25805, "s": 25745, "text": "First we create a new project by following the below steps:" }, { "code": null, "e": 26014, "s": 25805, "text": "Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish." }, { "code": null, "e": 26054, "s": 26014, "text": "Click on File, then New => New Project." }, { "code": null, "e": 26111, "s": 26054, "text": "After that include the Kotlin support and click on next." }, { "code": null, "e": 26176, "s": 26111, "text": "Select the minimum SDK as per convenience and click next button." }, { "code": null, "e": 26226, "s": 26176, "text": "Then select the Empty activity => next => finish." }, { "code": null, "e": 26350, "s": 26226, "text": "We can use android:timePickerMode to show only clock view. In the below example, we are using the TimePicker in clock mode." }, { "code": "<TimePicker android:id=\"@+id/timePicker1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"20dp\" android:timePickerMode=\"clock\"/>", "e": 26611, "s": 26350, "text": null }, { "code": null, "e": 26685, "s": 26611, "text": "The above code of TimePicker can be seen in android application like this" }, { "code": null, "e": 26777, "s": 26685, "text": "We can also use the TimePicker in spinner format by using android:timePickerMode attribute." }, { "code": "<TimePicker android:id=\"@+id/timePicker1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"20dp\" android:timePickerMode=\"spinner\"/>", "e": 27040, "s": 26777, "text": null }, { "code": null, "e": 27114, "s": 27040, "text": "The above code of TimePicker can be seen in android application like this" }, { "code": null, "e": 27247, "s": 27114, "text": "In this file, we will add the TimePicker and TextView widget and set their attributes so that it can be accessed in the kotlin file." }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <TimePicker android:id=\"@+id/timePicker\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_margin=\"@dimen/padding\" android:timePickerMode=\"clock\"/> <TextView android:id=\"@+id/textView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignBottom=\"@+id/timePicker\" android:textSize=\"18dp\" android:paddingLeft=\"80dp\" /> </RelativeLayout>", "e": 27987, "s": 27247, "text": null }, { "code": null, "e": 28120, "s": 27987, "text": "In this file, we will add the TimePicker and TextView widget and set their attributes so that it can be accessed in the kotlin file." }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <TimePicker android:id=\"@+id/timePicker\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_margin=\"@dimen/padding\" android:timePickerMode=\"spinner\"/> <TextView android:id=\"@+id/textView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignBottom=\"@+id/timePicker\" android:textSize=\"18dp\" android:paddingLeft=\"80dp\" /> </RelativeLayout>", "e": 28862, "s": 28120, "text": null }, { "code": null, "e": 28910, "s": 28862, "text": "Here, we will specify the name of the activity." }, { "code": "<resources> <string name=\"app_name\">TimePickerInKotlin</string></resources>", "e": 28989, "s": 28910, "text": null }, { "code": null, "e": 29068, "s": 28989, "text": "First of all, we define a function OnClickTime() and called from MainActivity." }, { "code": null, "e": 29094, "s": 29068, "text": "private fun OnClickTime()" }, { "code": null, "e": 29209, "s": 29094, "text": "then, we declare two variables textView and timePicker to access the widgets from the XML layout using their id’s." }, { "code": null, "e": 29300, "s": 29209, "text": "val textView = findViewById(R.id.textView)\nval timePicker = findViewById(R.id.timePicker)\n" }, { "code": "package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.ViewGroupimport android.widget.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) OnClickTime() } private fun OnClickTime() { val textView = findViewById<TextView>(R.id.textView) val timePicker = findViewById<TimePicker>(R.id.timePicker) timePicker.setOnTimeChangedListener { _, hour, minute -> var hour = hour var am_pm = \"\" // AM_PM decider logic when {hour == 0 -> { hour += 12 am_pm = \"AM\" } hour == 12 -> am_pm = \"PM\" hour > 12 -> { hour -= 12 am_pm = \"PM\" } else -> am_pm = \"AM\" } if (textView != null) { val hour = if (hour < 10) \"0\" + hour else hour val min = if (minute < 10) \"0\" + minute else minute // display format of time val msg = \"Time is: $hour : $min $am_pm\" textView.text = msg textView.visibility = ViewGroup.VISIBLE } } }}", "e": 30627, "s": 29300, "text": null }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"package=\"com.geeksforgeeks.myfirstkotlinapp\"> <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>", "e": 31282, "s": 30627, "text": null }, { "code": null, "e": 31302, "s": 31284, "text": "Android-Date-time" }, { "code": null, "e": 31317, "s": 31302, "text": "Kotlin Android" }, { "code": null, "e": 31325, "s": 31317, "text": "Android" }, { "code": null, "e": 31332, "s": 31325, "text": "Kotlin" }, { "code": null, "e": 31340, "s": 31332, "text": "Android" }, { "code": null, "e": 31438, "s": 31340, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31471, "s": 31438, "text": "Android Project folder Structure" }, { "code": null, "e": 31514, "s": 31471, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 31574, "s": 31514, "text": "Different Ways to Change the Project Name in Android Studio" }, { "code": null, "e": 31635, "s": 31574, "text": "Fix “SDK tools directory is missing” Error in Android Studio" }, { "code": null, "e": 31704, "s": 31635, "text": "How to Retrieve Data from the Firebase Realtime Database in Android?" }, { "code": null, "e": 31723, "s": 31704, "text": "Android UI Layouts" }, { "code": null, "e": 31766, "s": 31723, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 31808, "s": 31766, "text": "Content Providers in Android with Example" }, { "code": null, "e": 31823, "s": 31808, "text": "Kotlin Hashmap" } ]
Flutter - Assigning Actions to Buttons - GeeksforGeeks
04 Jan, 2021 Flutter is Google’s UI toolkit for building beautiful, natively compiled applications for mobile, web, and desktop from a single codebase. Flutter provides a number of prebuilt widgets to use. There are different types of Button widgets that are provided by the Flutter SDK. In this article, we are going to see how we can add actions to them. Below are some button widgets that are shipped with Flutter SDK: TextButton ElevatedButton OutlinedButton IconButton FloatingActionButton Actions are assigned using onPressed() function. We are going to see two methods to assign Actions. Note: We are not going to use any other dependencies for this application. Using function reference. In this method, we are going to define a function somewhere else and then use that function’s reference as an action. This method is recommended because you can reuse the same function more than once. Dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksforGeeks', // to hide debug banner debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.green, ), home: ButtonsExample(), ); }} // list all the buttonsclass ButtonsExample extends StatelessWidget { final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey(); void textButtonHandler() { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Text/ Flat Button'), duration: Duration(seconds: 1), ), ); } void elevatedButtonHandler() { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Elevated/ Raised Button'), duration: Duration(seconds: 1), ), ); } void outlineButtonHandler() { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Outline/ Outlined Button'), duration: Duration(seconds: 1), ), ); } void iconButtonHandler() { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Icon Button'), duration: Duration(seconds: 1), ), ); } void floatingActionButtonHandler() { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Floating Action Button'), duration: Duration(seconds: 1), ), ); } // assign actions to // all the listed buttons @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( key: scaffoldKey, appBar: AppBar( title: Text('GeeksforGeeks'), ), body: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextButton( onPressed: textButtonHandler, child: Text('Text Button'), ), FlatButton( minWidth: MediaQuery.of(context).size.width, onPressed: textButtonHandler, child: Text('Flat Button'), ), ElevatedButton( onPressed: elevatedButtonHandler, child: Text('Elevated Button'), ), RaisedButton( onPressed: elevatedButtonHandler, child: Text('Raised Button'), ), OutlineButton( onPressed: outlineButtonHandler, child: Text('Outline Button'), ), OutlinedButton( onPressed: outlineButtonHandler, child: Text('Outlined Button'), ), IconButton( icon: Icon(Icons.star), onPressed: iconButtonHandler, ), FloatingActionButton.extended( onPressed: floatingActionButtonHandler, label: Text('Floating Action Button'), ), ], ), ), ), ); }} Output: If you need to pass some arguments to the functions then, use the following approach: onPressed: () => nameOfFunction(...args) -- OR -- onPressed: () { nameOfFunction(...args); } Define function directly where the Button widget is used, This method is not well suited for big apps because this makes the app less readable and cause problems during debugging and if the same function is used more than once then you have to repeat code which is also not very good practice. Dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksforGeeks', // to hide debug banner debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.green, ), home: ButtonsExample(), ); }} // list all the buttons & // assign actions to // all the listed buttonsclass ButtonsExample extends StatelessWidget { final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey(); @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( key: scaffoldKey, appBar: AppBar( title: Text('GeeksforGeeks'), ), body: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextButton( onPressed: () { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Text Button'), duration: Duration(seconds: 1), ), ); }, child: Text('Text Button'), ), FlatButton( minWidth: MediaQuery.of(context).size.width, onPressed: () { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Flat Button'), duration: Duration(seconds: 1), ), ); }, child: Text('Flat Button'), ), ElevatedButton( onPressed: () { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Elevated Button'), duration: Duration(seconds: 1), ), ); }, child: Text('Elevated Button'), ), RaisedButton( onPressed: () { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Raised Button'), duration: Duration(seconds: 1), ), ); }, child: Text('Raised Button'), ), OutlineButton( onPressed: () { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Outline Button'), duration: Duration(seconds: 1), ), ); }, child: Text('Outline Button'), ), OutlinedButton( onPressed: () { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Outlined Button'), duration: Duration(seconds: 1), ), ); }, child: Text('Outlined Button'), ), IconButton( icon: Icon(Icons.star), onPressed: () { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Icon Button'), duration: Duration(seconds: 1), ), ); }, ), FloatingActionButton.extended( onPressed: () { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Floating Action Button'), duration: Duration(seconds: 1), ), ); }, label: Text('Floating Action Button'), ), ], ), ), ), ); }} Output: Picked Technical Scripter 2020 Dart Flutter Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Flexible Widget Flutter - Stack Widget Android Studio Setup for Flutter Development Flutter - Custom Bottom Navigation Bar Flutter Tutorial Flutter - Flexible Widget Flutter - Stack Widget Flutter - Dialogs
[ { "code": null, "e": 25261, "s": 25233, "text": "\n04 Jan, 2021" }, { "code": null, "e": 25605, "s": 25261, "text": "Flutter is Google’s UI toolkit for building beautiful, natively compiled applications for mobile, web, and desktop from a single codebase. Flutter provides a number of prebuilt widgets to use. There are different types of Button widgets that are provided by the Flutter SDK. In this article, we are going to see how we can add actions to them." }, { "code": null, "e": 25670, "s": 25605, "text": "Below are some button widgets that are shipped with Flutter SDK:" }, { "code": null, "e": 25681, "s": 25670, "text": "TextButton" }, { "code": null, "e": 25696, "s": 25681, "text": "ElevatedButton" }, { "code": null, "e": 25711, "s": 25696, "text": "OutlinedButton" }, { "code": null, "e": 25722, "s": 25711, "text": "IconButton" }, { "code": null, "e": 25743, "s": 25722, "text": "FloatingActionButton" }, { "code": null, "e": 25843, "s": 25743, "text": "Actions are assigned using onPressed() function. We are going to see two methods to assign Actions." }, { "code": null, "e": 25918, "s": 25843, "text": "Note: We are not going to use any other dependencies for this application." }, { "code": null, "e": 26062, "s": 25918, "text": "Using function reference. In this method, we are going to define a function somewhere else and then use that function’s reference as an action." }, { "code": null, "e": 26145, "s": 26062, "text": "This method is recommended because you can reuse the same function more than once." }, { "code": null, "e": 26150, "s": 26145, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksforGeeks', // to hide debug banner debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.green, ), home: ButtonsExample(), ); }} // list all the buttonsclass ButtonsExample extends StatelessWidget { final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey(); void textButtonHandler() { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Text/ Flat Button'), duration: Duration(seconds: 1), ), ); } void elevatedButtonHandler() { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Elevated/ Raised Button'), duration: Duration(seconds: 1), ), ); } void outlineButtonHandler() { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Outline/ Outlined Button'), duration: Duration(seconds: 1), ), ); } void iconButtonHandler() { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Icon Button'), duration: Duration(seconds: 1), ), ); } void floatingActionButtonHandler() { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Floating Action Button'), duration: Duration(seconds: 1), ), ); } // assign actions to // all the listed buttons @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( key: scaffoldKey, appBar: AppBar( title: Text('GeeksforGeeks'), ), body: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextButton( onPressed: textButtonHandler, child: Text('Text Button'), ), FlatButton( minWidth: MediaQuery.of(context).size.width, onPressed: textButtonHandler, child: Text('Flat Button'), ), ElevatedButton( onPressed: elevatedButtonHandler, child: Text('Elevated Button'), ), RaisedButton( onPressed: elevatedButtonHandler, child: Text('Raised Button'), ), OutlineButton( onPressed: outlineButtonHandler, child: Text('Outline Button'), ), OutlinedButton( onPressed: outlineButtonHandler, child: Text('Outlined Button'), ), IconButton( icon: Icon(Icons.star), onPressed: iconButtonHandler, ), FloatingActionButton.extended( onPressed: floatingActionButtonHandler, label: Text('Floating Action Button'), ), ], ), ), ), ); }}", "e": 29298, "s": 26150, "text": null }, { "code": null, "e": 29306, "s": 29298, "text": "Output:" }, { "code": null, "e": 29392, "s": 29306, "text": "If you need to pass some arguments to the functions then, use the following approach:" }, { "code": null, "e": 29489, "s": 29392, "text": "onPressed: () => nameOfFunction(...args)\n\n-- OR --\n\nonPressed: () {\n nameOfFunction(...args);\n}" }, { "code": null, "e": 29783, "s": 29489, "text": "Define function directly where the Button widget is used, This method is not well suited for big apps because this makes the app less readable and cause problems during debugging and if the same function is used more than once then you have to repeat code which is also not very good practice." }, { "code": null, "e": 29788, "s": 29783, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'GeeksforGeeks', // to hide debug banner debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.green, ), home: ButtonsExample(), ); }} // list all the buttons & // assign actions to // all the listed buttonsclass ButtonsExample extends StatelessWidget { final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey(); @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( key: scaffoldKey, appBar: AppBar( title: Text('GeeksforGeeks'), ), body: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextButton( onPressed: () { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Text Button'), duration: Duration(seconds: 1), ), ); }, child: Text('Text Button'), ), FlatButton( minWidth: MediaQuery.of(context).size.width, onPressed: () { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Flat Button'), duration: Duration(seconds: 1), ), ); }, child: Text('Flat Button'), ), ElevatedButton( onPressed: () { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Elevated Button'), duration: Duration(seconds: 1), ), ); }, child: Text('Elevated Button'), ), RaisedButton( onPressed: () { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Raised Button'), duration: Duration(seconds: 1), ), ); }, child: Text('Raised Button'), ), OutlineButton( onPressed: () { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Outline Button'), duration: Duration(seconds: 1), ), ); }, child: Text('Outline Button'), ), OutlinedButton( onPressed: () { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Outlined Button'), duration: Duration(seconds: 1), ), ); }, child: Text('Outlined Button'), ), IconButton( icon: Icon(Icons.star), onPressed: () { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Icon Button'), duration: Duration(seconds: 1), ), ); }, ), FloatingActionButton.extended( onPressed: () { scaffoldKey.currentState.showSnackBar( SnackBar( content: Text('Floating Action Button'), duration: Duration(seconds: 1), ), ); }, label: Text('Floating Action Button'), ), ], ), ), ), ); }}", "e": 33858, "s": 29788, "text": null }, { "code": null, "e": 33866, "s": 33858, "text": "Output:" }, { "code": null, "e": 33873, "s": 33866, "text": "Picked" }, { "code": null, "e": 33897, "s": 33873, "text": "Technical Scripter 2020" }, { "code": null, "e": 33902, "s": 33897, "text": "Dart" }, { "code": null, "e": 33910, "s": 33902, "text": "Flutter" }, { "code": null, "e": 33929, "s": 33910, "text": "Technical Scripter" }, { "code": null, "e": 34027, "s": 33929, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34066, "s": 34027, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 34092, "s": 34066, "text": "ListView Class in Flutter" }, { "code": null, "e": 34118, "s": 34092, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 34141, "s": 34118, "text": "Flutter - Stack Widget" }, { "code": null, "e": 34186, "s": 34141, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 34225, "s": 34186, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 34242, "s": 34225, "text": "Flutter Tutorial" }, { "code": null, "e": 34268, "s": 34242, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 34291, "s": 34268, "text": "Flutter - Stack Widget" } ]
Tensorflow.js tf.data.Dataset.skip() Method - GeeksforGeeks
21 Jun, 2021 Tensorflow.js is an open-source library that is being developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment. The tf.data.Dataset.skip() method is used to create a dataset that skips count initial elements from this dataset. Syntax: skip(count) Parameters: This method has as single parameter as mentioned above and described below: count: It is a tensor input where the number of element of this dataset that should be skipped to form the new dataset. When the count is greater than the size of this dataset, the new dataset will contain no elements. When the count is undefined or negative, it skips the entire dataset. Return Value: It returns the tf.data.Dataset. The below examples demonstrate the tf.data.Dataset.skip() method: Example 1: Javascript // Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Defining input elementsconst a = tf.data.array([4, 5, 6, 7, 8, 9]).skip(3);await a.forEachAsync(e => console.log(e)); Output: 7 8 9 Example 2: Javascript // Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Defining input elementsconst a = tf.data.array([4, 5, 6, 7, 8, 9]).skip(4);await a.forEachAsync(e => console.log(e)); Output: 8 9 Reference: https://js.tensorflow.org/api/latest/#tf.data.Dataset.skip Picked Tensorflow.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n21 Jun, 2021" }, { "code": null, "e": 26732, "s": 26545, "text": "Tensorflow.js is an open-source library that is being developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment." }, { "code": null, "e": 26847, "s": 26732, "text": "The tf.data.Dataset.skip() method is used to create a dataset that skips count initial elements from this dataset." }, { "code": null, "e": 26855, "s": 26847, "text": "Syntax:" }, { "code": null, "e": 26867, "s": 26855, "text": "skip(count)" }, { "code": null, "e": 26955, "s": 26867, "text": "Parameters: This method has as single parameter as mentioned above and described below:" }, { "code": null, "e": 27244, "s": 26955, "text": "count: It is a tensor input where the number of element of this dataset that should be skipped to form the new dataset. When the count is greater than the size of this dataset, the new dataset will contain no elements. When the count is undefined or negative, it skips the entire dataset." }, { "code": null, "e": 27290, "s": 27244, "text": "Return Value: It returns the tf.data.Dataset." }, { "code": null, "e": 27356, "s": 27290, "text": "The below examples demonstrate the tf.data.Dataset.skip() method:" }, { "code": null, "e": 27367, "s": 27356, "text": "Example 1:" }, { "code": null, "e": 27378, "s": 27367, "text": "Javascript" }, { "code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Defining input elementsconst a = tf.data.array([4, 5, 6, 7, 8, 9]).skip(3);await a.forEachAsync(e => console.log(e));", "e": 27579, "s": 27378, "text": null }, { "code": null, "e": 27587, "s": 27579, "text": "Output:" }, { "code": null, "e": 27593, "s": 27587, "text": "7\n8\n9" }, { "code": null, "e": 27604, "s": 27593, "text": "Example 2:" }, { "code": null, "e": 27615, "s": 27604, "text": "Javascript" }, { "code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Defining input elementsconst a = tf.data.array([4, 5, 6, 7, 8, 9]).skip(4);await a.forEachAsync(e => console.log(e));", "e": 27816, "s": 27615, "text": null }, { "code": null, "e": 27824, "s": 27816, "text": "Output:" }, { "code": null, "e": 27828, "s": 27824, "text": "8\n9" }, { "code": null, "e": 27898, "s": 27828, "text": "Reference: https://js.tensorflow.org/api/latest/#tf.data.Dataset.skip" }, { "code": null, "e": 27905, "s": 27898, "text": "Picked" }, { "code": null, "e": 27919, "s": 27905, "text": "Tensorflow.js" }, { "code": null, "e": 27930, "s": 27919, "text": "JavaScript" }, { "code": null, "e": 27947, "s": 27930, "text": "Web Technologies" }, { "code": null, "e": 28045, "s": 27947, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28085, "s": 28045, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28146, "s": 28085, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28187, "s": 28146, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28209, "s": 28187, "text": "JavaScript | Promises" }, { "code": null, "e": 28263, "s": 28209, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28303, "s": 28263, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28336, "s": 28303, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28379, "s": 28336, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28441, "s": 28379, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
MongoDB | Delete Database using MongoShell - GeeksforGeeks
19 Nov, 2019 Prerequisite : MongoDB Introduction Short Description : A MongoDB Database is a container for all the collections, where Collection is a bunch of MongoDB documents similar to tables in RDBMS and Document is made of fields similar to a tuple in RDBMS, but it has a dynamic schema here.Example of a Document : { "Name" : "Aman", Age : 24, Gender : "Male" } Example of a Collection : [ { "Name" : "Aman", Age : 24, Gender : "Male" }, { "Name" : "Suraj", Age : 32, Gender : "Male" }, { "Name" : "Joyita", "Age" : 21, "Gender" : "Female" } ] MongoShell : The mongo shell is an interactive JavaScript interface to query and update data as well as perform administrative operations in MongoDB. Detailed explanation about the Mongo shell is given on this site. Drop a Database : In MongoDB, databases hold collections of documents. On a single MongoDB server, we can run multiple databases. when you install MongoDB some databases are automatically generated to use. many times you need to delete some database when the database is no longer used. db.dropDatabase() the command is used to drop an existing database. This command will delete the currently selected database. If you have not selected any database, then it will delete the default ‘test’ database. Syntax : db.dropDatabase() Example : The below screenshot is showing the use of “db.dropDatabase()” command for a newly created database name userDB. How to delete a database which is not currently used : You can check currently selected database, using the command “db“. Then you can use “show dbs” command for checking the list of Databases. Then select the database you want to delete using command “use databasename“. Then execute db.dropDatabase() command to drop an existing database. Example : In below example we were using a database name userDB and we want to delete a different database name adminDB. so first we are going to select adminDB database then we will delete this database. References:https://docs.mongodb.com/manual/core/databases-and-collections/#databases Akanksha_Rai shubham_singh MongoDB Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array 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 Differences between Functional Components and Class Components in React How to apply style to parent if it has child with CSS? How to execute PHP code using command line ? Difference Between PUT and PATCH Request REST API (Introduction) How to redirect to another page in ReactJS ?
[ { "code": null, "e": 26169, "s": 26141, "text": "\n19 Nov, 2019" }, { "code": null, "e": 26205, "s": 26169, "text": "Prerequisite : MongoDB Introduction" }, { "code": null, "e": 26477, "s": 26205, "text": "Short Description : A MongoDB Database is a container for all the collections, where Collection is a bunch of MongoDB documents similar to tables in RDBMS and Document is made of fields similar to a tuple in RDBMS, but it has a dynamic schema here.Example of a Document :" }, { "code": null, "e": 26553, "s": 26477, "text": "{\n \"Name\" : \"Aman\",\n Age : 24,\n Gender : \"Male\" \n}\n" }, { "code": null, "e": 26579, "s": 26553, "text": "Example of a Collection :" }, { "code": null, "e": 26844, "s": 26579, "text": "[ \n {\n \"Name\" : \"Aman\",\n Age : 24,\n Gender : \"Male\" \n },\n {\n \"Name\" : \"Suraj\",\n Age : 32,\n Gender : \"Male\" \n },\n {\n \"Name\" : \"Joyita\",\n \"Age\" : 21,\n \"Gender\" : \"Female\"\n }\n]\n" }, { "code": null, "e": 27060, "s": 26844, "text": "MongoShell : The mongo shell is an interactive JavaScript interface to query and update data as well as perform administrative operations in MongoDB. Detailed explanation about the Mongo shell is given on this site." }, { "code": null, "e": 27347, "s": 27060, "text": "Drop a Database : In MongoDB, databases hold collections of documents. On a single MongoDB server, we can run multiple databases. when you install MongoDB some databases are automatically generated to use. many times you need to delete some database when the database is no longer used." }, { "code": null, "e": 27561, "s": 27347, "text": "db.dropDatabase() the command is used to drop an existing database. This command will delete the currently selected database. If you have not selected any database, then it will delete the default ‘test’ database." }, { "code": null, "e": 27570, "s": 27561, "text": "Syntax :" }, { "code": null, "e": 27589, "s": 27570, "text": " db.dropDatabase()" }, { "code": null, "e": 27712, "s": 27589, "text": "Example : The below screenshot is showing the use of “db.dropDatabase()” command for a newly created database name userDB." }, { "code": null, "e": 28053, "s": 27712, "text": "How to delete a database which is not currently used : You can check currently selected database, using the command “db“. Then you can use “show dbs” command for checking the list of Databases. Then select the database you want to delete using command “use databasename“. Then execute db.dropDatabase() command to drop an existing database." }, { "code": null, "e": 28258, "s": 28053, "text": "Example : In below example we were using a database name userDB and we want to delete a different database name adminDB. so first we are going to select adminDB database then we will delete this database." }, { "code": null, "e": 28343, "s": 28258, "text": "References:https://docs.mongodb.com/manual/core/databases-and-collections/#databases" }, { "code": null, "e": 28356, "s": 28343, "text": "Akanksha_Rai" }, { "code": null, "e": 28370, "s": 28356, "text": "shubham_singh" }, { "code": null, "e": 28378, "s": 28370, "text": "MongoDB" }, { "code": null, "e": 28395, "s": 28378, "text": "Web Technologies" }, { "code": null, "e": 28493, "s": 28395, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28533, "s": 28493, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28578, "s": 28533, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28621, "s": 28578, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28682, "s": 28621, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28754, "s": 28682, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28809, "s": 28754, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 28854, "s": 28809, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 28895, "s": 28854, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28919, "s": 28895, "text": "REST API (Introduction)" } ]
How to Create a Relative Frequency Histogram in R? - GeeksforGeeks
04 Jan, 2022 In this article, we will discuss how to create a Relative Frequency Histogram in the R programming language. Relative Frequency Histogram helps us to visualize the relative frequencies of values in a dataset. This shows how often a certain value is present in the dataset. A relative frequency histogram gives an empirical approximation to the probability density function of data. To create a Relative Frequency Histogram in the R Language, we use the histogram() function of the lattice package library. The histogram() function takes the data vector as an argument and returns a relative frequency histogram. By default, the Histogram() function provides a color theme according to the current, active theme. Syntax: histogram( data, type ) Parameter: data: determines the data vector to be plotted. type: determines the type of relative frequency histogram that includes percent, count, and density. Example: Example of a basic relative frequency histogram with default configuration in the R Language. R # load library latticelibrary(lattice) # create sample data vectorsample_data <- rnorm(100) # create relative frequency histogramhistogram( sample_data ) Output: To change the color of the bars of the histogram, we use the col argument of the histogram() function. To change the label of the x-axis and y-axis, we use the xlab and ylab arguments respectively. To add a title to the plot we use the main argument of the histogram() function. Syntax: histogram( data, col, xlab, ylab, main ) Parameter: col: determines the color of bars/bins. xlab and ylab: determine the label of the x-axis and y-axis respectively. main: determines the title of plot. Example: Example of a customized relative frequency histogram with green colored bars and custom labels. R # load library latticelibrary(lattice) # create sample data vectorsample_data <- rnorm(100) # create relative frequency histogramhistogram( sample_data, col="green", main="Title of Plot", xlab="X-axis title", ylab="Y-axis title") Output: To customize the number of bins/bars in the relative frequency histogram, we can use the breaks argument of the histogram() function. The breaks argument takes a number of bins as value and breaks the plot into that many bars. By using the breaks argument, we can increase as well as decrease the number of bars based on the value. Syntax: histogram( data, breaks ) Parameter: data: determines the data vector to be plotted. breaks: determines the number of bars in the histogram. Example: Example of a relative frequency histogram with 20 bars customized using the breaks argument of the histogram() function. R # load library latticelibrary(lattice) # create sample data vectorsample_data <- rnorm(100) # create relative frequency histogramhistogram( sample_data, breaks=20) Output: Picked R-Charts R-Graphs R-plots 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 Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to import an Excel File into R ? Time Series Analysis in R R - if statement How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n04 Jan, 2022" }, { "code": null, "e": 26596, "s": 26487, "text": "In this article, we will discuss how to create a Relative Frequency Histogram in the R programming language." }, { "code": null, "e": 26869, "s": 26596, "text": "Relative Frequency Histogram helps us to visualize the relative frequencies of values in a dataset. This shows how often a certain value is present in the dataset. A relative frequency histogram gives an empirical approximation to the probability density function of data." }, { "code": null, "e": 27199, "s": 26869, "text": "To create a Relative Frequency Histogram in the R Language, we use the histogram() function of the lattice package library. The histogram() function takes the data vector as an argument and returns a relative frequency histogram. By default, the Histogram() function provides a color theme according to the current, active theme." }, { "code": null, "e": 27207, "s": 27199, "text": "Syntax:" }, { "code": null, "e": 27231, "s": 27207, "text": "histogram( data, type )" }, { "code": null, "e": 27242, "s": 27231, "text": "Parameter:" }, { "code": null, "e": 27290, "s": 27242, "text": "data: determines the data vector to be plotted." }, { "code": null, "e": 27391, "s": 27290, "text": "type: determines the type of relative frequency histogram that includes percent, count, and density." }, { "code": null, "e": 27494, "s": 27391, "text": "Example: Example of a basic relative frequency histogram with default configuration in the R Language." }, { "code": null, "e": 27496, "s": 27494, "text": "R" }, { "code": "# load library latticelibrary(lattice) # create sample data vectorsample_data <- rnorm(100) # create relative frequency histogramhistogram( sample_data )", "e": 27652, "s": 27496, "text": null }, { "code": null, "e": 27660, "s": 27652, "text": "Output:" }, { "code": null, "e": 27939, "s": 27660, "text": "To change the color of the bars of the histogram, we use the col argument of the histogram() function. To change the label of the x-axis and y-axis, we use the xlab and ylab arguments respectively. To add a title to the plot we use the main argument of the histogram() function." }, { "code": null, "e": 27947, "s": 27939, "text": "Syntax:" }, { "code": null, "e": 27988, "s": 27947, "text": "histogram( data, col, xlab, ylab, main )" }, { "code": null, "e": 27999, "s": 27988, "text": "Parameter:" }, { "code": null, "e": 28039, "s": 27999, "text": "col: determines the color of bars/bins." }, { "code": null, "e": 28113, "s": 28039, "text": "xlab and ylab: determine the label of the x-axis and y-axis respectively." }, { "code": null, "e": 28149, "s": 28113, "text": "main: determines the title of plot." }, { "code": null, "e": 28254, "s": 28149, "text": "Example: Example of a customized relative frequency histogram with green colored bars and custom labels." }, { "code": null, "e": 28256, "s": 28254, "text": "R" }, { "code": "# load library latticelibrary(lattice) # create sample data vectorsample_data <- rnorm(100) # create relative frequency histogramhistogram( sample_data, col=\"green\", main=\"Title of Plot\", xlab=\"X-axis title\", ylab=\"Y-axis title\")", "e": 28498, "s": 28256, "text": null }, { "code": null, "e": 28506, "s": 28498, "text": "Output:" }, { "code": null, "e": 28838, "s": 28506, "text": "To customize the number of bins/bars in the relative frequency histogram, we can use the breaks argument of the histogram() function. The breaks argument takes a number of bins as value and breaks the plot into that many bars. By using the breaks argument, we can increase as well as decrease the number of bars based on the value." }, { "code": null, "e": 28846, "s": 28838, "text": "Syntax:" }, { "code": null, "e": 28872, "s": 28846, "text": "histogram( data, breaks )" }, { "code": null, "e": 28883, "s": 28872, "text": "Parameter:" }, { "code": null, "e": 28931, "s": 28883, "text": "data: determines the data vector to be plotted." }, { "code": null, "e": 28987, "s": 28931, "text": "breaks: determines the number of bars in the histogram." }, { "code": null, "e": 29117, "s": 28987, "text": "Example: Example of a relative frequency histogram with 20 bars customized using the breaks argument of the histogram() function." }, { "code": null, "e": 29119, "s": 29117, "text": "R" }, { "code": "# load library latticelibrary(lattice) # create sample data vectorsample_data <- rnorm(100) # create relative frequency histogramhistogram( sample_data, breaks=20)", "e": 29285, "s": 29119, "text": null }, { "code": null, "e": 29293, "s": 29285, "text": "Output:" }, { "code": null, "e": 29300, "s": 29293, "text": "Picked" }, { "code": null, "e": 29309, "s": 29300, "text": "R-Charts" }, { "code": null, "e": 29318, "s": 29309, "text": "R-Graphs" }, { "code": null, "e": 29326, "s": 29318, "text": "R-plots" }, { "code": null, "e": 29337, "s": 29326, "text": "R Language" }, { "code": null, "e": 29435, "s": 29337, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29487, "s": 29435, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29522, "s": 29487, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29560, "s": 29522, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29618, "s": 29560, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29661, "s": 29618, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29710, "s": 29661, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29747, "s": 29710, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 29773, "s": 29747, "text": "Time Series Analysis in R" }, { "code": null, "e": 29790, "s": 29773, "text": "R - if statement" } ]
Selecting Rows with .loc. A beginner’s guide to selecting subsets... | by Ednalyn C. De Dios | Towards Data Science
As data scientists, we spent most of our time wrangling knee-deep in manipulating data using Pandas. In this post, we’ll be looking at the .loc property of Pandas to select rows based on some predefined conditions. Let’s open up a Jupyter notebook, and let’s get wrangling! We will be using the 311 Service Calls dataset1 from the City of San Antonio Open Data website to illustrate how the different .loc techniques work. Before we get started, let’s do a little housekeeping first. Nothing fancy going on here. We’re just importing the mandatory Pandas library and setting the display options so that when we inspect our dataframe, the columns and rows won’t be truncated by Jupyter. We’re setting it up so that every output within a single cell is displayed and not just the last one. In the code above, we’re defining a function that will show us the number of missing or null values and their percentage. Let’s load the data into a dataframe. Doing a quick df.head() we’ll see the first five rows of the data: And df.info() will let us see the dtypes of the columns. Then, show_missing(df) shows us if there are any missing values in the data. Let’s select rows where the 'Dept' column has null values and also filtering a dataframe where null values are excluded. First, we did a value count of the column ‘Dept’ column. The method .value_counts() returns a panda series listing all the values of the designated column and their frequency. By default, the method ignores NaN values and will not list it. However, if you include the parameter dropna=False it will include any NaN values in the result. Next, the line df_null = df.loc[df['Dept'].isnull()] tells the computer to select rows in df where the column 'Dept' is null. The resulting dataframe is assigned to df_null , and all its rows will NaN as values in the ‘Dept’ column. Similarly, the line df_notnull = df.loc[df['Dept'].notnull()] tells the computer to select rows in df where the column 'Dept' is not null. The resulting dataframe is assigned to df_notnull , and all its rows will not have any NaN as values in the ‘Dept’ column. The general syntax for these two techniques are: df_new = df_old.loc[df_old['Column Name'].isnull()]df_new = df_old.loc[df_old['Column Name'].notnull()] The 'Late (Yes/No)' column looks interesting. Let’s take a look at it! Again, we did a quick value count on the 'Late (Yes/No)' column. Then, we filtered for the cases that were late with df_late = df.loc[df['Late (Yes/No)'] == 'YES']. Similarly, we did the opposite by changing 'YES' to 'NO' and assign it to a different dataframe df_notlate. The syntax is not much different from the previous example except the addition of == sign between the column and the value we want to compare. It basically asks, for every row, if the value on a particular column (left side) matches the value that we specified (right-side). If the match is True, it includes that row in the result. If the match is False, it ignores it. Here’s the resulting dataframe for df_late: And here’s the one for df_notlate: The general syntax for this technique is: df_new = df_old.loc[df_old['Column Name'] == 'some_value' ] We’ve learned how to select rows based on ‘yes’ and ‘no.’ But what if the values are not binary? For example, let’s look at the ‘Category’ column: One hundred ninety-two thousand one hundred ninety-seven rows or records do not have a category assigned, but instead of NaN, empty, or null value, we get 'No Category' as the category itself. What if we want to filter these out? Enter: the != operator. As usual, we did customary value counts on the 'Category' column to see what we’re working with. Then, we created the df_categorized dataframe to include any records in the the df dataframe that don’t have 'No Category' as their value in the 'Category' column. Here’s the result of doing a value count on the 'Category' column of the df_categorized dataframe: As the screenshot above shows, the value counts retained everything but the ‘No Category.’ The general syntax for this technique is: df_new = df_old.loc[df_old['Column Name'] != 'some_value' ] Let’s consider the following columns, 'Late (Yes/No)' and 'CaseStatus': What if we wanted to know which open cases right now are already passed their SLA (service level agreement)? We would need to use multiple conditions to filter the cases or rows in a new dataframe. Enter the & operator. The syntax is similar to the previous ones except for the introduction of the & operator in between parenthesis. In the line df_late_open = df.loc[(df[‘Late (Yes/No)’] == ‘YES’) & (df[‘CaseStatus’] == ‘Open’)], there are two conditions: (df[‘Late (Yes/No)’] == ‘YES’)(df[‘CaseStatus’] == ‘Open’) (df[‘Late (Yes/No)’] == ‘YES’) (df[‘CaseStatus’] == ‘Open’) We want both of these to be true to match a row, so we included the operator & in between them. In plain speak, the & bitwise operator simply means AND. Other bitwise operators include pipe| sign for OR and the tilde ~ for NOT. I encourage you to experiment using these bitwise operators to get a good feel of what all they can do. Just remember to enclose each condition between parenthesis so that you don’t confuse Python. The general syntax for this technique is: df_new = df_old.loc[(df_old['Column Name 1'] == 'some_value_1') & (df['Column Name 2'] == 'some_value_2')] Let’s look at the value count for the 'Council District' column: What if we wanted to focus on districts #2, #3, #4, and #5 because they’re in south San Antonio, and they’re known for getting poor service from the city? (I’m so totally making this up by the way!) In this case, we could use the .isin() method like so: Remember to pass your choices inside the .isin() method as a list like ['choice1', 'choice2', 'choice3'] because otherwise, it will cause an error. For integers like in our example, it is not necessary to include quotation marks because quotation marks are for string values only. Here’s the result of our new dataframe df_south: The general syntax for this technique is: df_new = df_old.loc[df_old[Column Name'].isin(['choice1', 'choice2', 'choice3'])] And that’s it! In this post, we loaded the 311 service calls data into a dataframe and created subsets of data using the .loc method. Thanks for reading! I hope you enjoyed today’s post. Data wrangling, at least for me, is a fun exercise because this is the phase where I first get to know the data and it gives me a chance to hone my problem-solving skills when faced with really messy data. Happy wrangling folks! Stay tuned! You can reach me on Twitter or LinkedIn. [1] City of San Antonio Open Data. (May 31, 2020). 311 Service Calls. https://data.sanantonio.gov/dataset/service-calls
[ { "code": null, "e": 386, "s": 171, "text": "As data scientists, we spent most of our time wrangling knee-deep in manipulating data using Pandas. In this post, we’ll be looking at the .loc property of Pandas to select rows based on some predefined conditions." }, { "code": null, "e": 445, "s": 386, "text": "Let’s open up a Jupyter notebook, and let’s get wrangling!" }, { "code": null, "e": 594, "s": 445, "text": "We will be using the 311 Service Calls dataset1 from the City of San Antonio Open Data website to illustrate how the different .loc techniques work." }, { "code": null, "e": 655, "s": 594, "text": "Before we get started, let’s do a little housekeeping first." }, { "code": null, "e": 959, "s": 655, "text": "Nothing fancy going on here. We’re just importing the mandatory Pandas library and setting the display options so that when we inspect our dataframe, the columns and rows won’t be truncated by Jupyter. We’re setting it up so that every output within a single cell is displayed and not just the last one." }, { "code": null, "e": 1081, "s": 959, "text": "In the code above, we’re defining a function that will show us the number of missing or null values and their percentage." }, { "code": null, "e": 1119, "s": 1081, "text": "Let’s load the data into a dataframe." }, { "code": null, "e": 1186, "s": 1119, "text": "Doing a quick df.head() we’ll see the first five rows of the data:" }, { "code": null, "e": 1243, "s": 1186, "text": "And df.info() will let us see the dtypes of the columns." }, { "code": null, "e": 1320, "s": 1243, "text": "Then, show_missing(df) shows us if there are any missing values in the data." }, { "code": null, "e": 1441, "s": 1320, "text": "Let’s select rows where the 'Dept' column has null values and also filtering a dataframe where null values are excluded." }, { "code": null, "e": 1778, "s": 1441, "text": "First, we did a value count of the column ‘Dept’ column. The method .value_counts() returns a panda series listing all the values of the designated column and their frequency. By default, the method ignores NaN values and will not list it. However, if you include the parameter dropna=False it will include any NaN values in the result." }, { "code": null, "e": 2011, "s": 1778, "text": "Next, the line df_null = df.loc[df['Dept'].isnull()] tells the computer to select rows in df where the column 'Dept' is null. The resulting dataframe is assigned to df_null , and all its rows will NaN as values in the ‘Dept’ column." }, { "code": null, "e": 2273, "s": 2011, "text": "Similarly, the line df_notnull = df.loc[df['Dept'].notnull()] tells the computer to select rows in df where the column 'Dept' is not null. The resulting dataframe is assigned to df_notnull , and all its rows will not have any NaN as values in the ‘Dept’ column." }, { "code": null, "e": 2322, "s": 2273, "text": "The general syntax for these two techniques are:" }, { "code": null, "e": 2426, "s": 2322, "text": "df_new = df_old.loc[df_old['Column Name'].isnull()]df_new = df_old.loc[df_old['Column Name'].notnull()]" }, { "code": null, "e": 2497, "s": 2426, "text": "The 'Late (Yes/No)' column looks interesting. Let’s take a look at it!" }, { "code": null, "e": 2770, "s": 2497, "text": "Again, we did a quick value count on the 'Late (Yes/No)' column. Then, we filtered for the cases that were late with df_late = df.loc[df['Late (Yes/No)'] == 'YES']. Similarly, we did the opposite by changing 'YES' to 'NO' and assign it to a different dataframe df_notlate." }, { "code": null, "e": 3141, "s": 2770, "text": "The syntax is not much different from the previous example except the addition of == sign between the column and the value we want to compare. It basically asks, for every row, if the value on a particular column (left side) matches the value that we specified (right-side). If the match is True, it includes that row in the result. If the match is False, it ignores it." }, { "code": null, "e": 3185, "s": 3141, "text": "Here’s the resulting dataframe for df_late:" }, { "code": null, "e": 3220, "s": 3185, "text": "And here’s the one for df_notlate:" }, { "code": null, "e": 3262, "s": 3220, "text": "The general syntax for this technique is:" }, { "code": null, "e": 3322, "s": 3262, "text": "df_new = df_old.loc[df_old['Column Name'] == 'some_value' ]" }, { "code": null, "e": 3469, "s": 3322, "text": "We’ve learned how to select rows based on ‘yes’ and ‘no.’ But what if the values are not binary? For example, let’s look at the ‘Category’ column:" }, { "code": null, "e": 3723, "s": 3469, "text": "One hundred ninety-two thousand one hundred ninety-seven rows or records do not have a category assigned, but instead of NaN, empty, or null value, we get 'No Category' as the category itself. What if we want to filter these out? Enter: the != operator." }, { "code": null, "e": 3984, "s": 3723, "text": "As usual, we did customary value counts on the 'Category' column to see what we’re working with. Then, we created the df_categorized dataframe to include any records in the the df dataframe that don’t have 'No Category' as their value in the 'Category' column." }, { "code": null, "e": 4083, "s": 3984, "text": "Here’s the result of doing a value count on the 'Category' column of the df_categorized dataframe:" }, { "code": null, "e": 4174, "s": 4083, "text": "As the screenshot above shows, the value counts retained everything but the ‘No Category.’" }, { "code": null, "e": 4216, "s": 4174, "text": "The general syntax for this technique is:" }, { "code": null, "e": 4276, "s": 4216, "text": "df_new = df_old.loc[df_old['Column Name'] != 'some_value' ]" }, { "code": null, "e": 4348, "s": 4276, "text": "Let’s consider the following columns, 'Late (Yes/No)' and 'CaseStatus':" }, { "code": null, "e": 4568, "s": 4348, "text": "What if we wanted to know which open cases right now are already passed their SLA (service level agreement)? We would need to use multiple conditions to filter the cases or rows in a new dataframe. Enter the & operator." }, { "code": null, "e": 4805, "s": 4568, "text": "The syntax is similar to the previous ones except for the introduction of the & operator in between parenthesis. In the line df_late_open = df.loc[(df[‘Late (Yes/No)’] == ‘YES’) & (df[‘CaseStatus’] == ‘Open’)], there are two conditions:" }, { "code": null, "e": 4864, "s": 4805, "text": "(df[‘Late (Yes/No)’] == ‘YES’)(df[‘CaseStatus’] == ‘Open’)" }, { "code": null, "e": 4895, "s": 4864, "text": "(df[‘Late (Yes/No)’] == ‘YES’)" }, { "code": null, "e": 4924, "s": 4895, "text": "(df[‘CaseStatus’] == ‘Open’)" }, { "code": null, "e": 5350, "s": 4924, "text": "We want both of these to be true to match a row, so we included the operator & in between them. In plain speak, the & bitwise operator simply means AND. Other bitwise operators include pipe| sign for OR and the tilde ~ for NOT. I encourage you to experiment using these bitwise operators to get a good feel of what all they can do. Just remember to enclose each condition between parenthesis so that you don’t confuse Python." }, { "code": null, "e": 5392, "s": 5350, "text": "The general syntax for this technique is:" }, { "code": null, "e": 5499, "s": 5392, "text": "df_new = df_old.loc[(df_old['Column Name 1'] == 'some_value_1') & (df['Column Name 2'] == 'some_value_2')]" }, { "code": null, "e": 5564, "s": 5499, "text": "Let’s look at the value count for the 'Council District' column:" }, { "code": null, "e": 5818, "s": 5564, "text": "What if we wanted to focus on districts #2, #3, #4, and #5 because they’re in south San Antonio, and they’re known for getting poor service from the city? (I’m so totally making this up by the way!) In this case, we could use the .isin() method like so:" }, { "code": null, "e": 6099, "s": 5818, "text": "Remember to pass your choices inside the .isin() method as a list like ['choice1', 'choice2', 'choice3'] because otherwise, it will cause an error. For integers like in our example, it is not necessary to include quotation marks because quotation marks are for string values only." }, { "code": null, "e": 6148, "s": 6099, "text": "Here’s the result of our new dataframe df_south:" }, { "code": null, "e": 6190, "s": 6148, "text": "The general syntax for this technique is:" }, { "code": null, "e": 6272, "s": 6190, "text": "df_new = df_old.loc[df_old[Column Name'].isin(['choice1', 'choice2', 'choice3'])]" }, { "code": null, "e": 6406, "s": 6272, "text": "And that’s it! In this post, we loaded the 311 service calls data into a dataframe and created subsets of data using the .loc method." }, { "code": null, "e": 6688, "s": 6406, "text": "Thanks for reading! I hope you enjoyed today’s post. Data wrangling, at least for me, is a fun exercise because this is the phase where I first get to know the data and it gives me a chance to hone my problem-solving skills when faced with really messy data. Happy wrangling folks!" }, { "code": null, "e": 6700, "s": 6688, "text": "Stay tuned!" }, { "code": null, "e": 6741, "s": 6700, "text": "You can reach me on Twitter or LinkedIn." } ]
Better Data Visualization with Dual Axis Graphs in Python | by Byron Dolon | Towards Data Science
Visualizing data makes it easy for people to understand trends and make informed decisions. An important part of data visualization is picking the right chart to showcase your data. Furthermore, even specific charts like bar graphs and line graphs can be further customized to best explain the data you would like to showcase. In addition to cosmetic changes like color and font, you might also consider adding additional features like average trend lines, forecasts, or implement a dual-axis. In this piece, we’ll cover how you can use a dual-axis in a line chart to make correlations and trends across data points more evident to your audience. We’ll also take a quick look at what a regular chart without a dual-axis would look like, so you can decide which of the two would best suit your visualization needs. We will be using the Plotly library in Python for the data visualization, as well as Pandas for some initial data pre-processing, so make sure you have these two packages installed already. Then, import the following and get ready to follow along! import pandas as pdimport plotly.express as pximport plotly.graph_objects as gofrom plotly.subplots import make_subplotsimport random First, to generate some sample data, run the following code. expense_data = { "Person": random.choices(["A", "B"], k=20), "Amount": random.sample(range(100, 200), 10) + random.sample(range(0, 99), 10), "Category": ["Groceries"] * 10 + ["Restaurant"] * 10, "Date": pd.to_datetime(pd.date_range('2020-01-01','2020-10-01', freq='MS').tolist() * 2)}df = pd.DataFrame(data=expense_data) The data we’re going to visualize will be based on some randomly generated personal expense data. Above you can see we’re just randomly creating expense data for 10 months and loading it into a Pandas DataFrame. The above code should output 20 lines worth of data. Our goal for this analysis is to compare the “Groceries” and “Restaurant” spending categories over time. As such, let’s next group the data by the Date and Category fields using a few lines of Pandas. df_grouped = df.groupby(by=[pd.Grouper(key="Date", freq="1M"), "Category"])["Amount"]df_grouped = df_grouped.sum().reset_index() Finally, using just one line of Plotly Express, we can create a line chart with the grouped DataFrame as input. px.line(df_grouped, x="Date", y="Amount", color="Category") Plotly Express allows us to come up with the above chart with just one line, where we input our DataFrame, x-axis values, y-axis values, and optionally the color parameter so have multiple colored lines in the chart (one for each category). The chart looks pretty good, but as you can see it’s a bit difficult to compare the two categories. It intuitively makes sense, since you would expect that people, in general, spend more money on groceries than on restaurant trips every month. (Also, we hardcoded this logic into the code that generates this sample data- you can double-check it above.) Next, let’s take a look at implementing a dual-axis to make it easier to compare the two different categories of spending. First, we need to create an empty subplots figure using make_subplots (which we imported earlier). We’ll also define two variables to name our target categories. # making dual axis and defining categoriesfig = make_subplots(specs=[[{"secondary_y": True}]])category_1 = "Groceries"category_2 = "Restaurant" We’re not outputting anything yet, but it’s good to note that in the make_subplots method we’re passing "secondary_y": True inside specs to make sure we can properly implement the dual-axis later on. Next, we’ll manually create the first line in our line chart. # creating first plotfig.add_trace( go.Scatter( y=df_grouped.loc[df_grouped["Category"]==category_1, "Amount"], x=df_grouped.loc[df_grouped["Category"]==category_1, "Date"], name=category_1 ), secondary_y=False,) Before, using Plotly Express made it really easy for us to just pass one line of code to generate everything. Using the regular Plotly library means we’ll need to write a bit more code. Above, we’re using the add_trace method on the fig object we defined earlier to add the data from our previously grouped DataFrame. We also imported plotly.graph_objects as go earlier, so we can pass in the x and y column values. Finally, we set secondary_y to False, since this is just the first line in the chart. If you run fig.show(), you should see something like this: It’s a bit plain, but not bad so far! Right now, we just have the Groceries data. To add the second line with Restaurant data, we’ll run the following. # creating next plotfig.add_trace( go.Scatter( y=df_grouped.loc[df_grouped["Category"]==category_2, "Amount"], x=df_grouped.loc[df_grouped["Category"]==category_2, "Date"], name=category_2 ), secondary_y=True,) It’s almost the exact same code, except we use category_2 and pass in secondary_y=True instead. Then, if you run fig.show()again, you should see something like this: Looking even better! Unlike before, we can more easily see how the two categories of spending data behave over time relative to each other. This is just randomly generated data, but you can see in some months that when Groceries spending is high, Restaurant spending is comparatively lower (and vice versa). We can make this a bit more clear by writing a bit more code to add axis labels like so: fig.update_yaxes(title_text=category_1, secondary_y=False)fig.update_yaxes(title_text=category_2, secondary_y=True) We’re using the same update_yaxes methods here, but passing in first False then True to the secondary_y parameter to appropriately label both axes. This is pretty great so far, but I think we can clean things up a bit and move all the logic into a single function suitable for reuse. Here’s my implementation: def create_dual_axis_graph(input_df, *args): # making dual axis initial fig dual_axis_fig = make_subplots(specs=[[{"secondary_y": True}]]) # defining categories from kwargs categories = [*args] assert len(categories) == 2, f"Must only provide two categories. You provided {len(categories)}." # creating graph with loop for count, category in enumerate(categories): dual_axis_fig.add_trace( go.Scatter( y=input_df.loc[input_df["Category"]==category, "Amount"], x=input_df.loc[input_df["Category"]==category, "Date"], name=category ), secondary_y=count, ) dual_axis_fig.update_yaxes(title_text=category, secondary_y=count) return dual_axis_fig We’re doing the exact same things as before, except we’re removing a bit of the repetition that was helpful for demonstration purposes. The create_dual_axis_graph function takes an input_df as the main argument (where you would provide your already grouped DataFrame like we did before), then *args as the names of the two categories you’d like to examine. We put the *args in a list (and also check that the list only has two elements), then loop through that list and use the add_trace method again to add in the data for the x and y axes. We’ll also make use of enumerate in this looping process so either 0 or 1 (which are Boolean) can be passed into the secondary_y parameter of add_trace and update_yaxes, just like we did earlier. Running the function should just take one line like this: create_dual_axis_graph(df_grouped, "Groceries", "Restaurant").show() This will give you the exact same dual-axis graph as before. Just to show what an incorrect implementation would look like, you could try this out: create_dual_axis_graph(df_grouped, "Groceries", "Restaurant", "Appliances").show() We defined an AssertionError earlier to make sure that only two arguments were passed into the list of categories. You could also define a way more comprehensive data validation step, like checking if the DataFrame had the right columns, if the column values had the right data types, if the categories provided were actually in the DataFrame, and much more. For this demo, however, the above function will suffice. And that’s all, folks! I hope this quick (semi end-to-end) data analysis and visualization demonstration was helpful for you! I like the dual-axis graph because it makes it really easy to compare two categories that aren’t necessary on the same scale, and because Plotly Express didn’t have a native way to do so, I thought it would be great to share this implementation with everyone. Best of luck trying this out and using it on your own data! Thanks a bunch again for reading! If you’re thinking about becoming a paying member on Medium, I’d really appreciate it if you sign up using my referral link below! This would let me directly receive a portion of your membership fees, so it would be a big help. byrondolon.medium.com More by me:- Check for a Substring in a Pandas DataFrame- Conditional Selection and Assignment With .loc in Pandas- 2 Easy Ways to Get Tables From a Website With Pandas- 5 (and a half) Lines of Code for Understanding Your Data with Pandas- Top 4 Repositories on GitHub to Learn Pandas
[ { "code": null, "e": 499, "s": 172, "text": "Visualizing data makes it easy for people to understand trends and make informed decisions. An important part of data visualization is picking the right chart to showcase your data. Furthermore, even specific charts like bar graphs and line graphs can be further customized to best explain the data you would like to showcase." }, { "code": null, "e": 986, "s": 499, "text": "In addition to cosmetic changes like color and font, you might also consider adding additional features like average trend lines, forecasts, or implement a dual-axis. In this piece, we’ll cover how you can use a dual-axis in a line chart to make correlations and trends across data points more evident to your audience. We’ll also take a quick look at what a regular chart without a dual-axis would look like, so you can decide which of the two would best suit your visualization needs." }, { "code": null, "e": 1234, "s": 986, "text": "We will be using the Plotly library in Python for the data visualization, as well as Pandas for some initial data pre-processing, so make sure you have these two packages installed already. Then, import the following and get ready to follow along!" }, { "code": null, "e": 1368, "s": 1234, "text": "import pandas as pdimport plotly.express as pximport plotly.graph_objects as gofrom plotly.subplots import make_subplotsimport random" }, { "code": null, "e": 1429, "s": 1368, "text": "First, to generate some sample data, run the following code." }, { "code": null, "e": 1762, "s": 1429, "text": "expense_data = { \"Person\": random.choices([\"A\", \"B\"], k=20), \"Amount\": random.sample(range(100, 200), 10) + random.sample(range(0, 99), 10), \"Category\": [\"Groceries\"] * 10 + [\"Restaurant\"] * 10, \"Date\": pd.to_datetime(pd.date_range('2020-01-01','2020-10-01', freq='MS').tolist() * 2)}df = pd.DataFrame(data=expense_data)" }, { "code": null, "e": 2027, "s": 1762, "text": "The data we’re going to visualize will be based on some randomly generated personal expense data. Above you can see we’re just randomly creating expense data for 10 months and loading it into a Pandas DataFrame. The above code should output 20 lines worth of data." }, { "code": null, "e": 2228, "s": 2027, "text": "Our goal for this analysis is to compare the “Groceries” and “Restaurant” spending categories over time. As such, let’s next group the data by the Date and Category fields using a few lines of Pandas." }, { "code": null, "e": 2357, "s": 2228, "text": "df_grouped = df.groupby(by=[pd.Grouper(key=\"Date\", freq=\"1M\"), \"Category\"])[\"Amount\"]df_grouped = df_grouped.sum().reset_index()" }, { "code": null, "e": 2469, "s": 2357, "text": "Finally, using just one line of Plotly Express, we can create a line chart with the grouped DataFrame as input." }, { "code": null, "e": 2529, "s": 2469, "text": "px.line(df_grouped, x=\"Date\", y=\"Amount\", color=\"Category\")" }, { "code": null, "e": 2770, "s": 2529, "text": "Plotly Express allows us to come up with the above chart with just one line, where we input our DataFrame, x-axis values, y-axis values, and optionally the color parameter so have multiple colored lines in the chart (one for each category)." }, { "code": null, "e": 3124, "s": 2770, "text": "The chart looks pretty good, but as you can see it’s a bit difficult to compare the two categories. It intuitively makes sense, since you would expect that people, in general, spend more money on groceries than on restaurant trips every month. (Also, we hardcoded this logic into the code that generates this sample data- you can double-check it above.)" }, { "code": null, "e": 3247, "s": 3124, "text": "Next, let’s take a look at implementing a dual-axis to make it easier to compare the two different categories of spending." }, { "code": null, "e": 3409, "s": 3247, "text": "First, we need to create an empty subplots figure using make_subplots (which we imported earlier). We’ll also define two variables to name our target categories." }, { "code": null, "e": 3553, "s": 3409, "text": "# making dual axis and defining categoriesfig = make_subplots(specs=[[{\"secondary_y\": True}]])category_1 = \"Groceries\"category_2 = \"Restaurant\"" }, { "code": null, "e": 3753, "s": 3553, "text": "We’re not outputting anything yet, but it’s good to note that in the make_subplots method we’re passing \"secondary_y\": True inside specs to make sure we can properly implement the dual-axis later on." }, { "code": null, "e": 3815, "s": 3753, "text": "Next, we’ll manually create the first line in our line chart." }, { "code": null, "e": 4060, "s": 3815, "text": "# creating first plotfig.add_trace( go.Scatter( y=df_grouped.loc[df_grouped[\"Category\"]==category_1, \"Amount\"], x=df_grouped.loc[df_grouped[\"Category\"]==category_1, \"Date\"], name=category_1 ), secondary_y=False,)" }, { "code": null, "e": 4562, "s": 4060, "text": "Before, using Plotly Express made it really easy for us to just pass one line of code to generate everything. Using the regular Plotly library means we’ll need to write a bit more code. Above, we’re using the add_trace method on the fig object we defined earlier to add the data from our previously grouped DataFrame. We also imported plotly.graph_objects as go earlier, so we can pass in the x and y column values. Finally, we set secondary_y to False, since this is just the first line in the chart." }, { "code": null, "e": 4621, "s": 4562, "text": "If you run fig.show(), you should see something like this:" }, { "code": null, "e": 4773, "s": 4621, "text": "It’s a bit plain, but not bad so far! Right now, we just have the Groceries data. To add the second line with Restaurant data, we’ll run the following." }, { "code": null, "e": 5024, "s": 4773, "text": "# creating next plotfig.add_trace( go.Scatter( y=df_grouped.loc[df_grouped[\"Category\"]==category_2, \"Amount\"], x=df_grouped.loc[df_grouped[\"Category\"]==category_2, \"Date\"], name=category_2 ), secondary_y=True,)" }, { "code": null, "e": 5190, "s": 5024, "text": "It’s almost the exact same code, except we use category_2 and pass in secondary_y=True instead. Then, if you run fig.show()again, you should see something like this:" }, { "code": null, "e": 5498, "s": 5190, "text": "Looking even better! Unlike before, we can more easily see how the two categories of spending data behave over time relative to each other. This is just randomly generated data, but you can see in some months that when Groceries spending is high, Restaurant spending is comparatively lower (and vice versa)." }, { "code": null, "e": 5587, "s": 5498, "text": "We can make this a bit more clear by writing a bit more code to add axis labels like so:" }, { "code": null, "e": 5703, "s": 5587, "text": "fig.update_yaxes(title_text=category_1, secondary_y=False)fig.update_yaxes(title_text=category_2, secondary_y=True)" }, { "code": null, "e": 5851, "s": 5703, "text": "We’re using the same update_yaxes methods here, but passing in first False then True to the secondary_y parameter to appropriately label both axes." }, { "code": null, "e": 6013, "s": 5851, "text": "This is pretty great so far, but I think we can clean things up a bit and move all the logic into a single function suitable for reuse. Here’s my implementation:" }, { "code": null, "e": 6780, "s": 6013, "text": "def create_dual_axis_graph(input_df, *args): # making dual axis initial fig dual_axis_fig = make_subplots(specs=[[{\"secondary_y\": True}]]) # defining categories from kwargs categories = [*args] assert len(categories) == 2, f\"Must only provide two categories. You provided {len(categories)}.\" # creating graph with loop for count, category in enumerate(categories): dual_axis_fig.add_trace( go.Scatter( y=input_df.loc[input_df[\"Category\"]==category, \"Amount\"], x=input_df.loc[input_df[\"Category\"]==category, \"Date\"], name=category ), secondary_y=count, ) dual_axis_fig.update_yaxes(title_text=category, secondary_y=count) return dual_axis_fig" }, { "code": null, "e": 7137, "s": 6780, "text": "We’re doing the exact same things as before, except we’re removing a bit of the repetition that was helpful for demonstration purposes. The create_dual_axis_graph function takes an input_df as the main argument (where you would provide your already grouped DataFrame like we did before), then *args as the names of the two categories you’d like to examine." }, { "code": null, "e": 7518, "s": 7137, "text": "We put the *args in a list (and also check that the list only has two elements), then loop through that list and use the add_trace method again to add in the data for the x and y axes. We’ll also make use of enumerate in this looping process so either 0 or 1 (which are Boolean) can be passed into the secondary_y parameter of add_trace and update_yaxes, just like we did earlier." }, { "code": null, "e": 7576, "s": 7518, "text": "Running the function should just take one line like this:" }, { "code": null, "e": 7645, "s": 7576, "text": "create_dual_axis_graph(df_grouped, \"Groceries\", \"Restaurant\").show()" }, { "code": null, "e": 7793, "s": 7645, "text": "This will give you the exact same dual-axis graph as before. Just to show what an incorrect implementation would look like, you could try this out:" }, { "code": null, "e": 7876, "s": 7793, "text": "create_dual_axis_graph(df_grouped, \"Groceries\", \"Restaurant\", \"Appliances\").show()" }, { "code": null, "e": 8292, "s": 7876, "text": "We defined an AssertionError earlier to make sure that only two arguments were passed into the list of categories. You could also define a way more comprehensive data validation step, like checking if the DataFrame had the right columns, if the column values had the right data types, if the categories provided were actually in the DataFrame, and much more. For this demo, however, the above function will suffice." }, { "code": null, "e": 8315, "s": 8292, "text": "And that’s all, folks!" }, { "code": null, "e": 8678, "s": 8315, "text": "I hope this quick (semi end-to-end) data analysis and visualization demonstration was helpful for you! I like the dual-axis graph because it makes it really easy to compare two categories that aren’t necessary on the same scale, and because Plotly Express didn’t have a native way to do so, I thought it would be great to share this implementation with everyone." }, { "code": null, "e": 8738, "s": 8678, "text": "Best of luck trying this out and using it on your own data!" }, { "code": null, "e": 9000, "s": 8738, "text": "Thanks a bunch again for reading! If you’re thinking about becoming a paying member on Medium, I’d really appreciate it if you sign up using my referral link below! This would let me directly receive a portion of your membership fees, so it would be a big help." }, { "code": null, "e": 9022, "s": 9000, "text": "byrondolon.medium.com" } ]
How to remove a specific line or curve in Matplotlib?
To remove a specific line or curve in Matplotlib, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Plot line1 and line2 using plot() method. Pop the second line and remove it. To display the figure, use show() method. from matplotlib import pyplot as plt, image as mimg plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True line_1 = plt.plot([1, 2, 3]) line_2 = plt.plot([2, 4, 6]) line = line_2.pop(0) line.remove() plt.show()
[ { "code": null, "e": 1146, "s": 1062, "text": "To remove a specific line or curve in Matplotlib, we can take the following steps −" }, { "code": null, "e": 1222, "s": 1146, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1264, "s": 1222, "text": "Plot line1 and line2 using plot() method." }, { "code": null, "e": 1299, "s": 1264, "text": "Pop the second line and remove it." }, { "code": null, "e": 1341, "s": 1299, "text": "To display the figure, use show() method." }, { "code": null, "e": 1588, "s": 1341, "text": "from matplotlib import pyplot as plt, image as mimg\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nline_1 = plt.plot([1, 2, 3])\nline_2 = plt.plot([2, 4, 6])\n\nline = line_2.pop(0)\nline.remove()\n\nplt.show()" } ]
The Garoppolo Effect: Exploring NFL Data using Python Tutorial | by Kishan Panchal | Towards Data Science
Jimmy Garoppolo just signed the largest contract in NFL history with the San Francisco 49ers. He started 5 games for them after being traded midseason and led the 49ers to wins in all of those games. I wanted to explore how the 49ers team changed after Garoppolo was traded and understand a bit more about how he helped the team. For this analysis, I used a dataset about 2017 NFL plays. You can get the data using NFL scrapeR. I used this tool to download NFL play by play data for 2017 and have included a direct link to where the 2017 NFL data can be downloaded. For our purposes, we are just going to focus on analyzing the 49ers data for the 2017 season, and this is a walkthrough about how to do that using Python 2.7. I have included some comments within the code to help you follow along. Since Jimmy Garoppolo only started 5 games for the 49ers, these plots will not all have a similar number of observations, but let’s see what interesting things we can learn. import pandas as pd # data manipulation libraryimport numpy as np # numerical computation libraryimport datetime as dt import matplotlib.pyplot as plt # plotting libraryfrom matplotlib import cm # color maps for plottingplt.style.use('ggplot') # use the ggplot plotting style%matplotlib inline # show plots in line in a jupyter notebookfrom __future__ import division # division without truncating decimals Now, let’s read in our data into a variable called nfl. nfl = pd.read_csv('https://raw.githubusercontent.com/ryurko/nflscrapR-data/master/data/season_play_by_play/pbp_2017.csv', low_memory=False) Because we want to compare how the team performed before and after the trade, we can add an additional column that indicates that a date was before or after the date when Jimmy Garoppolo started a game for the 49ers. Doing this will allow us to compare the data before and after Jimmy was a starter since we can aggregate data based on the value of this column. First, we convert the date column to datetime format so that we can compare them with a date that we want to check against. nfl['Date'] = pd.to_datetime(nfl['Date']) Then we can create a column called Jimmy that is yes if the game date is on or after December 3rd, 2017 and is no otherwise. nfl['Jimmy'] = np.where( nfl['Date']>=pd.datetime(2017,12,3), 'yes', 'no') Now if we check our nfl dataframe, we will see that the last column is now Jimmy. We can obtain 49ers specific data from the 2017 NFL data by subsetting the NFL data such that the home or away team is the SF 49ers. niners = nfl[ (nfl["HomeTeam"] == 'SF') | (nfl["AwayTeam"] == 'SF') ] Next, we can look into touchdowns scored. To check touchdown information, we can check that the home or away team is SF, a scoring play occurred, a touchdown occurred, the team on offense was SF, and there was no interceptor, who is a player who intercepted the ball. niners_td = nfl[((nfl["HomeTeam"] == 'SF') | (nfl["AwayTeam"] == 'SF')) & (nfl["sp"] == 1) & (nfl["Touchdown"] == 1) & (nfl["DefensiveTeam"] != 'SF') & pd.isnull(nfl["Interceptor"]) ] And we get 31 touchdowns for the season. Now we can check how many touchdowns were scored without Jimmy and with him by grouping our dataframe. niners_td.groupby('Jimmy').Touchdown.sum() Now let’s graph the number of touchdowns scored while Jimmy started and did not start games. tds = niners_td.groupby('Jimmy').Touchdown.sum() # score the touchdown information in tdsfig, ax = plt.subplots(figsize=(8, 6), dpi = 72) # Get access to the figure and axes to modify their attributes laterax.set_title("Total Number of Touchdowns", fontsize = 18) # Chart titleax.set_xlabel('Jimmy', fontsize = 15) # X-axis labelax.set_ylabel('Number of Touchdowns', fontsize = 15) # Y-axis labelplt.xticks(fontsize = 13)plt.yticks(fontsize = 13)mycolors = ['#A6192E', '#85714D'] # Using scarlet and gold colorstds.plot(kind='bar', alpha = 0.9, rot=0, color = mycolors) # Plot a Bar chartplt.show() While this plot is nice, we should also check the number of touchdowns per game since Jimmy only played in 5 games. We can see that the 49ers scored approximately 1 more touchdown per game when Jimmy Garoppolo started. This does not mean that he was responsible for every touchdown scored when he played, but this just shows the number of touchdowns that were scored when he played. To get a different point of view about the touchdown situation, we can take a time-series approach where we take a look at the number of touchdowns and interceptions over time. We can mark off the point in time at which Garoppolo started games and see what changes we can observe. # get sum of touchdowns by game daytd_by_date = niners.groupby('Date')['Touchdown'].sum()td_by_date;# get sum of interceptions by game dayinter_by_date = niners.groupby('Date')['InterceptionThrown'].sum()inter_by_date; Now let’s graph it. fig, ax = plt.subplots(figsize=(8, 6), dpi = 80) # set plot size mycolors = ['#A6192E', '#85714D'] # Using scarlet and gold colorsf1 = td_by_date.plot(color = mycolors[0]) # plot the touchdownsf2 = inter_by_date.plot(color = mycolors[1]) # plot the interceptionsax.set_title("Touchdowns and Interceptions over Time", fontsize = 18) # Chart titleax.set_xlabel('Game Date', fontsize = 15) # X-axis labelax.set_ylabel('Count', fontsize = 15) # Y-axis labelplt.xticks(fontsize = 12)plt.yticks(fontsize = 12)plt.axvline(dt.datetime(2017, 12, 3), color = 'black') # add a vertical lineplt.legend(loc='upper center', frameon=True, facecolor="white") # add a legend with a white backgroundplt.show() The lines to the right of the black vertical line are games that Jimmy started. We notice that before he started for the 49ers, they were on a downward trend in terms of the number of touchdowns scored, and after he started, their offense started taking off again. We can also compare the different types of plays made when Garoppolo was not and was starting. This can give us an overall sense of how the prevalence of certain plays changed when he started vs when he did not since the types of plays ran can change with a different quarterback. To compare different playtypes, we use the niners dataframe and not the niners_td dataframe defined above because we are concerned with overall plays in the game and not just the plays that occur when the 49ers are on offense. fig, ax = plt.subplots(2, 1, figsize=(10, 8), dpi = 85) # specify a plot with 2 rows and 1 column# get plays where Jimmy did not start and did startf1 = niners[niners['Jimmy']=='no']['PlayType'].value_counts().plot(kind='barh', ax=ax[0]) f2 = niners[niners['Jimmy']=='yes']['PlayType'].value_counts().plot(kind='barh', ax=ax[1])f1.set(title = "Before Jimmy's Starts", xlabel='Count', ylabel='Play Type')f2.set(title = "After Jimmy's Starts", xlabel='Count', ylabel='Play Type')f1.set_xlim(0,805) # use the same scale for both plotsf2.set_xlim(0,805)fig.tight_layout() # prevent overlapping axis labelsplt.show() There are a different number of games and therefore count of plays, of course, but if we use the colors in both plots to match up which play was most frequent, we see that in both graphs, the most common plays were Pass, Run, and Kickoff, but then we notice that punts were more common before Jimmy started whereas field goals were more common after Jimmy started. This could indicate that Jimmy’s play could have helped the 49ers get closer to scoring position and the chance to score more field goals. Let’s take a look at the top plays in terms of yards gained when the 49ers were on offense. As before, we will subset our data to obtain data when the 49ers are on offense. niners_offense = nfl[((nfl["HomeTeam"] == 'SF') | (nfl["AwayTeam"] == 'SF')) & (nfl["DefensiveTeam"] != 'SF') ] We can create a new dataframe called most_yards that takes the 50 observations where the 49ers offense gained the most amount of yards. most_yards = niners_offense.sort_values(by='Yards.Gained', ascending=False)[:50] We can see that 20 of these 50 top plays by yards gained occurred when Jimmy started, but since the number of the occurrences differ, we will look at overall values instead of separating the plots as before since these different observations can lead to a varying number of bars in bar plots for instance. We notice that Marquise Goodwin was the receiver who was part of the plays resulting in the most yards gained last season. passes = most_yards[most_yards["PlayType"] == 'Pass']fig, ax = plt.subplots(figsize=(8, 6), dpi = 75)f1 = passes['Receiver'].value_counts().plot(kind='barh')f1.set(title = "Players with the most Yards after receiving Passes", xlabel='Count', ylabel='Player Name')plt.show() We can see that Matt Breida and Carlos Hyde were part of the most successful runs by yards gained last season. runs = most_yards[most_yards['PlayType'] == 'Run']fig, ax = plt.subplots(figsize=(6, 5), dpi = 75)f1 = runs['Rusher'].value_counts().plot(kind='barh')f1.set(title = "Players with the most Yards from Rushing", xlabel='Count', ylabel='Player Name')plt.show() I hope that you enjoyed this guide walking through some data analysis in Python using NFL data. Now you can go download the NFL data, play around with different information, and see what interesting things you find! Thank you for taking the time to read this post, and feel free to leave a comment or connect on LinkedIn. References: Pandas Data Frame DocumentationPandas Plot DocumentationMatplotlib DocumentationNFL ScrapeRPersonal Github Repository with this code notebook Pandas Data Frame Documentation Pandas Plot Documentation Matplotlib Documentation NFL ScrapeR Personal Github Repository with this code notebook
[ { "code": null, "e": 372, "s": 172, "text": "Jimmy Garoppolo just signed the largest contract in NFL history with the San Francisco 49ers. He started 5 games for them after being traded midseason and led the 49ers to wins in all of those games." }, { "code": null, "e": 738, "s": 372, "text": "I wanted to explore how the 49ers team changed after Garoppolo was traded and understand a bit more about how he helped the team. For this analysis, I used a dataset about 2017 NFL plays. You can get the data using NFL scrapeR. I used this tool to download NFL play by play data for 2017 and have included a direct link to where the 2017 NFL data can be downloaded." }, { "code": null, "e": 1143, "s": 738, "text": "For our purposes, we are just going to focus on analyzing the 49ers data for the 2017 season, and this is a walkthrough about how to do that using Python 2.7. I have included some comments within the code to help you follow along. Since Jimmy Garoppolo only started 5 games for the 49ers, these plots will not all have a similar number of observations, but let’s see what interesting things we can learn." }, { "code": null, "e": 1551, "s": 1143, "text": "import pandas as pd # data manipulation libraryimport numpy as np # numerical computation libraryimport datetime as dt import matplotlib.pyplot as plt # plotting libraryfrom matplotlib import cm # color maps for plottingplt.style.use('ggplot') # use the ggplot plotting style%matplotlib inline # show plots in line in a jupyter notebookfrom __future__ import division # division without truncating decimals " }, { "code": null, "e": 1607, "s": 1551, "text": "Now, let’s read in our data into a variable called nfl." }, { "code": null, "e": 1747, "s": 1607, "text": "nfl = pd.read_csv('https://raw.githubusercontent.com/ryurko/nflscrapR-data/master/data/season_play_by_play/pbp_2017.csv', low_memory=False)" }, { "code": null, "e": 2109, "s": 1747, "text": "Because we want to compare how the team performed before and after the trade, we can add an additional column that indicates that a date was before or after the date when Jimmy Garoppolo started a game for the 49ers. Doing this will allow us to compare the data before and after Jimmy was a starter since we can aggregate data based on the value of this column." }, { "code": null, "e": 2233, "s": 2109, "text": "First, we convert the date column to datetime format so that we can compare them with a date that we want to check against." }, { "code": null, "e": 2275, "s": 2233, "text": "nfl['Date'] = pd.to_datetime(nfl['Date'])" }, { "code": null, "e": 2400, "s": 2275, "text": "Then we can create a column called Jimmy that is yes if the game date is on or after December 3rd, 2017 and is no otherwise." }, { "code": null, "e": 2475, "s": 2400, "text": "nfl['Jimmy'] = np.where( nfl['Date']>=pd.datetime(2017,12,3), 'yes', 'no')" }, { "code": null, "e": 2557, "s": 2475, "text": "Now if we check our nfl dataframe, we will see that the last column is now Jimmy." }, { "code": null, "e": 2690, "s": 2557, "text": "We can obtain 49ers specific data from the 2017 NFL data by subsetting the NFL data such that the home or away team is the SF 49ers." }, { "code": null, "e": 2760, "s": 2690, "text": "niners = nfl[ (nfl[\"HomeTeam\"] == 'SF') | (nfl[\"AwayTeam\"] == 'SF') ]" }, { "code": null, "e": 3028, "s": 2760, "text": "Next, we can look into touchdowns scored. To check touchdown information, we can check that the home or away team is SF, a scoring play occurred, a touchdown occurred, the team on offense was SF, and there was no interceptor, who is a player who intercepted the ball." }, { "code": null, "e": 3212, "s": 3028, "text": "niners_td = nfl[((nfl[\"HomeTeam\"] == 'SF') | (nfl[\"AwayTeam\"] == 'SF')) & (nfl[\"sp\"] == 1) & (nfl[\"Touchdown\"] == 1) & (nfl[\"DefensiveTeam\"] != 'SF') & pd.isnull(nfl[\"Interceptor\"]) ]" }, { "code": null, "e": 3253, "s": 3212, "text": "And we get 31 touchdowns for the season." }, { "code": null, "e": 3356, "s": 3253, "text": "Now we can check how many touchdowns were scored without Jimmy and with him by grouping our dataframe." }, { "code": null, "e": 3399, "s": 3356, "text": "niners_td.groupby('Jimmy').Touchdown.sum()" }, { "code": null, "e": 3492, "s": 3399, "text": "Now let’s graph the number of touchdowns scored while Jimmy started and did not start games." }, { "code": null, "e": 4091, "s": 3492, "text": "tds = niners_td.groupby('Jimmy').Touchdown.sum() # score the touchdown information in tdsfig, ax = plt.subplots(figsize=(8, 6), dpi = 72) # Get access to the figure and axes to modify their attributes laterax.set_title(\"Total Number of Touchdowns\", fontsize = 18) # Chart titleax.set_xlabel('Jimmy', fontsize = 15) # X-axis labelax.set_ylabel('Number of Touchdowns', fontsize = 15) # Y-axis labelplt.xticks(fontsize = 13)plt.yticks(fontsize = 13)mycolors = ['#A6192E', '#85714D'] # Using scarlet and gold colorstds.plot(kind='bar', alpha = 0.9, rot=0, color = mycolors) # Plot a Bar chartplt.show()" }, { "code": null, "e": 4207, "s": 4091, "text": "While this plot is nice, we should also check the number of touchdowns per game since Jimmy only played in 5 games." }, { "code": null, "e": 4474, "s": 4207, "text": "We can see that the 49ers scored approximately 1 more touchdown per game when Jimmy Garoppolo started. This does not mean that he was responsible for every touchdown scored when he played, but this just shows the number of touchdowns that were scored when he played." }, { "code": null, "e": 4755, "s": 4474, "text": "To get a different point of view about the touchdown situation, we can take a time-series approach where we take a look at the number of touchdowns and interceptions over time. We can mark off the point in time at which Garoppolo started games and see what changes we can observe." }, { "code": null, "e": 4974, "s": 4755, "text": "# get sum of touchdowns by game daytd_by_date = niners.groupby('Date')['Touchdown'].sum()td_by_date;# get sum of interceptions by game dayinter_by_date = niners.groupby('Date')['InterceptionThrown'].sum()inter_by_date;" }, { "code": null, "e": 4994, "s": 4974, "text": "Now let’s graph it." }, { "code": null, "e": 5686, "s": 4994, "text": "fig, ax = plt.subplots(figsize=(8, 6), dpi = 80) # set plot size mycolors = ['#A6192E', '#85714D'] # Using scarlet and gold colorsf1 = td_by_date.plot(color = mycolors[0]) # plot the touchdownsf2 = inter_by_date.plot(color = mycolors[1]) # plot the interceptionsax.set_title(\"Touchdowns and Interceptions over Time\", fontsize = 18) # Chart titleax.set_xlabel('Game Date', fontsize = 15) # X-axis labelax.set_ylabel('Count', fontsize = 15) # Y-axis labelplt.xticks(fontsize = 12)plt.yticks(fontsize = 12)plt.axvline(dt.datetime(2017, 12, 3), color = 'black') # add a vertical lineplt.legend(loc='upper center', frameon=True, facecolor=\"white\") # add a legend with a white backgroundplt.show()" }, { "code": null, "e": 5951, "s": 5686, "text": "The lines to the right of the black vertical line are games that Jimmy started. We notice that before he started for the 49ers, they were on a downward trend in terms of the number of touchdowns scored, and after he started, their offense started taking off again." }, { "code": null, "e": 6459, "s": 5951, "text": "We can also compare the different types of plays made when Garoppolo was not and was starting. This can give us an overall sense of how the prevalence of certain plays changed when he started vs when he did not since the types of plays ran can change with a different quarterback. To compare different playtypes, we use the niners dataframe and not the niners_td dataframe defined above because we are concerned with overall plays in the game and not just the plays that occur when the 49ers are on offense." }, { "code": null, "e": 7071, "s": 6459, "text": "fig, ax = plt.subplots(2, 1, figsize=(10, 8), dpi = 85) # specify a plot with 2 rows and 1 column# get plays where Jimmy did not start and did startf1 = niners[niners['Jimmy']=='no']['PlayType'].value_counts().plot(kind='barh', ax=ax[0]) f2 = niners[niners['Jimmy']=='yes']['PlayType'].value_counts().plot(kind='barh', ax=ax[1])f1.set(title = \"Before Jimmy's Starts\", xlabel='Count', ylabel='Play Type')f2.set(title = \"After Jimmy's Starts\", xlabel='Count', ylabel='Play Type')f1.set_xlim(0,805) # use the same scale for both plotsf2.set_xlim(0,805)fig.tight_layout() # prevent overlapping axis labelsplt.show()" }, { "code": null, "e": 7575, "s": 7071, "text": "There are a different number of games and therefore count of plays, of course, but if we use the colors in both plots to match up which play was most frequent, we see that in both graphs, the most common plays were Pass, Run, and Kickoff, but then we notice that punts were more common before Jimmy started whereas field goals were more common after Jimmy started. This could indicate that Jimmy’s play could have helped the 49ers get closer to scoring position and the chance to score more field goals." }, { "code": null, "e": 7748, "s": 7575, "text": "Let’s take a look at the top plays in terms of yards gained when the 49ers were on offense. As before, we will subset our data to obtain data when the 49ers are on offense." }, { "code": null, "e": 7860, "s": 7748, "text": "niners_offense = nfl[((nfl[\"HomeTeam\"] == 'SF') | (nfl[\"AwayTeam\"] == 'SF')) & (nfl[\"DefensiveTeam\"] != 'SF') ]" }, { "code": null, "e": 7996, "s": 7860, "text": "We can create a new dataframe called most_yards that takes the 50 observations where the 49ers offense gained the most amount of yards." }, { "code": null, "e": 8077, "s": 7996, "text": "most_yards = niners_offense.sort_values(by='Yards.Gained', ascending=False)[:50]" }, { "code": null, "e": 8383, "s": 8077, "text": "We can see that 20 of these 50 top plays by yards gained occurred when Jimmy started, but since the number of the occurrences differ, we will look at overall values instead of separating the plots as before since these different observations can lead to a varying number of bars in bar plots for instance." }, { "code": null, "e": 8506, "s": 8383, "text": "We notice that Marquise Goodwin was the receiver who was part of the plays resulting in the most yards gained last season." }, { "code": null, "e": 8780, "s": 8506, "text": "passes = most_yards[most_yards[\"PlayType\"] == 'Pass']fig, ax = plt.subplots(figsize=(8, 6), dpi = 75)f1 = passes['Receiver'].value_counts().plot(kind='barh')f1.set(title = \"Players with the most Yards after receiving Passes\", xlabel='Count', ylabel='Player Name')plt.show()" }, { "code": null, "e": 8891, "s": 8780, "text": "We can see that Matt Breida and Carlos Hyde were part of the most successful runs by yards gained last season." }, { "code": null, "e": 9148, "s": 8891, "text": "runs = most_yards[most_yards['PlayType'] == 'Run']fig, ax = plt.subplots(figsize=(6, 5), dpi = 75)f1 = runs['Rusher'].value_counts().plot(kind='barh')f1.set(title = \"Players with the most Yards from Rushing\", xlabel='Count', ylabel='Player Name')plt.show()" }, { "code": null, "e": 9364, "s": 9148, "text": "I hope that you enjoyed this guide walking through some data analysis in Python using NFL data. Now you can go download the NFL data, play around with different information, and see what interesting things you find!" }, { "code": null, "e": 9470, "s": 9364, "text": "Thank you for taking the time to read this post, and feel free to leave a comment or connect on LinkedIn." }, { "code": null, "e": 9482, "s": 9470, "text": "References:" }, { "code": null, "e": 9624, "s": 9482, "text": "Pandas Data Frame DocumentationPandas Plot DocumentationMatplotlib DocumentationNFL ScrapeRPersonal Github Repository with this code notebook" }, { "code": null, "e": 9656, "s": 9624, "text": "Pandas Data Frame Documentation" }, { "code": null, "e": 9682, "s": 9656, "text": "Pandas Plot Documentation" }, { "code": null, "e": 9707, "s": 9682, "text": "Matplotlib Documentation" }, { "code": null, "e": 9719, "s": 9707, "text": "NFL ScrapeR" } ]
Find the Number of 1 Bits in a large Binary Number in C++
Given a 32-bit Unsigned Binary Number, the task is to count the set bits, i.e., '1's present in it. For Example Input: N = 00000000000000100111 Output: 4 Explanation: Total set bits present in the given unsigned number is 4, thus we will return the output as '4'. We have given an unsigned 32-bit binary number. The task is to count how many '1's present in it. To count the number of '1's present in the given binary number, we can use the inbuilt STL function '__builin_popcount(n)' which takes a binary number as the input parameter. Take a binary number N as the input. A function count1Bit(uint32_t n) takes a 32-bit binary number as the input and returns the count of '1' present in the binary number. The inbuilt function __builtin_popcount(n) takes the input of 'n' as a parameter and returns the count. Live Demo #include<bits/stdc++.h> using namespace std; int count1bits(uint32_t n) { return bitset < 32 > (n).count(); } int main() { uint32_t N = 0000000010100000011; cout << count1bits(N) << endl; return 0; } Running the above code will generate the output as, 4 In the given number, there are 4 set bits or '1s' present in it. So, the output is '4'.
[ { "code": null, "e": 1162, "s": 1062, "text": "Given a 32-bit Unsigned Binary Number, the task is to count the set bits, i.e., '1's present in it." }, { "code": null, "e": 1174, "s": 1162, "text": "For Example" }, { "code": null, "e": 1181, "s": 1174, "text": "Input:" }, { "code": null, "e": 1206, "s": 1181, "text": "N = 00000000000000100111" }, { "code": null, "e": 1214, "s": 1206, "text": "Output:" }, { "code": null, "e": 1216, "s": 1214, "text": "4" }, { "code": null, "e": 1326, "s": 1216, "text": "Explanation: Total set bits present in the given unsigned number is 4, thus we will return the output as '4'." }, { "code": null, "e": 1424, "s": 1326, "text": "We have given an unsigned 32-bit binary number. The task is to count how many '1's present in it." }, { "code": null, "e": 1599, "s": 1424, "text": "To count the number of '1's present in the given binary number, we can use the inbuilt STL function '__builin_popcount(n)' which takes a binary number as the input parameter." }, { "code": null, "e": 1636, "s": 1599, "text": "Take a binary number N as the input." }, { "code": null, "e": 1770, "s": 1636, "text": "A function count1Bit(uint32_t n) takes a 32-bit binary number as the input and returns the count of '1' present in the binary number." }, { "code": null, "e": 1874, "s": 1770, "text": "The inbuilt function __builtin_popcount(n) takes the input of 'n' as a parameter and returns the count." }, { "code": null, "e": 1884, "s": 1874, "text": "Live Demo" }, { "code": null, "e": 2096, "s": 1884, "text": "#include<bits/stdc++.h>\nusing namespace std;\nint count1bits(uint32_t n) {\n return bitset < 32 > (n).count();\n}\nint main() {\n uint32_t N = 0000000010100000011;\n cout << count1bits(N) << endl;\n return 0;\n}" }, { "code": null, "e": 2148, "s": 2096, "text": "Running the above code will generate the output as," }, { "code": null, "e": 2150, "s": 2148, "text": "4" }, { "code": null, "e": 2238, "s": 2150, "text": "In the given number, there are 4 set bits or '1s' present in it. So, the output is '4'." } ]
Barcodes and QR Codes Decoder in Python | by Ng Wai Foong | Towards Data Science
By reading this piece, you will learn about the tips and tricks to generate one-dimensional barcodes in different formats as well as Quick Response code (QR Code) generation. Besides, this tutorial will outline the methods to decode both the barcode and QR Code using the same Python library. Previously, I have covered a tutorial on How to Generate and Decode QR Codes in Python which used OpenCV to decode QR Codes. In this tutorial, I will be using another module called pyzbar for decoding instead. Based on the official documentation, pyzbar is “... a pure Python library that reads one-dimensional barcodes and QR codes using the zbar library, an open source software suite for reading bar codes from various sources, such as video streams, image files and raw intensity sensors. It supports many popular symbologies (types of bar codes) including EAN-13/UPC-A, UPC-E, EAN-8, Code 128, Code 39, Interleaved 2 of 5 and QR Code.” Based on the experiments that I have conducted, pyzbar performs better compared to python-opencv in terms of accuracy when decoding QR Codes. On top of that, pyzbar is able to decode barcodes as well. Let’s proceed to the next section and start installing the necessary modules. It is highly recommended to setup a virtual environment before you continue with the installation. You can easily install all the modules via pip install. Our first module is the python-barcode package which helps to generate one-dimensional barcodes based on the formats that we have specified. Run the following command to install it pip install python-barcode By default, result will be exported as SVG. You need to install additional dependencies such as Pillow. You can choose to install the dependencies independently or together with python-barcode as follows: pip install python-barcode[images] You can install qrcode package individually via the following command pip install qrcode Optionally, you can include the Pillow dependencies together with the standard installation as well pip install qrcode[pil] Installation for pyzbar is slightly complicated and depends on the operating system of your machine. For Windows user, zbar DLL comes together with the Windows Python wheels. For Mac OS X, you can install the zbar shared library via the following command brew install zbar The following command should be used if you are using Linux. sudo apt-get install libzbar0 Once you are done with it, run the following command to install pyzbar Python package. pip install pyzbar In fact, it also support command-line functionality which allows you to run it directly in command line. To do so, you should install it as follows: pip install pyzbar[scripts] In this section, we are going to generate barcodes using the python-barcode package. At the time of this writing, this package supports the following formats: EAN-8 EAN-13 EAN-14 UPC-A JAN ISBN-10 ISBN-13 ISSN Code 39 Code 128 PZN I am going to generate a new barcode using the EAN13 format. The result will be in PNG format. Let’s add the following import statement. ImageWriter is needed if you are saving the results as images. Otherwise, it will be defaulted to SVG. from barcode import EAN13from barcode.writer import ImageWriter Continue appending the following code below it. Since we are writing an image, you need to specify the filemode as wb. For your information, EAN13 accepts a string which contains 12 digits instead of 13. The last digit is a checksum and will be generated automatically. If your input is a 13 digits string, the last digit will be ignored. with open('barcode.png', 'wb') as f: EAN13('123456789102', writer=ImageWriter()).write(f) The complete code snippet is as follows: It should generate the following image when you run the Python file. Generation of QR Code is slightly complicated compared to barcode due to the fact that QR Code is 2-dimensional. Add the following import statement import qrcodefrom PIL import Image Create an instance of QRCode object with the following parameters qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=10, border=4,) version — Control the size of the QR Code. It accepts an integer from 1 to 40. Version 1 consists of 21 x 21 matrix. error_correction — Control the error correction used for the QR Code. box_size — Control the number of pixels of each boxes of the QR code. border — Control the boxes thickness of the border. The default is value is 4 which is also the minimum value according to the specification. There are 4 constants available for error_correction. The higher errors can be corrected, the better it is. ERROR_CORRECT_L — About 7% or less errors can be corrected. ERROR_CORRECT_M — About 15% or less errors can be corrected. This is the default value. ERROR_CORRECT_Q — About 25% or less errors can be corrected. ERROR_CORRECT_H — About 30% or less errors can be corrected. Continue appending the following code snippet below it. Replace the input parameter for add_data based on your own use cases. qr.add_data("https://medium.com/@ngwaifoong92")qr.make(fit=True)img = qr.make_image(fill_color="black", back_color="white")img.save("qrcode.png") You can find the complete code in the following gist. You should get a QR Code once you ran the code. In my case, it looks like this. Once you are done with it, proceed to the next section and start implementing our decoder. One main feature of pyzbar is that decoding is done directly using the same function. In addition, it supports decoding multiple barcodes or QR Codes in a single image. Import the decode() function from the module as follows: from pyzbar.pyzbar import decode You can pass either an instance of PIL.Image or an instance of numpy.ndarray. You can easily load an image into numpy.ndarry using OpenCV. For loading with PIL, use the following code from PIL import Imageimg = Image.open('qrcode.png') Here is an example of how you can load your image using OpenCV. import cv2img = cv2.imread('qrcode.png') Append the following code below it. It will print out the results as strings. result = decode(img) decode() function returns a list of namedtuple called Decoded. Each of them contains the following fields: data — The decoded string in bytes. You need to decode it using utf8 to get a string. type — Only useful for barcodes as it outlines the barcode format. rect — A Rect object which represents the captured localization area. polygon — A list of Point instances which represents the barcode or QR Code. If you were to print out the whole returned result, you should get the following output [Decoded(data=b'https://medium.com/@ngwaifoong92', type='QRCODE', rect=Rect(left=40, top=40, width=330, height=330), polygon=[Point(x=40, y=40), Point(x=40, y=369), Point(x=370, y=370), Point(x=369, y=40)])] Use the following code to loop over each of the element and print out the decoded string for i in result: print(i.data.decode("utf-8")) The complete code can be found at the following gist. Let’s recap what we have learned today. We started off with some explanations on the fundamental concepts behind python-barcode, qrcode and pyzbar. After that, we moved on to install the necessary modules. Installation is pretty straightforward with pip install. Once we are done with it, we implemented the generation of both barcodes and QR Codes with the configuration parameters of our choice. Finally, we utilized pyzbar module to decode the images that we have generated earlier. Thanks for reading this piece. Hope to see you again in the next article! python-barcode Githubqrcode Githubpyzbar Github
[ { "code": null, "e": 722, "s": 172, "text": "By reading this piece, you will learn about the tips and tricks to generate one-dimensional barcodes in different formats as well as Quick Response code (QR Code) generation. Besides, this tutorial will outline the methods to decode both the barcode and QR Code using the same Python library. Previously, I have covered a tutorial on How to Generate and Decode QR Codes in Python which used OpenCV to decode QR Codes. In this tutorial, I will be using another module called pyzbar for decoding instead. Based on the official documentation, pyzbar is" }, { "code": null, "e": 1106, "s": 722, "text": "“... a pure Python library that reads one-dimensional barcodes and QR codes using the zbar library, an open source software suite for reading bar codes from various sources, such as video streams, image files and raw intensity sensors. It supports many popular symbologies (types of bar codes) including EAN-13/UPC-A, UPC-E, EAN-8, Code 128, Code 39, Interleaved 2 of 5 and QR Code.”" }, { "code": null, "e": 1307, "s": 1106, "text": "Based on the experiments that I have conducted, pyzbar performs better compared to python-opencv in terms of accuracy when decoding QR Codes. On top of that, pyzbar is able to decode barcodes as well." }, { "code": null, "e": 1385, "s": 1307, "text": "Let’s proceed to the next section and start installing the necessary modules." }, { "code": null, "e": 1540, "s": 1385, "text": "It is highly recommended to setup a virtual environment before you continue with the installation. You can easily install all the modules via pip install." }, { "code": null, "e": 1721, "s": 1540, "text": "Our first module is the python-barcode package which helps to generate one-dimensional barcodes based on the formats that we have specified. Run the following command to install it" }, { "code": null, "e": 1748, "s": 1721, "text": "pip install python-barcode" }, { "code": null, "e": 1953, "s": 1748, "text": "By default, result will be exported as SVG. You need to install additional dependencies such as Pillow. You can choose to install the dependencies independently or together with python-barcode as follows:" }, { "code": null, "e": 1988, "s": 1953, "text": "pip install python-barcode[images]" }, { "code": null, "e": 2058, "s": 1988, "text": "You can install qrcode package individually via the following command" }, { "code": null, "e": 2077, "s": 2058, "text": "pip install qrcode" }, { "code": null, "e": 2177, "s": 2077, "text": "Optionally, you can include the Pillow dependencies together with the standard installation as well" }, { "code": null, "e": 2201, "s": 2177, "text": "pip install qrcode[pil]" }, { "code": null, "e": 2376, "s": 2201, "text": "Installation for pyzbar is slightly complicated and depends on the operating system of your machine. For Windows user, zbar DLL comes together with the Windows Python wheels." }, { "code": null, "e": 2456, "s": 2376, "text": "For Mac OS X, you can install the zbar shared library via the following command" }, { "code": null, "e": 2474, "s": 2456, "text": "brew install zbar" }, { "code": null, "e": 2535, "s": 2474, "text": "The following command should be used if you are using Linux." }, { "code": null, "e": 2565, "s": 2535, "text": "sudo apt-get install libzbar0" }, { "code": null, "e": 2652, "s": 2565, "text": "Once you are done with it, run the following command to install pyzbar Python package." }, { "code": null, "e": 2671, "s": 2652, "text": "pip install pyzbar" }, { "code": null, "e": 2820, "s": 2671, "text": "In fact, it also support command-line functionality which allows you to run it directly in command line. To do so, you should install it as follows:" }, { "code": null, "e": 2848, "s": 2820, "text": "pip install pyzbar[scripts]" }, { "code": null, "e": 2933, "s": 2848, "text": "In this section, we are going to generate barcodes using the python-barcode package." }, { "code": null, "e": 3007, "s": 2933, "text": "At the time of this writing, this package supports the following formats:" }, { "code": null, "e": 3013, "s": 3007, "text": "EAN-8" }, { "code": null, "e": 3020, "s": 3013, "text": "EAN-13" }, { "code": null, "e": 3027, "s": 3020, "text": "EAN-14" }, { "code": null, "e": 3033, "s": 3027, "text": "UPC-A" }, { "code": null, "e": 3037, "s": 3033, "text": "JAN" }, { "code": null, "e": 3045, "s": 3037, "text": "ISBN-10" }, { "code": null, "e": 3053, "s": 3045, "text": "ISBN-13" }, { "code": null, "e": 3058, "s": 3053, "text": "ISSN" }, { "code": null, "e": 3066, "s": 3058, "text": "Code 39" }, { "code": null, "e": 3075, "s": 3066, "text": "Code 128" }, { "code": null, "e": 3079, "s": 3075, "text": "PZN" }, { "code": null, "e": 3174, "s": 3079, "text": "I am going to generate a new barcode using the EAN13 format. The result will be in PNG format." }, { "code": null, "e": 3319, "s": 3174, "text": "Let’s add the following import statement. ImageWriter is needed if you are saving the results as images. Otherwise, it will be defaulted to SVG." }, { "code": null, "e": 3383, "s": 3319, "text": "from barcode import EAN13from barcode.writer import ImageWriter" }, { "code": null, "e": 3722, "s": 3383, "text": "Continue appending the following code below it. Since we are writing an image, you need to specify the filemode as wb. For your information, EAN13 accepts a string which contains 12 digits instead of 13. The last digit is a checksum and will be generated automatically. If your input is a 13 digits string, the last digit will be ignored." }, { "code": null, "e": 3815, "s": 3722, "text": "with open('barcode.png', 'wb') as f: EAN13('123456789102', writer=ImageWriter()).write(f)" }, { "code": null, "e": 3856, "s": 3815, "text": "The complete code snippet is as follows:" }, { "code": null, "e": 3925, "s": 3856, "text": "It should generate the following image when you run the Python file." }, { "code": null, "e": 4038, "s": 3925, "text": "Generation of QR Code is slightly complicated compared to barcode due to the fact that QR Code is 2-dimensional." }, { "code": null, "e": 4073, "s": 4038, "text": "Add the following import statement" }, { "code": null, "e": 4108, "s": 4073, "text": "import qrcodefrom PIL import Image" }, { "code": null, "e": 4174, "s": 4108, "text": "Create an instance of QRCode object with the following parameters" }, { "code": null, "e": 4292, "s": 4174, "text": "qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=10, border=4,)" }, { "code": null, "e": 4409, "s": 4292, "text": "version — Control the size of the QR Code. It accepts an integer from 1 to 40. Version 1 consists of 21 x 21 matrix." }, { "code": null, "e": 4479, "s": 4409, "text": "error_correction — Control the error correction used for the QR Code." }, { "code": null, "e": 4549, "s": 4479, "text": "box_size — Control the number of pixels of each boxes of the QR code." }, { "code": null, "e": 4691, "s": 4549, "text": "border — Control the boxes thickness of the border. The default is value is 4 which is also the minimum value according to the specification." }, { "code": null, "e": 4799, "s": 4691, "text": "There are 4 constants available for error_correction. The higher errors can be corrected, the better it is." }, { "code": null, "e": 4859, "s": 4799, "text": "ERROR_CORRECT_L — About 7% or less errors can be corrected." }, { "code": null, "e": 4947, "s": 4859, "text": "ERROR_CORRECT_M — About 15% or less errors can be corrected. This is the default value." }, { "code": null, "e": 5008, "s": 4947, "text": "ERROR_CORRECT_Q — About 25% or less errors can be corrected." }, { "code": null, "e": 5069, "s": 5008, "text": "ERROR_CORRECT_H — About 30% or less errors can be corrected." }, { "code": null, "e": 5195, "s": 5069, "text": "Continue appending the following code snippet below it. Replace the input parameter for add_data based on your own use cases." }, { "code": null, "e": 5341, "s": 5195, "text": "qr.add_data(\"https://medium.com/@ngwaifoong92\")qr.make(fit=True)img = qr.make_image(fill_color=\"black\", back_color=\"white\")img.save(\"qrcode.png\")" }, { "code": null, "e": 5395, "s": 5341, "text": "You can find the complete code in the following gist." }, { "code": null, "e": 5475, "s": 5395, "text": "You should get a QR Code once you ran the code. In my case, it looks like this." }, { "code": null, "e": 5566, "s": 5475, "text": "Once you are done with it, proceed to the next section and start implementing our decoder." }, { "code": null, "e": 5792, "s": 5566, "text": "One main feature of pyzbar is that decoding is done directly using the same function. In addition, it supports decoding multiple barcodes or QR Codes in a single image. Import the decode() function from the module as follows:" }, { "code": null, "e": 5825, "s": 5792, "text": "from pyzbar.pyzbar import decode" }, { "code": null, "e": 6009, "s": 5825, "text": "You can pass either an instance of PIL.Image or an instance of numpy.ndarray. You can easily load an image into numpy.ndarry using OpenCV. For loading with PIL, use the following code" }, { "code": null, "e": 6061, "s": 6009, "text": "from PIL import Imageimg = Image.open('qrcode.png')" }, { "code": null, "e": 6125, "s": 6061, "text": "Here is an example of how you can load your image using OpenCV." }, { "code": null, "e": 6166, "s": 6125, "text": "import cv2img = cv2.imread('qrcode.png')" }, { "code": null, "e": 6244, "s": 6166, "text": "Append the following code below it. It will print out the results as strings." }, { "code": null, "e": 6265, "s": 6244, "text": "result = decode(img)" }, { "code": null, "e": 6372, "s": 6265, "text": "decode() function returns a list of namedtuple called Decoded. Each of them contains the following fields:" }, { "code": null, "e": 6458, "s": 6372, "text": "data — The decoded string in bytes. You need to decode it using utf8 to get a string." }, { "code": null, "e": 6525, "s": 6458, "text": "type — Only useful for barcodes as it outlines the barcode format." }, { "code": null, "e": 6595, "s": 6525, "text": "rect — A Rect object which represents the captured localization area." }, { "code": null, "e": 6672, "s": 6595, "text": "polygon — A list of Point instances which represents the barcode or QR Code." }, { "code": null, "e": 6760, "s": 6672, "text": "If you were to print out the whole returned result, you should get the following output" }, { "code": null, "e": 6968, "s": 6760, "text": "[Decoded(data=b'https://medium.com/@ngwaifoong92', type='QRCODE', rect=Rect(left=40, top=40, width=330, height=330), polygon=[Point(x=40, y=40), Point(x=40, y=369), Point(x=370, y=370), Point(x=369, y=40)])]" }, { "code": null, "e": 7057, "s": 6968, "text": "Use the following code to loop over each of the element and print out the decoded string" }, { "code": null, "e": 7107, "s": 7057, "text": "for i in result: print(i.data.decode(\"utf-8\"))" }, { "code": null, "e": 7161, "s": 7107, "text": "The complete code can be found at the following gist." }, { "code": null, "e": 7201, "s": 7161, "text": "Let’s recap what we have learned today." }, { "code": null, "e": 7309, "s": 7201, "text": "We started off with some explanations on the fundamental concepts behind python-barcode, qrcode and pyzbar." }, { "code": null, "e": 7424, "s": 7309, "text": "After that, we moved on to install the necessary modules. Installation is pretty straightforward with pip install." }, { "code": null, "e": 7559, "s": 7424, "text": "Once we are done with it, we implemented the generation of both barcodes and QR Codes with the configuration parameters of our choice." }, { "code": null, "e": 7647, "s": 7559, "text": "Finally, we utilized pyzbar module to decode the images that we have generated earlier." }, { "code": null, "e": 7721, "s": 7647, "text": "Thanks for reading this piece. Hope to see you again in the next article!" } ]
All you need to know about Regular Expressions | by Ria Kulshrestha | Towards Data Science
Regular expressions are a generalized way to match patterns with sequences of characters. They define a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. “find and replace” like operations. Let’s say you have to search a corpus and return all the email addresses mentioned in it. A pretty straightforward task for a human as every email address can be generalized as a string of alphanumeric characters with some permissible special characters like . (dot), _(underscore), -(hyphen), followed by a ‘@{domainName}.com’. But how do you pass such a template to a computer? The fact that email addresses can be of variable length, don’t have a fixed location for numeric/special characters (could be in the beginning, the end, or anywhere in between), doesn’t make the task any easier for a computer. This is where regular expressions come to our rescue! By using them we can easily create a generalized template that a not only a computer will understand but will satisfy all of our restrictions. The term regular expression comes from mathematics and computer science theory, where it reflects a trait of mathematical expressions called regularity. The text patterns used by the earliest grep tools were regular expressions in the mathematical sense. Though the name has stuck, modern-day Perl-style regular expressions (which we still use with other programming languages) are not regular expressions at all in the mathematical sense. They are often called REs, or regexes, or regex patterns. #1: Most characters match with themselves. So if you have to write a regular expression for the word “wubbaLubbaDubDub”, the regex for it would be ‘wubbaLubbaDubDub’. Keep in mind that REs are case-sensitive. But there are some characters called meta-characters which don’t match to themselves rather signal that some out-of-the-ordinary thing should be matched, or they affect other portions of the RE by repeating them or changing their meaning. These meta-characters make regular expressions the powerful tool they are. #2: Repeaters *,+,{}. A lot of time you’ll face a scenario where you don't know how many times a character will be repeated or if it will be repeated at all. Repeaters allow us to tackle such cases. The asterisk (*): It implies that the preceding character is present 0 or more times. There is no upper bound on the number of occurrences of the preceding character. In ‘a*b’, ‘a’ precedes the *, which means ‘a’ can occur 0/0+ times. So it will match to ‘b’, ‘ab’, ‘aab’, ‘aaab’, ‘aa..(infinite a’s)..b’. The plus(+): It is the same as * but implies at least 1 occurrence of the previous character. ‘a+b’ will match to ‘ab’, ‘aab’, ‘aaab’, ‘aaa...aab’ but not just ‘b’. The curly braces {}: These are used to define a range of occurrences of the previous character. ‘a{3},b’: will match ‘aaab’ only. ‘a{min,}b’: restricting minimum occurrences of ‘a’, no upper limit restrictions. ‘a{3,}b’ will match ‘aaab’, ‘aaaab’, ‘aaa...aab’.‘a{min, max}b’: ‘a’ should occur at least min times and at most max times. ‘a{3,5}b’ will match ‘aaab’, ‘aaaab’, ‘aaaaab’. #3 The wildcard(.): Knowing the order of characters in a string is not always feasible. A wildcard comes in really handy in these situations.It implies that any character can take its place in the sequence. ‘.’ will match all strings with just one character.‘.*’ will match all possible strings of any length.‘a.b’ will match ‘aab’, ‘abb’, ‘acb’, ‘adb’, .... ‘a b’ [a(space)b], ‘a/b’ and so on. Basically, any sequence of length 3 starting with ‘a’ and ending with ‘b’. #4 The Optional character(?): Sometimes multiple variations of a word are possible. Like ‘color’ (American English) and ‘colour’ (British English) are different spellings of the same word and both are correct, the only difference being an extra ‘u’ in the British version. The ‘?’ implies that the previous character may or may not be present in the final string. In a way, ‘?’ implies a 0 or 1 occurrence. ‘colou?r’ will match both ‘color’ and ‘colour’.‘docx?’ will match both ‘doc’ and ‘docx’. #5 The Caret(^): It implies the first character of a string. ‘^a.*’ will match all strings starting with ‘a’.‘^a{2}.*’ will match all strings starting with ‘aa’. #6 The dollar($): It implies the last character of a string. ‘.*b$’ will match all strings ending with a ‘b’. #7 Character classes([]): More often than not, for a particular position in a string, there will be more than one possible character. To accommodate all the possible characters we use character classes. They specify a set of characters that you wish to match. Characters can be listed individually, or a range of characters can be indicated by giving two characters and separating them by a ‘-’. ‘[abc]’: will match ‘a’, ‘b’, or ‘c’. ‘[^abc]’:Negation will match any character except ‘a’, ‘b’, and ‘c’. Note -- Not to be confused with caret where ^ implies begins with. If inside a character class ^ implies negation.Character range: ‘[a-zA-Z]’ will match any character from a-z or A-Z. \d matches any decimal digit; this is equivalent to the class [0–9].\D Matches any non-digit character; this is equivalent to the class [^0–9]. \s Matches any whitespace character; this is equivalent to the class[\t\n\r\f\v].\S Matches any non-whitespace character; this is equivalent to the class[^\t\n\r\f\v].\w Matches any alphanumeric character; this is equivalent to the class [a-zA-Z0–9].\W Matches any non-alphanumeric character; this is equivalent to the class [^a-zA-Z0–9]. #9 Grouping character: A set of different symbols of a regular expression can be grouped together to act as a single unit and behave as a block, for this, you need to wrap the regular expression in the parenthesis( ). ‘(ab)+’ will match ‘ab’, ‘abab’,’abab...’.‘^(th).*” will match all string starting with ‘th’. #10 Vertical Bar ( | ): Matches any one element separated by the (|). th(e|is|at) will match words - the, this and that. #11 The Escape character (\): What if you want to match a meta-character with itself i.e match ‘*’ with a ‘*’ and not use it is a wild card?You can do so by adding a backslash( \ ) before that character. This will allow special characters to be used without invoking their special meaning. \d+[\+-x\*]\d+ will match patterns like "2+2" and "3*9" in "(2+2)*3*9". In order to write a regex for any email address, we need to keep in mind the following constraints: It can only start with an alphabet. ^([a-zA-Z]) It is of variable length and can contain any alphanumeric character along with ‘.’, ‘_’, ‘-’. ([a-zA-Z0–9_\-\.]*) It should have a ‘@’ followed by a domain name. @([a-zA-Z0–9_\-\.]+) It should end with a .(dot) something, usually 2/3 character long. \.([a-zA-Z]){2,3}$ Our final regular expression for an email address :^([a-zA-Z])([a-zA-Z0–9_\-\.]*)@([a-zA-Z0–9_\-\.]+)\.([a-zA-Z]){2,3}$ Regexes are useful in a wide variety of text processing tasks, and more generally string processing, where the data need not be textual. Common applications include data validation, data scraping (especially web scraping), data wrangling, simple parsing, the production of syntax highlighting systems, and many other tasks. While regexes would be useful on Internet search engines, processing them across the entire database could consume excessive computer resources depending on the complexity and design of the regex. Although in many cases system administrators can run regex-based queries internally, most search engines do not offer regex support to the public. Part 2 of this tutorial is up now, where we use REs in python through their re module. It also discusses some complex problems one faces while writing Regular Expression i.e. “The backlash plague”. See you there! 👋 Wikipedia: Regular Expression Geeksforgeeks Python Docs Regular Expressions Cookbook by Steven Levithan, Jan Goyvaerts Learning Git in Under 8 minutes! I‘m glad you made it till the end of this article. 🎉I hope your reading experience was as enriching as the one I had writing this. 💖 Do check out my other articles here. If you want to reach out to me, my medium of choice would be Twitter.
[ { "code": null, "e": 402, "s": 172, "text": "Regular expressions are a generalized way to match patterns with sequences of characters. They define a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. “find and replace” like operations." }, { "code": null, "e": 731, "s": 402, "text": "Let’s say you have to search a corpus and return all the email addresses mentioned in it. A pretty straightforward task for a human as every email address can be generalized as a string of alphanumeric characters with some permissible special characters like . (dot), _(underscore), -(hyphen), followed by a ‘@{domainName}.com’." }, { "code": null, "e": 1009, "s": 731, "text": "But how do you pass such a template to a computer? The fact that email addresses can be of variable length, don’t have a fixed location for numeric/special characters (could be in the beginning, the end, or anywhere in between), doesn’t make the task any easier for a computer." }, { "code": null, "e": 1206, "s": 1009, "text": "This is where regular expressions come to our rescue! By using them we can easily create a generalized template that a not only a computer will understand but will satisfy all of our restrictions." }, { "code": null, "e": 1646, "s": 1206, "text": "The term regular expression comes from mathematics and computer science theory, where it reflects a trait of mathematical expressions called regularity. The text patterns used by the earliest grep tools were regular expressions in the mathematical sense. Though the name has stuck, modern-day Perl-style regular expressions (which we still use with other programming languages) are not regular expressions at all in the mathematical sense." }, { "code": null, "e": 1704, "s": 1646, "text": "They are often called REs, or regexes, or regex patterns." }, { "code": null, "e": 1913, "s": 1704, "text": "#1: Most characters match with themselves. So if you have to write a regular expression for the word “wubbaLubbaDubDub”, the regex for it would be ‘wubbaLubbaDubDub’. Keep in mind that REs are case-sensitive." }, { "code": null, "e": 2227, "s": 1913, "text": "But there are some characters called meta-characters which don’t match to themselves rather signal that some out-of-the-ordinary thing should be matched, or they affect other portions of the RE by repeating them or changing their meaning. These meta-characters make regular expressions the powerful tool they are." }, { "code": null, "e": 2426, "s": 2227, "text": "#2: Repeaters *,+,{}. A lot of time you’ll face a scenario where you don't know how many times a character will be repeated or if it will be repeated at all. Repeaters allow us to tackle such cases." }, { "code": null, "e": 2593, "s": 2426, "text": "The asterisk (*): It implies that the preceding character is present 0 or more times. There is no upper bound on the number of occurrences of the preceding character." }, { "code": null, "e": 2732, "s": 2593, "text": "In ‘a*b’, ‘a’ precedes the *, which means ‘a’ can occur 0/0+ times. So it will match to ‘b’, ‘ab’, ‘aab’, ‘aaab’, ‘aa..(infinite a’s)..b’." }, { "code": null, "e": 2826, "s": 2732, "text": "The plus(+): It is the same as * but implies at least 1 occurrence of the previous character." }, { "code": null, "e": 2897, "s": 2826, "text": "‘a+b’ will match to ‘ab’, ‘aab’, ‘aaab’, ‘aaa...aab’ but not just ‘b’." }, { "code": null, "e": 2993, "s": 2897, "text": "The curly braces {}: These are used to define a range of occurrences of the previous character." }, { "code": null, "e": 3280, "s": 2993, "text": "‘a{3},b’: will match ‘aaab’ only. ‘a{min,}b’: restricting minimum occurrences of ‘a’, no upper limit restrictions. ‘a{3,}b’ will match ‘aaab’, ‘aaaab’, ‘aaa...aab’.‘a{min, max}b’: ‘a’ should occur at least min times and at most max times. ‘a{3,5}b’ will match ‘aaab’, ‘aaaab’, ‘aaaaab’." }, { "code": null, "e": 3487, "s": 3280, "text": "#3 The wildcard(.): Knowing the order of characters in a string is not always feasible. A wildcard comes in really handy in these situations.It implies that any character can take its place in the sequence." }, { "code": null, "e": 3750, "s": 3487, "text": "‘.’ will match all strings with just one character.‘.*’ will match all possible strings of any length.‘a.b’ will match ‘aab’, ‘abb’, ‘acb’, ‘adb’, .... ‘a b’ [a(space)b], ‘a/b’ and so on. Basically, any sequence of length 3 starting with ‘a’ and ending with ‘b’." }, { "code": null, "e": 4157, "s": 3750, "text": "#4 The Optional character(?): Sometimes multiple variations of a word are possible. Like ‘color’ (American English) and ‘colour’ (British English) are different spellings of the same word and both are correct, the only difference being an extra ‘u’ in the British version. The ‘?’ implies that the previous character may or may not be present in the final string. In a way, ‘?’ implies a 0 or 1 occurrence." }, { "code": null, "e": 4246, "s": 4157, "text": "‘colou?r’ will match both ‘color’ and ‘colour’.‘docx?’ will match both ‘doc’ and ‘docx’." }, { "code": null, "e": 4307, "s": 4246, "text": "#5 The Caret(^): It implies the first character of a string." }, { "code": null, "e": 4408, "s": 4307, "text": "‘^a.*’ will match all strings starting with ‘a’.‘^a{2}.*’ will match all strings starting with ‘aa’." }, { "code": null, "e": 4469, "s": 4408, "text": "#6 The dollar($): It implies the last character of a string." }, { "code": null, "e": 4518, "s": 4469, "text": "‘.*b$’ will match all strings ending with a ‘b’." }, { "code": null, "e": 4914, "s": 4518, "text": "#7 Character classes([]): More often than not, for a particular position in a string, there will be more than one possible character. To accommodate all the possible characters we use character classes. They specify a set of characters that you wish to match. Characters can be listed individually, or a range of characters can be indicated by giving two characters and separating them by a ‘-’." }, { "code": null, "e": 5206, "s": 4914, "text": "‘[abc]’: will match ‘a’, ‘b’, or ‘c’. ‘[^abc]’:Negation will match any character except ‘a’, ‘b’, and ‘c’. Note -- Not to be confused with caret where ^ implies begins with. If inside a character class ^ implies negation.Character range: ‘[a-zA-Z]’ will match any character from a-z or A-Z. " }, { "code": null, "e": 5689, "s": 5206, "text": "\\d matches any decimal digit; this is equivalent to the class [0–9].\\D Matches any non-digit character; this is equivalent to the class [^0–9]. \\s Matches any whitespace character; this is equivalent to the class[\\t\\n\\r\\f\\v].\\S Matches any non-whitespace character; this is equivalent to the class[^\\t\\n\\r\\f\\v].\\w Matches any alphanumeric character; this is equivalent to the class [a-zA-Z0–9].\\W Matches any non-alphanumeric character; this is equivalent to the class [^a-zA-Z0–9]." }, { "code": null, "e": 5907, "s": 5689, "text": "#9 Grouping character: A set of different symbols of a regular expression can be grouped together to act as a single unit and behave as a block, for this, you need to wrap the regular expression in the parenthesis( )." }, { "code": null, "e": 6001, "s": 5907, "text": "‘(ab)+’ will match ‘ab’, ‘abab’,’abab...’.‘^(th).*” will match all string starting with ‘th’." }, { "code": null, "e": 6071, "s": 6001, "text": "#10 Vertical Bar ( | ): Matches any one element separated by the (|)." }, { "code": null, "e": 6122, "s": 6071, "text": "th(e|is|at) will match words - the, this and that." }, { "code": null, "e": 6412, "s": 6122, "text": "#11 The Escape character (\\): What if you want to match a meta-character with itself i.e match ‘*’ with a ‘*’ and not use it is a wild card?You can do so by adding a backslash( \\ ) before that character. This will allow special characters to be used without invoking their special meaning." }, { "code": null, "e": 6493, "s": 6412, "text": "\\d+[\\+-x\\*]\\d+ will match patterns like \"2+2\" and \"3*9\" in \"(2+2)*3*9\"." }, { "code": null, "e": 6593, "s": 6493, "text": "In order to write a regex for any email address, we need to keep in mind the following constraints:" }, { "code": null, "e": 6641, "s": 6593, "text": "It can only start with an alphabet. ^([a-zA-Z])" }, { "code": null, "e": 6755, "s": 6641, "text": "It is of variable length and can contain any alphanumeric character along with ‘.’, ‘_’, ‘-’. ([a-zA-Z0–9_\\-\\.]*)" }, { "code": null, "e": 6824, "s": 6755, "text": "It should have a ‘@’ followed by a domain name. @([a-zA-Z0–9_\\-\\.]+)" }, { "code": null, "e": 6910, "s": 6824, "text": "It should end with a .(dot) something, usually 2/3 character long. \\.([a-zA-Z]){2,3}$" }, { "code": null, "e": 7030, "s": 6910, "text": "Our final regular expression for an email address :^([a-zA-Z])([a-zA-Z0–9_\\-\\.]*)@([a-zA-Z0–9_\\-\\.]+)\\.([a-zA-Z]){2,3}$" }, { "code": null, "e": 7354, "s": 7030, "text": "Regexes are useful in a wide variety of text processing tasks, and more generally string processing, where the data need not be textual. Common applications include data validation, data scraping (especially web scraping), data wrangling, simple parsing, the production of syntax highlighting systems, and many other tasks." }, { "code": null, "e": 7698, "s": 7354, "text": "While regexes would be useful on Internet search engines, processing them across the entire database could consume excessive computer resources depending on the complexity and design of the regex. Although in many cases system administrators can run regex-based queries internally, most search engines do not offer regex support to the public." }, { "code": null, "e": 7913, "s": 7698, "text": "Part 2 of this tutorial is up now, where we use REs in python through their re module. It also discusses some complex problems one faces while writing Regular Expression i.e. “The backlash plague”. See you there! 👋" }, { "code": null, "e": 7943, "s": 7913, "text": "Wikipedia: Regular Expression" }, { "code": null, "e": 7957, "s": 7943, "text": "Geeksforgeeks" }, { "code": null, "e": 7969, "s": 7957, "text": "Python Docs" }, { "code": null, "e": 8032, "s": 7969, "text": "Regular Expressions Cookbook by Steven Levithan, Jan Goyvaerts" }, { "code": null, "e": 8065, "s": 8032, "text": "Learning Git in Under 8 minutes!" }, { "code": null, "e": 8198, "s": 8065, "text": "I‘m glad you made it till the end of this article. 🎉I hope your reading experience was as enriching as the one I had writing this. 💖" }, { "code": null, "e": 8235, "s": 8198, "text": "Do check out my other articles here." } ]
Online Java Formatter
Editable Java Code 1234567891011121314151617181920212223242526import java.util.regex.Matcher;import java.util.regex.Pattern;public class RegexMatches{public static void main( String args[] ){// String to be scanned to find the pattern.String line = "This order was placed for QT3000! OK?";String pattern = "(.*)(\\d+)(.*)";// Create a Pattern objectPattern r = Pattern.compile(pattern);// Now create matcher object.Matcher m = r.matcher(line);if (m.find( )) {System.out.println("Found value: " + m.group(0) );System.out.println("Found value: " + m.group(1) );System.out.println("Found value: " + m.group(2) );} else {System.out.println("NO MATCH");}}}X Privacy Policy Cookies Policy Terms of Use
[ { "code": null, "e": 19, "s": 0, "text": "Editable Java Code" }, { "code": null, "e": 653, "s": 19, "text": "1234567891011121314151617181920212223242526import java.util.regex.Matcher;import java.util.regex.Pattern;public class RegexMatches{public static void main( String args[] ){// String to be scanned to find the pattern.String line = \"This order was placed for QT3000! OK?\";String pattern = \"(.*)(\\\\d+)(.*)\";// Create a Pattern objectPattern r = Pattern.compile(pattern);// Now create matcher object.Matcher m = r.matcher(line);if (m.find( )) {System.out.println(\"Found value: \" + m.group(0) );System.out.println(\"Found value: \" + m.group(1) );System.out.println(\"Found value: \" + m.group(2) );} else {System.out.println(\"NO MATCH\");}}}X" }, { "code": null, "e": 668, "s": 653, "text": "Privacy Policy" }, { "code": null, "e": 683, "s": 668, "text": "Cookies Policy" } ]
Build Interactive Charts using Flask and D3.js | by Samir Saci | Towards Data Science
You are a proud Data Scientist presenting your new solution designed using optimized code, fancy libraries, advanced linear algebra and complex statistical concepts. And [...] Your solution got less interest, recognition or enthusiasm from your management than a simple PowerBI dashboard presented by a new intern the day before. Have you faced this frustration? Simple fancy visualization can have more impact than a very complex model, especially for a non-technical audience. This article will give you a recipe to design fancy visualization using D3.js without prior knowledge of javascript (or very light). Pre-requisite Basic knowledge of HTML Intermediate knowledge of Python including Flask framework Find an example of visualization you want to design You are surfing in http://bl.ocks.org/, a great website to get tutorials for D3.js, and you find inspiration looking at this Matrix Diagram by Mike Bostock. Les Misérables is a famous French historical novel by Victor Hugo published in 1862. This matrix is showing the co-occurrence of characters 1 coloured cell = two characters appearing in the same chapter dark cells: characters with a high frequency of occurrence light cells: characters with a low frequency of occurrence You have a dataset of Luxury Cosmetics products Online Sales at the order line level. You want to build a matrix showing co-occurrence of brands 1 coloured cell = two brands appearing in the same customer order dark cells: brands that appear with many other brands light cells: brands that appear with few other brands You can find the source code shared in my Github repository: Samir SaciMy portfolio with other projects: Samir Saci Let us start by rendering an example found b.locks (Link) following structure below app.py/templates index.html/static /data miserables.json /js /Libs matrix.js /css /templates: index.html HTML source code of the dashboard page (Link) /js/libs: javascript libraries used to render D3.js /js/matrix.js: script used to render your dashboard using miserables.json /static/miserables.json: JSON file used by matrix.js to render (Link) /CSS: CSS files used to render the page Full code is uploaded in my Github repository (Link) used Copy Github repository in your local folderDownload libraries listed in requirements.txtLaunch app.py Copy Github repository in your local folder Download libraries listed in requirements.txt Launch app.py You have now built your first visualization solution using Flask and D3.js. Next steps are Replace miserables.json with your dataset Adapt matrix.js to show brands co-occurrence Adapt HTML page code to samirsaci.com Start with miserables.json The first step is to analyse miserables.json 1. Nodes: Characters distributed in different groups"nodes": {"name" : Character Name, "group" : Group Number}2. Links: Listing pairs of characters"nodes": {"source" : Character Name 1, "target" : Character Name 2, "value" : Number of Co-occurence} Get your brands.json What do we want? 1. Nodes: Brands are distributed in groups depending on the number of different brands that are ordered with it"nodes": {"name" : Brand Name, "group" : Group Number}2. Links: Listing pairs of brands that with number of orders they appear together"nodes": {"source" : Brand Name 1, "target" : Character_name2, "value" : Number of Orders they appear together} Build nodes The first function order_brand will prepare data frames and lists needed for the create_nodes function that will build your nodes dictionary. Comments n_groups: number of groups brands will be split line 35: descending order {group 1: brands ordered with many other brands, group n: brands that appear with few other brands} Export everything in JSON Final Result Comments json_to: this function will return JSON that will be retrieved by sending a get request to the page ‘/get-json’ Your JSON is ready to be used by matrix.js (after a few adjustments). I added these lines in the mouseover function to display the pair of brands selected. Download JSON file This function will send a GET request to your flask page ‘/get-json’ that will return json_to with the create_json function. Final Rendering /CSS: bootstrap and styles.css to improve the rendering of your page You can find a static version of this matrix chart in my portfolio: Matrix Chart This was an easy process in 4 steps Find a good visualization you want to use for your business caseDownload HTML code, javascript, CSS, JSON file and all files needed to build the pageRender this page locally with FlaskAnalyse JSON format and build functions to adapt your input dataAdapt javascript to fit with your data frame formatCustomize HTML page to add information regarding your dataset Find a good visualization you want to use for your business case Download HTML code, javascript, CSS, JSON file and all files needed to build the page Render this page locally with Flask Analyse JSON format and build functions to adapt your input data Adapt javascript to fit with your data frame format Customize HTML page to add information regarding your dataset Please feel free to contact me, I am willing to share and exchange on topics related to Data Science and Supply Chain.My Portfolio: https://samirsaci.com [1] — Mike Bostock & Jean-Daniel Fekete, Les Misérables Co-occurrence, Link [2] — Samir Saci, Initial Example for Flask Rendering, Github [3] — Samir Saci, Final Solution, Github [4] — Samir Saci, Example of a final rendering in my portfolio, Final Rendering
[ { "code": null, "e": 337, "s": 171, "text": "You are a proud Data Scientist presenting your new solution designed using optimized code, fancy libraries, advanced linear algebra and complex statistical concepts." }, { "code": null, "e": 347, "s": 337, "text": "And [...]" }, { "code": null, "e": 501, "s": 347, "text": "Your solution got less interest, recognition or enthusiasm from your management than a simple PowerBI dashboard presented by a new intern the day before." }, { "code": null, "e": 534, "s": 501, "text": "Have you faced this frustration?" }, { "code": null, "e": 650, "s": 534, "text": "Simple fancy visualization can have more impact than a very complex model, especially for a non-technical audience." }, { "code": null, "e": 783, "s": 650, "text": "This article will give you a recipe to design fancy visualization using D3.js without prior knowledge of javascript (or very light)." }, { "code": null, "e": 797, "s": 783, "text": "Pre-requisite" }, { "code": null, "e": 821, "s": 797, "text": "Basic knowledge of HTML" }, { "code": null, "e": 880, "s": 821, "text": "Intermediate knowledge of Python including Flask framework" }, { "code": null, "e": 932, "s": 880, "text": "Find an example of visualization you want to design" }, { "code": null, "e": 1089, "s": 932, "text": "You are surfing in http://bl.ocks.org/, a great website to get tutorials for D3.js, and you find inspiration looking at this Matrix Diagram by Mike Bostock." }, { "code": null, "e": 1175, "s": 1089, "text": "Les Misérables is a famous French historical novel by Victor Hugo published in 1862." }, { "code": null, "e": 1230, "s": 1175, "text": "This matrix is showing the co-occurrence of characters" }, { "code": null, "e": 1293, "s": 1230, "text": "1 coloured cell = two characters appearing in the same chapter" }, { "code": null, "e": 1352, "s": 1293, "text": "dark cells: characters with a high frequency of occurrence" }, { "code": null, "e": 1411, "s": 1352, "text": "light cells: characters with a low frequency of occurrence" }, { "code": null, "e": 1497, "s": 1411, "text": "You have a dataset of Luxury Cosmetics products Online Sales at the order line level." }, { "code": null, "e": 1556, "s": 1497, "text": "You want to build a matrix showing co-occurrence of brands" }, { "code": null, "e": 1622, "s": 1556, "text": "1 coloured cell = two brands appearing in the same customer order" }, { "code": null, "e": 1676, "s": 1622, "text": "dark cells: brands that appear with many other brands" }, { "code": null, "e": 1730, "s": 1676, "text": "light cells: brands that appear with few other brands" }, { "code": null, "e": 1846, "s": 1730, "text": "You can find the source code shared in my Github repository: Samir SaciMy portfolio with other projects: Samir Saci" }, { "code": null, "e": 1930, "s": 1846, "text": "Let us start by rendering an example found b.locks (Link) following structure below" }, { "code": null, "e": 2039, "s": 1930, "text": "app.py/templates index.html/static /data miserables.json /js /Libs matrix.js /css" }, { "code": null, "e": 2108, "s": 2039, "text": "/templates: index.html HTML source code of the dashboard page (Link)" }, { "code": null, "e": 2160, "s": 2108, "text": "/js/libs: javascript libraries used to render D3.js" }, { "code": null, "e": 2234, "s": 2160, "text": "/js/matrix.js: script used to render your dashboard using miserables.json" }, { "code": null, "e": 2304, "s": 2234, "text": "/static/miserables.json: JSON file used by matrix.js to render (Link)" }, { "code": null, "e": 2344, "s": 2304, "text": "/CSS: CSS files used to render the page" }, { "code": null, "e": 2402, "s": 2344, "text": "Full code is uploaded in my Github repository (Link) used" }, { "code": null, "e": 2504, "s": 2402, "text": "Copy Github repository in your local folderDownload libraries listed in requirements.txtLaunch app.py" }, { "code": null, "e": 2548, "s": 2504, "text": "Copy Github repository in your local folder" }, { "code": null, "e": 2594, "s": 2548, "text": "Download libraries listed in requirements.txt" }, { "code": null, "e": 2608, "s": 2594, "text": "Launch app.py" }, { "code": null, "e": 2684, "s": 2608, "text": "You have now built your first visualization solution using Flask and D3.js." }, { "code": null, "e": 2699, "s": 2684, "text": "Next steps are" }, { "code": null, "e": 2741, "s": 2699, "text": "Replace miserables.json with your dataset" }, { "code": null, "e": 2786, "s": 2741, "text": "Adapt matrix.js to show brands co-occurrence" }, { "code": null, "e": 2810, "s": 2786, "text": "Adapt HTML page code to" }, { "code": null, "e": 2824, "s": 2810, "text": "samirsaci.com" }, { "code": null, "e": 2851, "s": 2824, "text": "Start with miserables.json" }, { "code": null, "e": 2896, "s": 2851, "text": "The first step is to analyse miserables.json" }, { "code": null, "e": 3175, "s": 2896, "text": "1. Nodes: Characters distributed in different groups\"nodes\": {\"name\" : Character Name, \"group\" : Group Number}2. Links: Listing pairs of characters\"nodes\": {\"source\" : Character Name 1, \"target\" : Character Name 2, \"value\" : Number of Co-occurence}" }, { "code": null, "e": 3196, "s": 3175, "text": "Get your brands.json" }, { "code": null, "e": 3213, "s": 3196, "text": "What do we want?" }, { "code": null, "e": 3601, "s": 3213, "text": "1. Nodes: Brands are distributed in groups depending on the number of different brands that are ordered with it\"nodes\": {\"name\" : Brand Name, \"group\" : Group Number}2. Links: Listing pairs of brands that with number of orders they appear together\"nodes\": {\"source\" : Brand Name 1, \"target\" : Character_name2, \"value\" : Number of Orders they appear together}" }, { "code": null, "e": 3613, "s": 3601, "text": "Build nodes" }, { "code": null, "e": 3755, "s": 3613, "text": "The first function order_brand will prepare data frames and lists needed for the create_nodes function that will build your nodes dictionary." }, { "code": null, "e": 3764, "s": 3755, "text": "Comments" }, { "code": null, "e": 3812, "s": 3764, "text": "n_groups: number of groups brands will be split" }, { "code": null, "e": 3938, "s": 3812, "text": "line 35: descending order {group 1: brands ordered with many other brands, group n: brands that appear with few other brands}" }, { "code": null, "e": 3964, "s": 3938, "text": "Export everything in JSON" }, { "code": null, "e": 3977, "s": 3964, "text": "Final Result" }, { "code": null, "e": 3986, "s": 3977, "text": "Comments" }, { "code": null, "e": 4098, "s": 3986, "text": "json_to: this function will return JSON that will be retrieved by sending a get request to the page ‘/get-json’" }, { "code": null, "e": 4168, "s": 4098, "text": "Your JSON is ready to be used by matrix.js (after a few adjustments)." }, { "code": null, "e": 4254, "s": 4168, "text": "I added these lines in the mouseover function to display the pair of brands selected." }, { "code": null, "e": 4273, "s": 4254, "text": "Download JSON file" }, { "code": null, "e": 4398, "s": 4273, "text": "This function will send a GET request to your flask page ‘/get-json’ that will return json_to with the create_json function." }, { "code": null, "e": 4414, "s": 4398, "text": "Final Rendering" }, { "code": null, "e": 4483, "s": 4414, "text": "/CSS: bootstrap and styles.css to improve the rendering of your page" }, { "code": null, "e": 4564, "s": 4483, "text": "You can find a static version of this matrix chart in my portfolio: Matrix Chart" }, { "code": null, "e": 4600, "s": 4564, "text": "This was an easy process in 4 steps" }, { "code": null, "e": 4961, "s": 4600, "text": "Find a good visualization you want to use for your business caseDownload HTML code, javascript, CSS, JSON file and all files needed to build the pageRender this page locally with FlaskAnalyse JSON format and build functions to adapt your input dataAdapt javascript to fit with your data frame formatCustomize HTML page to add information regarding your dataset" }, { "code": null, "e": 5026, "s": 4961, "text": "Find a good visualization you want to use for your business case" }, { "code": null, "e": 5112, "s": 5026, "text": "Download HTML code, javascript, CSS, JSON file and all files needed to build the page" }, { "code": null, "e": 5148, "s": 5112, "text": "Render this page locally with Flask" }, { "code": null, "e": 5213, "s": 5148, "text": "Analyse JSON format and build functions to adapt your input data" }, { "code": null, "e": 5265, "s": 5213, "text": "Adapt javascript to fit with your data frame format" }, { "code": null, "e": 5327, "s": 5265, "text": "Customize HTML page to add information regarding your dataset" }, { "code": null, "e": 5481, "s": 5327, "text": "Please feel free to contact me, I am willing to share and exchange on topics related to Data Science and Supply Chain.My Portfolio: https://samirsaci.com" }, { "code": null, "e": 5558, "s": 5481, "text": "[1] — Mike Bostock & Jean-Daniel Fekete, Les Misérables Co-occurrence, Link" }, { "code": null, "e": 5620, "s": 5558, "text": "[2] — Samir Saci, Initial Example for Flask Rendering, Github" }, { "code": null, "e": 5661, "s": 5620, "text": "[3] — Samir Saci, Final Solution, Github" } ]
Renaming column names – Python Pandas
We can use the rename() method to rename column names. Let’s say the following is our Pandas DataFrame with 3 columns − dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units": [90, 120, 100, 150, 200, 130] } ) We will rename two columns i.e. “Car” to “Car Names” and “Reg_Price” to “Registration Cost”: dataFrame.rename(columns={dataFrame.columns[0]: 'Car Names', dataFrame.columns[1]: 'Registration Cost'}) Following is the code − import pandas as pd # Create DataFrame dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units": [90, 120, 100, 150, 200, 130] } ) print"DataFrame ...\n",dataFrame # Renaming columns res = dataFrame.rename(columns={dataFrame.columns[0]: 'Car Names', dataFrame.columns[1]: 'Registration Cost'}) print"\nUpdated DataFrame with renamed column names...\n",res This will produce the following output − DataFrame ... Car Reg_Price Units 0 BMW 7000 90 1 Lexus 1500 120 2 Tesla 5000 100 3 Mustang 8000 150 4 Mercedes 9000 200 5 Jaguar 6000 130 Updated DataFrame with renamed column names... Car Names Registration Cost Units 0 BMW 7000 90 1 Lexus 1500 120 2 Tesla 5000 100 3 Mustang 8000 150 4 Mercedes 9000 200 5 Jaguar 6000 130
[ { "code": null, "e": 1182, "s": 1062, "text": "We can use the rename() method to rename column names. Let’s say the following is our Pandas DataFrame with 3 columns −" }, { "code": null, "e": 1381, "s": 1182, "text": "dataFrame = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],\"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 6000],\"Units\": [90, 120, 100, 150, 200, 130]\n }\n)" }, { "code": null, "e": 1474, "s": 1381, "text": "We will rename two columns i.e. “Car” to “Car Names” and “Reg_Price” to “Registration Cost”:" }, { "code": null, "e": 1580, "s": 1474, "text": "dataFrame.rename(columns={dataFrame.columns[0]: 'Car Names', dataFrame.columns[1]: 'Registration Cost'})\n" }, { "code": null, "e": 1604, "s": 1580, "text": "Following is the code −" }, { "code": null, "e": 2073, "s": 1604, "text": "import pandas as pd\n\n# Create DataFrame\ndataFrame = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],\"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 6000],\"Units\": [90, 120, 100, 150, 200, 130]\n }\n)\n\nprint\"DataFrame ...\\n\",dataFrame\n\n# Renaming columns\nres = dataFrame.rename(columns={dataFrame.columns[0]: 'Car Names', dataFrame.columns[1]: 'Registration Cost'})\n\nprint\"\\nUpdated DataFrame with renamed column names...\\n\",res\n\n" }, { "code": null, "e": 2114, "s": 2073, "text": "This will produce the following output −" }, { "code": null, "e": 2680, "s": 2114, "text": "DataFrame ...\n Car Reg_Price Units\n0 BMW 7000 90\n1 Lexus 1500 120\n2 Tesla 5000 100\n3 Mustang 8000 150\n4 Mercedes 9000 200\n5 Jaguar 6000 130\n\nUpdated DataFrame with renamed column names...\n Car Names Registration Cost Units\n0 BMW 7000 90\n1 Lexus 1500 120\n2 Tesla 5000 100\n3 Mustang 8000 150\n4 Mercedes 9000 200\n5 Jaguar 6000 130" } ]
Pandas in Practice. A hands-on tutorial which demonstrates... | by Sultan Al Awar | Towards Data Science
Have you ever struggled to analyze big datasets in Excel then, you should have considered Pandas, powerful programming and data analysis toolbox which allows you to manipulate million-row data points in milliseconds with high processing power and user productivity. In fact, Pandas is an open-source python library, introduced by software developer Wes McKinney in 2008, which includes high-level data structures and programming tools to perform data analysis and manipulation on different data types whether numbers, text or dates, etc. This tutorial provides the necessary knowledge for you to start applying Pandas in your projects. Let us consider you just joined a startup as a data analyst and you have been assigned to support the team to drive insights about the customers base. Your manager shared the dataset and here is your opportunity to showcase your python skills and use the Pandas package to perform the analysis. This tutorial will help you to develop and use Pandas knowledge to: 1- import and read a CSV file 2- generate a basic understanding of a given data 3- select and filter data based on conditions 4- apply various data operation tools such as creating new variables or changing data types 5- perform data aggregation using group by and pivot table methods 6- transform analytical insights into business recommendations. #load the needed packages and modules import pandas as pdimport numpy as npfrom datetime import dateimport datetime as dt The first step is to load the data using pd_read_csv which reads the data of a CSV file, loads and returns the content in a data frame. You might ask yourself, what is a data frame? Data frames are the primary data structure in the pandas package which displays the data in a table of different attributes as shown below. For more information about the pd.read_csv, visit the link. The dataset which will be used in this tutorial is a dummy dataset was created for this article. It is available in this link and it includes interesting data about customers which can be used in a targeted marketing campaign. #load the data and make sure to change the path for your localdirectory data = pd.read_csv('C:/Users/Smart PC/Desktop/project_data.csv') After we loaded the data, we can use different methods to view and understand the variables. For example, data.head() enables us to view the first 5 rows of the dataframe whereas data.tail() returns the last 5 rows. If you want to get the first 10 rows, you need to specify it in the method as data.head(10). #first 5 rowsdata.head() #last 5 rows data.tail() Another interesting method is data.info() which gives us the number of data points and variables of the dataset. It also displays the data types. We can see that our dataset has 499 data points and 12 variables ranging from customers’ personal information to purchases, calls, intercoms, and complaints. #check the basic information of the datadata.info() We can check the shape of the dataset using data.shape; it indicates that our dataset has 449 rows and 12 columns. #extract the shape of the datadata.shape Let us consider we are interested to know the unique values of the marital status field then, we should select the column and apply the unique method. As shown below the variable marital status has 5 unique categories. However, we notice that widow and widowed are two two different naming for the same category so we can make it consistent through using replace method on the column values as displayed below. data['marital_status'].unique() data[‘marital_status’] = data[‘marital_status’].replace(‘Widow’, ‘Widowed’) Another interesting way to know the unique values but with their respective counts is to apply the value_count method on the column. For instance, the education attribute has 5 categories whereby Graduation and PhD constitute the largest proportion. round(data['educational_level'].value_counts(normalize=True),2) We can check for duplicates and null values in the whole dataset using the .duplicated and .isnull methods. Furthermore, we can select one variable of interest in the dataset to detect its missing values or duplicates as displayed below. data.isnull()data.duplicated().sum()data['educational_level'].isnull().sum() #specifying Education as a variable where we should look for the sum of missing values We can simply select a subset of the data points from the data frame. Let us consider that we want to select the Birthdate, Education, and Income of every customer; this is achievable through selecting the column names with double brackets as shown below. subset_data = data[['year_of_birth ', 'educational_level', 'annual_income']]subset_data We can select a unique category of the education by specifying that only “Master” should be returned from the data frame. data[data["educational_level"] == "Master"] The other two popular methods to select data from a data frame are: loc and iloc. The main distinction between these two methods is that: loc is label-based, which means that we have to specify rows and columns based on the titles. However, iloc is integer position-based, so we have to select the rows and columns by their position values as integer i.e: 0,1,2. To read more about selecting data using these methods, visit this link. As we notice below, we are selecting the first seven data points using the loc method, but for the variables ‘educational_level’ and ‘recency’. We can also achieve the same result with iloc but with specifying the rows and columns as integer values. data.loc[:6, ['educational_level', 'recency']] #specify the rows and columns as labels data.iloc[:6, [2,6]] #speciy rows and columns as integer based values Another powerful tool is to filter data using the loc and isin() methods whereby we choose the variable of interest and we select the categories we want. For example, below we are choosing all the customers with a Marital Status described as Single or Divorced only. data.loc[data[‘marital_status’].isin([‘Single’, ‘Divorced’])] We can combine iloc with a python operator to select data that satisfies two conditions such as choosing the customers with an income higher than 75,000 and with a master’s degree. data.iloc[list((data.annual_income > 75000) & (data.educational_level == 'Master')), :,] We can apply different operations on the dataset using Pandas such as but not limited to:- setting a new index with the variable of our interest using the .set_index() method- sorting the data frame by one of the variable using .sort_values() with ascending or descending order; For more information about the sort_values(), visit the link - creating a new variable which could be the result of a mathematical operation such as sum of other variables - building categories of a variable using pd.cut() method; For more information about the pd.cut(), visit the link - changing the datatype of variables into datetime or integer types- determining the age based on year of birth - creating the week date (calendar week and year) from the purchase dateand many more; this is just a glimpse of what we can achieve with pandas! #set the index as customer_iddata.set_index(‘customer_id’) #sort the data by year_of_birth, ascending is default;data.sort_values(by = ['year_of_birth '], ascending = True) # if we want it in descending we should set ascending = False #create a new variable which is the sum of all purchases performed by customersdata['sum_purchases'] = data.online_purchases + data.store_purchases data['sum_purchases'] #create an income category (low, meduim, high) based on the income variableincome_categories = ['Low', 'Meduim', 'High'] #set the categoriesbins = [0,75000,120000,600000] #set the income boundaries cats= pd.cut(data['annual_income'],bins, labels=income_categories) #apply the pd.cut methoddata['Income_Category'] = cats #assign the categories based on incomedata[['annual_income', 'Income_Category']] #we can change the datatype of purchase_date to datetime and year_birth to integerdata['purhcase_date'] = pd.to_datetime(data['purhcase_date'])data['year_of_birth '] = data['year_of_birth '].astype(int)#find out the age of customers based on the current yeartoday = date.today()year = int(today.year)data['Age'] = year - data['year_of_birth ']data['Age'] #extract the week_date from the purchase_date which shows the year of purchase and the calendar week#make sure to change the purhcase_date varibale to datetime as shown above before applying the .isocalendar() methoddata["week_date"] = [int(f'{i.isocalendar()[0]}{i.isocalendar()[1]}') for i in data.purhcase_date]data["week_date After we created new variables, we can further aggregate to generate interesting insights from categories. Two key methods every data scientist uses to analyze data by groups: groupby(): a method that involves splitting categories, applying a function, and combining the results, whereby it can be used with a mathematical operation such as mean, sum, or count with an aggregated view by a group. For further information about this operation, visit this link groupby(): a method that involves splitting categories, applying a function, and combining the results, whereby it can be used with a mathematical operation such as mean, sum, or count with an aggregated view by a group. For further information about this operation, visit this link 2. pivot_table() : a very useful technique that creates a spreadsheet-style pivot table as a Data frame, and it also allows analysts to apply a mathematical operation on selected variables per group. For further information about this pivot_table, visit this link #apply groupby to find the mean of income, recency, number of web and store purchases by educational groupaggregate_view = pd.DataFrame(data.groupby(by='educational_level')[['annual_income', 'recency', 'store_purchases', 'online_purchases']].mean()).reset_index()aggregate_view #apply pivot table to find the aggregated sum of purchases and mean of recency per education and marital status grouppivot_table = pd.DataFrame(pd.pivot_table(data, values=['sum_purchases', 'recency'], index=['marital_status'], columns=['educational_level'], aggfunc={'recency': np.mean, 'sum_purchases': np.sum}, fill_value=0)).reset_index()pivot_table Now after we completed the process of data cleaning and performing operations and aggregations on our dataset, we can conclude with some interesting insights about our customer base: PhD people have the highest income, number of online and store purchases; however, High School graduates people have the highest recency or number of days since their last purchase Basic people account for the lowest number of web and store purchases Married people with Graduation level have the highest total purchases Therefore, the business recommendations for any potential marketing campaign should focus on attracting and retaining PhD people and married couples with Graduation level, and more products should be offered to satisfy the needs and interests of other categories such as Basic people that have the lowest purchases as well as High School people who are not purchasing regularly. Additionally, further work should be conducted to understand customer behaviors and interests, for example, performing RFM analysis or regression modeling will be beneficial to study the effect of variables on the number of purchases by educational or marital status group. Finally, I hope you found this article as enriching, practical, and useful to employ pandas in your upcoming data analysis exercise. Here is a concluding summary:- Pandas is a data analysis library built on top of the Python programming language,- Pandas excels at performing complex operations on large data sets with multiple variables,- Data frame is the primary data structure in pandas,- loc and iloc are used to select and filter data,- group_by and pivot_table are the two most well-known aggregation methods. Stay tuned for more exciting machine learning and data analytics sharing knowledge content.
[ { "code": null, "e": 801, "s": 165, "text": "Have you ever struggled to analyze big datasets in Excel then, you should have considered Pandas, powerful programming and data analysis toolbox which allows you to manipulate million-row data points in milliseconds with high processing power and user productivity. In fact, Pandas is an open-source python library, introduced by software developer Wes McKinney in 2008, which includes high-level data structures and programming tools to perform data analysis and manipulation on different data types whether numbers, text or dates, etc. This tutorial provides the necessary knowledge for you to start applying Pandas in your projects." }, { "code": null, "e": 1096, "s": 801, "text": "Let us consider you just joined a startup as a data analyst and you have been assigned to support the team to drive insights about the customers base. Your manager shared the dataset and here is your opportunity to showcase your python skills and use the Pandas package to perform the analysis." }, { "code": null, "e": 1164, "s": 1096, "text": "This tutorial will help you to develop and use Pandas knowledge to:" }, { "code": null, "e": 1194, "s": 1164, "text": "1- import and read a CSV file" }, { "code": null, "e": 1244, "s": 1194, "text": "2- generate a basic understanding of a given data" }, { "code": null, "e": 1290, "s": 1244, "text": "3- select and filter data based on conditions" }, { "code": null, "e": 1382, "s": 1290, "text": "4- apply various data operation tools such as creating new variables or changing data types" }, { "code": null, "e": 1449, "s": 1382, "text": "5- perform data aggregation using group by and pivot table methods" }, { "code": null, "e": 1513, "s": 1449, "text": "6- transform analytical insights into business recommendations." }, { "code": null, "e": 1635, "s": 1513, "text": "#load the needed packages and modules import pandas as pdimport numpy as npfrom datetime import dateimport datetime as dt" }, { "code": null, "e": 2017, "s": 1635, "text": "The first step is to load the data using pd_read_csv which reads the data of a CSV file, loads and returns the content in a data frame. You might ask yourself, what is a data frame? Data frames are the primary data structure in the pandas package which displays the data in a table of different attributes as shown below. For more information about the pd.read_csv, visit the link." }, { "code": null, "e": 2244, "s": 2017, "text": "The dataset which will be used in this tutorial is a dummy dataset was created for this article. It is available in this link and it includes interesting data about customers which can be used in a targeted marketing campaign." }, { "code": null, "e": 2381, "s": 2244, "text": "#load the data and make sure to change the path for your localdirectory data = pd.read_csv('C:/Users/Smart PC/Desktop/project_data.csv')" }, { "code": null, "e": 2690, "s": 2381, "text": "After we loaded the data, we can use different methods to view and understand the variables. For example, data.head() enables us to view the first 5 rows of the dataframe whereas data.tail() returns the last 5 rows. If you want to get the first 10 rows, you need to specify it in the method as data.head(10)." }, { "code": null, "e": 2715, "s": 2690, "text": "#first 5 rowsdata.head()" }, { "code": null, "e": 2740, "s": 2715, "text": "#last 5 rows data.tail()" }, { "code": null, "e": 3044, "s": 2740, "text": "Another interesting method is data.info() which gives us the number of data points and variables of the dataset. It also displays the data types. We can see that our dataset has 499 data points and 12 variables ranging from customers’ personal information to purchases, calls, intercoms, and complaints." }, { "code": null, "e": 3096, "s": 3044, "text": "#check the basic information of the datadata.info()" }, { "code": null, "e": 3211, "s": 3096, "text": "We can check the shape of the dataset using data.shape; it indicates that our dataset has 449 rows and 12 columns." }, { "code": null, "e": 3252, "s": 3211, "text": "#extract the shape of the datadata.shape" }, { "code": null, "e": 3663, "s": 3252, "text": "Let us consider we are interested to know the unique values of the marital status field then, we should select the column and apply the unique method. As shown below the variable marital status has 5 unique categories. However, we notice that widow and widowed are two two different naming for the same category so we can make it consistent through using replace method on the column values as displayed below." }, { "code": null, "e": 3695, "s": 3663, "text": "data['marital_status'].unique()" }, { "code": null, "e": 3771, "s": 3695, "text": "data[‘marital_status’] = data[‘marital_status’].replace(‘Widow’, ‘Widowed’)" }, { "code": null, "e": 4021, "s": 3771, "text": "Another interesting way to know the unique values but with their respective counts is to apply the value_count method on the column. For instance, the education attribute has 5 categories whereby Graduation and PhD constitute the largest proportion." }, { "code": null, "e": 4085, "s": 4021, "text": "round(data['educational_level'].value_counts(normalize=True),2)" }, { "code": null, "e": 4323, "s": 4085, "text": "We can check for duplicates and null values in the whole dataset using the .duplicated and .isnull methods. Furthermore, we can select one variable of interest in the dataset to detect its missing values or duplicates as displayed below." }, { "code": null, "e": 4487, "s": 4323, "text": "data.isnull()data.duplicated().sum()data['educational_level'].isnull().sum() #specifying Education as a variable where we should look for the sum of missing values" }, { "code": null, "e": 4743, "s": 4487, "text": "We can simply select a subset of the data points from the data frame. Let us consider that we want to select the Birthdate, Education, and Income of every customer; this is achievable through selecting the column names with double brackets as shown below." }, { "code": null, "e": 4831, "s": 4743, "text": "subset_data = data[['year_of_birth ', 'educational_level', 'annual_income']]subset_data" }, { "code": null, "e": 4953, "s": 4831, "text": "We can select a unique category of the education by specifying that only “Master” should be returned from the data frame." }, { "code": null, "e": 4997, "s": 4953, "text": "data[data[\"educational_level\"] == \"Master\"]" }, { "code": null, "e": 5432, "s": 4997, "text": "The other two popular methods to select data from a data frame are: loc and iloc. The main distinction between these two methods is that: loc is label-based, which means that we have to specify rows and columns based on the titles. However, iloc is integer position-based, so we have to select the rows and columns by their position values as integer i.e: 0,1,2. To read more about selecting data using these methods, visit this link." }, { "code": null, "e": 5682, "s": 5432, "text": "As we notice below, we are selecting the first seven data points using the loc method, but for the variables ‘educational_level’ and ‘recency’. We can also achieve the same result with iloc but with specifying the rows and columns as integer values." }, { "code": null, "e": 5769, "s": 5682, "text": "data.loc[:6, ['educational_level', 'recency']] #specify the rows and columns as labels" }, { "code": null, "e": 5839, "s": 5769, "text": "data.iloc[:6, [2,6]] #speciy rows and columns as integer based values" }, { "code": null, "e": 6106, "s": 5839, "text": "Another powerful tool is to filter data using the loc and isin() methods whereby we choose the variable of interest and we select the categories we want. For example, below we are choosing all the customers with a Marital Status described as Single or Divorced only." }, { "code": null, "e": 6168, "s": 6106, "text": "data.loc[data[‘marital_status’].isin([‘Single’, ‘Divorced’])]" }, { "code": null, "e": 6349, "s": 6168, "text": "We can combine iloc with a python operator to select data that satisfies two conditions such as choosing the customers with an income higher than 75,000 and with a master’s degree." }, { "code": null, "e": 6439, "s": 6349, "text": "data.iloc[list((data.annual_income > 75000) & (data.educational_level == 'Master')), :,]" }, { "code": null, "e": 7263, "s": 6439, "text": "We can apply different operations on the dataset using Pandas such as but not limited to:- setting a new index with the variable of our interest using the .set_index() method- sorting the data frame by one of the variable using .sort_values() with ascending or descending order; For more information about the sort_values(), visit the link - creating a new variable which could be the result of a mathematical operation such as sum of other variables - building categories of a variable using pd.cut() method; For more information about the pd.cut(), visit the link - changing the datatype of variables into datetime or integer types- determining the age based on year of birth - creating the week date (calendar week and year) from the purchase dateand many more; this is just a glimpse of what we can achieve with pandas!" }, { "code": null, "e": 7322, "s": 7263, "text": "#set the index as customer_iddata.set_index(‘customer_id’)" }, { "code": null, "e": 7498, "s": 7322, "text": "#sort the data by year_of_birth, ascending is default;data.sort_values(by = ['year_of_birth '], ascending = True) # if we want it in descending we should set ascending = False" }, { "code": null, "e": 7668, "s": 7498, "text": "#create a new variable which is the sum of all purchases performed by customersdata['sum_purchases'] = data.online_purchases + data.store_purchases data['sum_purchases']" }, { "code": null, "e": 8069, "s": 7668, "text": "#create an income category (low, meduim, high) based on the income variableincome_categories = ['Low', 'Meduim', 'High'] #set the categoriesbins = [0,75000,120000,600000] #set the income boundaries cats= pd.cut(data['annual_income'],bins, labels=income_categories) #apply the pd.cut methoddata['Income_Category'] = cats #assign the categories based on incomedata[['annual_income', 'Income_Category']]" }, { "code": null, "e": 8424, "s": 8069, "text": "#we can change the datatype of purchase_date to datetime and year_birth to integerdata['purhcase_date'] = pd.to_datetime(data['purhcase_date'])data['year_of_birth '] = data['year_of_birth '].astype(int)#find out the age of customers based on the current yeartoday = date.today()year = int(today.year)data['Age'] = year - data['year_of_birth ']data['Age']" }, { "code": null, "e": 8754, "s": 8424, "text": "#extract the week_date from the purchase_date which shows the year of purchase and the calendar week#make sure to change the purhcase_date varibale to datetime as shown above before applying the .isocalendar() methoddata[\"week_date\"] = [int(f'{i.isocalendar()[0]}{i.isocalendar()[1]}') for i in data.purhcase_date]data[\"week_date" }, { "code": null, "e": 8930, "s": 8754, "text": "After we created new variables, we can further aggregate to generate interesting insights from categories. Two key methods every data scientist uses to analyze data by groups:" }, { "code": null, "e": 9213, "s": 8930, "text": "groupby(): a method that involves splitting categories, applying a function, and combining the results, whereby it can be used with a mathematical operation such as mean, sum, or count with an aggregated view by a group. For further information about this operation, visit this link" }, { "code": null, "e": 9496, "s": 9213, "text": "groupby(): a method that involves splitting categories, applying a function, and combining the results, whereby it can be used with a mathematical operation such as mean, sum, or count with an aggregated view by a group. For further information about this operation, visit this link" }, { "code": null, "e": 9760, "s": 9496, "text": "2. pivot_table() : a very useful technique that creates a spreadsheet-style pivot table as a Data frame, and it also allows analysts to apply a mathematical operation on selected variables per group. For further information about this pivot_table, visit this link" }, { "code": null, "e": 10039, "s": 9760, "text": "#apply groupby to find the mean of income, recency, number of web and store purchases by educational groupaggregate_view = pd.DataFrame(data.groupby(by='educational_level')[['annual_income', 'recency', 'store_purchases', 'online_purchases']].mean()).reset_index()aggregate_view" }, { "code": null, "e": 10416, "s": 10039, "text": "#apply pivot table to find the aggregated sum of purchases and mean of recency per education and marital status grouppivot_table = pd.DataFrame(pd.pivot_table(data, values=['sum_purchases', 'recency'], index=['marital_status'], columns=['educational_level'], aggfunc={'recency': np.mean, 'sum_purchases': np.sum}, fill_value=0)).reset_index()pivot_table" }, { "code": null, "e": 10599, "s": 10416, "text": "Now after we completed the process of data cleaning and performing operations and aggregations on our dataset, we can conclude with some interesting insights about our customer base:" }, { "code": null, "e": 10780, "s": 10599, "text": "PhD people have the highest income, number of online and store purchases; however, High School graduates people have the highest recency or number of days since their last purchase" }, { "code": null, "e": 10850, "s": 10780, "text": "Basic people account for the lowest number of web and store purchases" }, { "code": null, "e": 10920, "s": 10850, "text": "Married people with Graduation level have the highest total purchases" }, { "code": null, "e": 11299, "s": 10920, "text": "Therefore, the business recommendations for any potential marketing campaign should focus on attracting and retaining PhD people and married couples with Graduation level, and more products should be offered to satisfy the needs and interests of other categories such as Basic people that have the lowest purchases as well as High School people who are not purchasing regularly." }, { "code": null, "e": 11573, "s": 11299, "text": "Additionally, further work should be conducted to understand customer behaviors and interests, for example, performing RFM analysis or regression modeling will be beneficial to study the effect of variables on the number of purchases by educational or marital status group." }, { "code": null, "e": 12090, "s": 11573, "text": "Finally, I hope you found this article as enriching, practical, and useful to employ pandas in your upcoming data analysis exercise. Here is a concluding summary:- Pandas is a data analysis library built on top of the Python programming language,- Pandas excels at performing complex operations on large data sets with multiple variables,- Data frame is the primary data structure in pandas,- loc and iloc are used to select and filter data,- group_by and pivot_table are the two most well-known aggregation methods." } ]
How to use year input type in HTML?
The month input type is used in HTML using the <input type = "month">. Using this, allow the users to select month and year. But, what if you only want to show the year popup? Well, year input type isn’t available. To use year input type, we will be using jQuery to add datepicker. It is used with the text input type. On running the program, only the year will be visible. You can try to run the following code to learn how to use input type to set a year Live Demo <html> <head> <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"> </script> <script type="text/javascript"> $(function() { $( "#date" ).datepicker({dateFormat: 'yy'}); }); </script> </head> <body> <form action = "" method = "get"> Details:<br> <br> Student Name <br> <input type="name" name="sname"> <br> Year of Birth <br> <input type="text" id="date"> <br> <input type="submit" value="Submit"> </form> </body> </html>
[ { "code": null, "e": 1277, "s": 1062, "text": "The month input type is used in HTML using the <input type = \"month\">. Using this, allow the users to select month and year. But, what if you only want to show the year popup? Well, year input type isn’t available." }, { "code": null, "e": 1436, "s": 1277, "text": "To use year input type, we will be using jQuery to add datepicker. It is used with the text input type. On running the program, only the year will be visible." }, { "code": null, "e": 1519, "s": 1436, "text": "You can try to run the following code to learn how to use input type to set a year" }, { "code": null, "e": 1529, "s": 1519, "text": "Live Demo" }, { "code": null, "e": 2085, "s": 1529, "text": "<html>\n <head>\n <script src=\"https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js\">\n </script>\n <script type=\"text/javascript\">\n $(function() {\n $( \"#date\" ).datepicker({dateFormat: 'yy'});\n });\n </script>\n </head>\n <body>\n <form action = \"\" method = \"get\">\n Details:<br> <br>\n Student Name <br> <input type=\"name\" name=\"sname\"> <br>\n Year of Birth <br> <input type=\"text\" id=\"date\"> <br>\n <input type=\"submit\" value=\"Submit\">\n </form>\n </body>\n</html>" } ]
How To Create And Use Custom Matplotlib Style Sheet | by Shan Dou | Towards Data Science
The aesthetics of data visualizations are important. I often view this as “beautiful data deserves beautiful presentations” — Being overly fastidious with graph styling is not encouraged, but a healthy amount of polishing could go a long way. Nevertheless, for static graphs that we typically make with matplotlib or seaborn, the default aesthetics usually require tweaking. This is where custom style sheets come in handy for at least two reasons: Make our workflow compliant with the Don’t Repeat Yourself (DRY) principle: We don’t need to type the same chunks of styling codes repetitively every time. Instead, we apply the style sheet with one line of code Styling consistency is easily achieved, and that could be an implicit signature for individuals, teams, and organizations Most of us may already have been using a few built-in styles in day-to-day work. For example, a quick run of # This code snippet mimics command usages in ipython consoleIn [1]: import matplotlib.pyplot as pltOut [1]: plt.style.available will return a full list of style sheets, and we can find a gallery view of their effects in matplotlib’s documentation. Under the hood, we can locate these built-in style sheets and take a look: # This code snippet mimics command usages in ipython consoleIn [2]: import matplotlib# Locate path to matplotlib by checking where config file is# To learn more about the function below,# type ?matplotlib.matplotlib_fnameIn [3]: matplotlib.matplotlib_fname()Out [3]: '/Users/sdou/opt/miniconda3/lib/python3.8/site-packages/matplotlib/mpl-data/matplotlibrc' The path /Users/.../mpl-data is where we would like to go and locate the style sheets: In [4]: !ls /Users/sdou/opt/miniconda3/lib/python3.8/site-packages/matplotlib/mpl-data/fonts images matplotlibrc stylelib The folder of interest is stylelib. Let’s now take a look inside this folder: In [5]: !ls -1 /Users/sdou/opt/miniconda3/lib/python3.8/site-packages/matplotlib/mpl-data/stylelib/Solarize_Light2.mplstyle_classic_test_patch.mplstylebmh.mplstyleclassic.mplstyledark_background.mplstylefast.mplstylefivethirtyeight.mplstyleggplot.mplstylegrayscale.mplstyleseaborn-bright.mplstyleseaborn-colorblind.mplstyleseaborn-dark-palette.mplstyleseaborn-dark.mplstyleseaborn-darkgrid.mplstyleseaborn-deep.mplstyleseaborn-muted.mplstyleseaborn-notebook.mplstyleseaborn-paper.mplstyleseaborn-pastel.mplstyleseaborn-poster.mplstyleseaborn-talk.mplstyleseaborn-ticks.mplstyleseaborn-white.mplstyleseaborn-whitegrid.mplstyleseaborn.mplstyletableau-colorblind10.mplstyle Let’s inspect one of the .mplstyle files. Here we use classic.mplstyle as an example and display the top 37 lines of the file: We can see a comprehensive list of matplotlib parameter settings and their default values, and the parameters are organized into groups such as lines, markers, patch, text. Below is a minimalism example (named signature.mplstyle)built on top of the built-in style sheetseaborn-colorblind.mplstyle If we have write privilege to the abovementioned path for stylelib, we can put the custom style sheet into the same folder and invoke the style sheet with # Scenario 1: Apply globally to a jupyter notebookplt.style.use(“signature”)# Scenario 2: Apply locally with context managerwith plt.style.context("signature"): plt.plot([1, 2, 3, 4]) If we don’t have the write privilege, the only extra thing we would need to do is to include the full path of the custom style sheet. Here we use a simple example of directly storing the style sheet under the home directory: # Scenario 1: Apply globally to a jupyter notebookplt.style.use(“/home/signature.mplstyle”)# Scenario 2: Apply locally with context managerwith plt.style.context("/home/signature.mplstyle"): plt.plot([1, 2, 3, 4]) There could be cases when we want to recover the default styling. There are at two ways to recover the default settings: Reset via rcParams.update Reset via rcParams.update import matplotlib as mplmpl.rcParams.update(mpl.rcParamsDefault) 2. Reset with default style sheet plt.style.use('default') Here we penguin dataset as an example to demonstrate the effect of the custom style sheet signaure.mplstyle. import matplotlib.pyplot as pltimport seaborn as sns# Load the penguins datasetpenguins = sns.load_dataset("penguins") Use default style Use default style plt.style.use("default")# Show the joint distribution using kernel density estimationg = sns.jointplot( data=penguins, x="bill_length_mm", y="bill_depth_mm", hue="species", kind="kde",)g.fig.suptitle("Styled With Default Style Sheet", y=1.01)plt.show() 2. Use custom style set in signature.mplstyle plt.style.use("signature")# Show the joint distribution using kernel density estimationg = sns.jointplot( data=penguins, x="bill_length_mm", y="bill_depth_mm", hue="species", kind="kde",)g.fig.suptitle("Styled With Custom Style Sheet", y=1.01)plt.show() Beautiful data deserves beautiful presentations. But instead of typing chunks of styling codes repetitively, a bit upfront time investment in setting up our own custom style sheet (file extension .mplstyle) could both save time and ensure styling consistency To build custom style sheets, we could start with built-in style sheets and custom them further to our liking. One key step is to locate these style sheets with the help of matplotlib.matplotlib_fname() 4.11 Customizing Matplotlib: Configurations and Stylesheets: Data Science Handbook by Jake VanderPlas
[ { "code": null, "e": 415, "s": 172, "text": "The aesthetics of data visualizations are important. I often view this as “beautiful data deserves beautiful presentations” — Being overly fastidious with graph styling is not encouraged, but a healthy amount of polishing could go a long way." }, { "code": null, "e": 621, "s": 415, "text": "Nevertheless, for static graphs that we typically make with matplotlib or seaborn, the default aesthetics usually require tweaking. This is where custom style sheets come in handy for at least two reasons:" }, { "code": null, "e": 833, "s": 621, "text": "Make our workflow compliant with the Don’t Repeat Yourself (DRY) principle: We don’t need to type the same chunks of styling codes repetitively every time. Instead, we apply the style sheet with one line of code" }, { "code": null, "e": 955, "s": 833, "text": "Styling consistency is easily achieved, and that could be an implicit signature for individuals, teams, and organizations" }, { "code": null, "e": 1064, "s": 955, "text": "Most of us may already have been using a few built-in styles in day-to-day work. For example, a quick run of" }, { "code": null, "e": 1192, "s": 1064, "text": "# This code snippet mimics command usages in ipython consoleIn [1]: import matplotlib.pyplot as pltOut [1]: plt.style.available" }, { "code": null, "e": 1312, "s": 1192, "text": "will return a full list of style sheets, and we can find a gallery view of their effects in matplotlib’s documentation." }, { "code": null, "e": 1387, "s": 1312, "text": "Under the hood, we can locate these built-in style sheets and take a look:" }, { "code": null, "e": 1744, "s": 1387, "text": "# This code snippet mimics command usages in ipython consoleIn [2]: import matplotlib# Locate path to matplotlib by checking where config file is# To learn more about the function below,# type ?matplotlib.matplotlib_fnameIn [3]: matplotlib.matplotlib_fname()Out [3]: '/Users/sdou/opt/miniconda3/lib/python3.8/site-packages/matplotlib/mpl-data/matplotlibrc'" }, { "code": null, "e": 1831, "s": 1744, "text": "The path /Users/.../mpl-data is where we would like to go and locate the style sheets:" }, { "code": null, "e": 1975, "s": 1831, "text": "In [4]: !ls /Users/sdou/opt/miniconda3/lib/python3.8/site-packages/matplotlib/mpl-data/fonts images matplotlibrc stylelib" }, { "code": null, "e": 2053, "s": 1975, "text": "The folder of interest is stylelib. Let’s now take a look inside this folder:" }, { "code": null, "e": 2724, "s": 2053, "text": "In [5]: !ls -1 /Users/sdou/opt/miniconda3/lib/python3.8/site-packages/matplotlib/mpl-data/stylelib/Solarize_Light2.mplstyle_classic_test_patch.mplstylebmh.mplstyleclassic.mplstyledark_background.mplstylefast.mplstylefivethirtyeight.mplstyleggplot.mplstylegrayscale.mplstyleseaborn-bright.mplstyleseaborn-colorblind.mplstyleseaborn-dark-palette.mplstyleseaborn-dark.mplstyleseaborn-darkgrid.mplstyleseaborn-deep.mplstyleseaborn-muted.mplstyleseaborn-notebook.mplstyleseaborn-paper.mplstyleseaborn-pastel.mplstyleseaborn-poster.mplstyleseaborn-talk.mplstyleseaborn-ticks.mplstyleseaborn-white.mplstyleseaborn-whitegrid.mplstyleseaborn.mplstyletableau-colorblind10.mplstyle" }, { "code": null, "e": 2851, "s": 2724, "text": "Let’s inspect one of the .mplstyle files. Here we use classic.mplstyle as an example and display the top 37 lines of the file:" }, { "code": null, "e": 3024, "s": 2851, "text": "We can see a comprehensive list of matplotlib parameter settings and their default values, and the parameters are organized into groups such as lines, markers, patch, text." }, { "code": null, "e": 3148, "s": 3024, "text": "Below is a minimalism example (named signature.mplstyle)built on top of the built-in style sheetseaborn-colorblind.mplstyle" }, { "code": null, "e": 3303, "s": 3148, "text": "If we have write privilege to the abovementioned path for stylelib, we can put the custom style sheet into the same folder and invoke the style sheet with" }, { "code": null, "e": 3490, "s": 3303, "text": "# Scenario 1: Apply globally to a jupyter notebookplt.style.use(“signature”)# Scenario 2: Apply locally with context managerwith plt.style.context(\"signature\"): plt.plot([1, 2, 3, 4])" }, { "code": null, "e": 3715, "s": 3490, "text": "If we don’t have the write privilege, the only extra thing we would need to do is to include the full path of the custom style sheet. Here we use a simple example of directly storing the style sheet under the home directory:" }, { "code": null, "e": 3932, "s": 3715, "text": "# Scenario 1: Apply globally to a jupyter notebookplt.style.use(“/home/signature.mplstyle”)# Scenario 2: Apply locally with context managerwith plt.style.context(\"/home/signature.mplstyle\"): plt.plot([1, 2, 3, 4])" }, { "code": null, "e": 4053, "s": 3932, "text": "There could be cases when we want to recover the default styling. There are at two ways to recover the default settings:" }, { "code": null, "e": 4079, "s": 4053, "text": "Reset via rcParams.update" }, { "code": null, "e": 4105, "s": 4079, "text": "Reset via rcParams.update" }, { "code": null, "e": 4170, "s": 4105, "text": "import matplotlib as mplmpl.rcParams.update(mpl.rcParamsDefault)" }, { "code": null, "e": 4204, "s": 4170, "text": "2. Reset with default style sheet" }, { "code": null, "e": 4229, "s": 4204, "text": "plt.style.use('default')" }, { "code": null, "e": 4338, "s": 4229, "text": "Here we penguin dataset as an example to demonstrate the effect of the custom style sheet signaure.mplstyle." }, { "code": null, "e": 4457, "s": 4338, "text": "import matplotlib.pyplot as pltimport seaborn as sns# Load the penguins datasetpenguins = sns.load_dataset(\"penguins\")" }, { "code": null, "e": 4475, "s": 4457, "text": "Use default style" }, { "code": null, "e": 4493, "s": 4475, "text": "Use default style" }, { "code": null, "e": 4761, "s": 4493, "text": "plt.style.use(\"default\")# Show the joint distribution using kernel density estimationg = sns.jointplot( data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\", hue=\"species\", kind=\"kde\",)g.fig.suptitle(\"Styled With Default Style Sheet\", y=1.01)plt.show()" }, { "code": null, "e": 4807, "s": 4761, "text": "2. Use custom style set in signature.mplstyle" }, { "code": null, "e": 5076, "s": 4807, "text": "plt.style.use(\"signature\")# Show the joint distribution using kernel density estimationg = sns.jointplot( data=penguins, x=\"bill_length_mm\", y=\"bill_depth_mm\", hue=\"species\", kind=\"kde\",)g.fig.suptitle(\"Styled With Custom Style Sheet\", y=1.01)plt.show()" }, { "code": null, "e": 5335, "s": 5076, "text": "Beautiful data deserves beautiful presentations. But instead of typing chunks of styling codes repetitively, a bit upfront time investment in setting up our own custom style sheet (file extension .mplstyle) could both save time and ensure styling consistency" }, { "code": null, "e": 5538, "s": 5335, "text": "To build custom style sheets, we could start with built-in style sheets and custom them further to our liking. One key step is to locate these style sheets with the help of matplotlib.matplotlib_fname()" } ]
How to use the Entry widget in Tkinter?
The Entry widget is a single-line text widget defined in Tcl/Tk toolkit. We can use the Entry widget to accept and display single-line user input. In order to use the Entry widget, you have to first create an Entry widget using the constructor Entry(parent, width, **options). Once we've defined our Entry widget, we can configure its properties such as font-properties, color, width, etc., using the configure() method. Let use create an Entry widget to accept the username and display it in the window. # Import the required libraries from tkinter import * # Create an instance of tkinter frame or window win = Tk() # Set the size of the tkinter window win.geometry("700x350") def show_name(): # Create a Label widget label = Label(win, text="Hello " + str(entry.get()) + "👋", font=('Calibri 25')).pack(pady=20) entry.delete(0, END) # Create a Label Label(win, text="Enter Your Name").pack() # Create an Entry widget entry = Entry(win, width=25) entry.pack(pady=20) Button(win, text="Submit", command=show_name).pack() win.mainloop() When you run the above code, it will display a window with an Entry widget and a button. Type your name in the given Entry widget and click the button to show the message on the window.
[ { "code": null, "e": 1209, "s": 1062, "text": "The Entry widget is a single-line text widget defined in Tcl/Tk toolkit. We can use the Entry widget to accept and display single-line user input." }, { "code": null, "e": 1483, "s": 1209, "text": "In order to use the Entry widget, you have to first create an Entry widget using the constructor Entry(parent, width, **options). Once we've defined our Entry widget, we can configure its properties such as font-properties, color, width, etc., using the configure() method." }, { "code": null, "e": 1567, "s": 1483, "text": "Let use create an Entry widget to accept the username and display it in the window." }, { "code": null, "e": 2114, "s": 1567, "text": "# Import the required libraries\nfrom tkinter import *\n\n# Create an instance of tkinter frame or window\nwin = Tk()\n\n# Set the size of the tkinter window\nwin.geometry(\"700x350\")\n\ndef show_name():\n # Create a Label widget\n label = Label(win, text=\"Hello \" + str(entry.get()) + \"👋\", font=('Calibri 25')).pack(pady=20)\n entry.delete(0, END)\n\n# Create a Label\nLabel(win, text=\"Enter Your Name\").pack()\n\n# Create an Entry widget\nentry = Entry(win, width=25)\nentry.pack(pady=20)\n\nButton(win, text=\"Submit\", command=show_name).pack()\n\nwin.mainloop()" }, { "code": null, "e": 2300, "s": 2114, "text": "When you run the above code, it will display a window with an Entry widget and a button. Type your name in the given Entry widget and click the button to show the message on the window." } ]
On ROC and Precision-Recall curves | by Carlos Azevedo | Towards Data Science
In machine learning, when facing binary classification problems, there are two main metric tools that every data scientist uses: Receiver Operating Characteristic (ROC) curve and Precision-Recall (PR) curve. The main goal of this article is to cover how to interpret these curves along with their inherent confusion matrices and thresholds. We start by covering the raw data for these curves: the confusion matrix. Then we go through the actual curves and to finish, we show how these curves could look like when the problem is not properly set up. The Confusion Matrix is the raw data for everything we will be showing here: it’s a table that contains the number of True Positives (TP), True Negatives (TN), False Positives (FP), and False Negatives (FN). The advantage of using ROC and PR curves is that they summarise performance information that is relevant to binary classification problems. It makes it easier to read and to interpret compared to having several confusion matrices — one for every threshold — and then compute some ratios to have glimpse of what those numbers (TP, TN, FP, FN) mean. And voilá, we just defined what ROC and PR curves represent — ratios of numbers we get from several confusion matrices. The Confusion Matrix supports several classes but in this article, we will focus on the binary classification problem. | predicted negative | predicted positive ||-----------------|---------------------|---------------------|| actual negative | True Negative (TN) | False Positive (FP) || actual positive | False Negative (FN) | True Positive (TP) |True Positives (TP): Positive samples predicted as positiveTrue Negatives (TN): Negative samples predicted as negativeFalse Positives (FP): Negative samples predicted as positiveFalse Negatives (FN): Positive samples predicted as negative The Confusion Matrix as it is is perfectly fine when dealing with balanced data sets. It’s when we are working with imbalanced data sets that we need a more sophisticated evaluation metric that allows us to reason clearly about the trade-offs. Wikipedia has a great page on all the metrics regarding binary classification. I find it confusing that there are several names for the same metric. Here I’ll list mainly the ones that matter for this article with the variations that are most commonly used: Negatives (N): Total number of negative samples.N = FP + TNTrue Positive Rate (TPR): ratio of correct positive predictions to the overral number of positive examples in the dataset.TPR = Recall = Sensitivity = TP / PFalse Positive Rate (FPR): ratio of correct negative predictions to the overral number of negative samples in the dataset.FPR = 1 - Specificity = FP / NPrecision: From the positive predictions what proportion of it is correct.Precision = TP / (TP + FP)Important: Note that the y-axis of the ROC curve (Sensitivity) is the same as the x-axis of the PR curve (Recall). Left plot: Along the y-axis, we have the score while the x-axis just helps with the visualization by making it more spread so we can easily see the score data points. There are 5 different horizontal lines that represent different thresholds: below this line, all the data points are classified as negative (class 0) and if the data point is above the line or at the same score it is classified as positive (class 1). Each of these lines has a different color in order to map them into the other two plots: ROC and PR curves. Top right plot: This is the ROC curve. The x-axis is the FPR and the y-axis is the Sensitivity (or Recall or TPR). As the threshold on the left plot goes from the bottom to top the ROC curve develops from right to left. Each data point in this plot represents a different threshold that at each step turns a positive prediction into a negative prediction.The goal in ROC space is to be in the upper-left-hand corner — that is the point (0, 1) meaning that we have zero False Positives (FPR=0) and that we classified all positives as positive (Recall=1). The diagonal dashed line (the “curve” for a no-skill classifier2) is what we have, on average, when drawing randomly scores on the unit interval3 or if our predictions are all 0 or all 1. Bottom right plot: This is the PR curve. Both the x-axis of the PR curve and the y-axis of the ROC curve stand for Recall so we see that they develop similarly. This curve focuses mainly on the performance of the positive class which is crucial when dealing with imbalanced classes. In the PR space, the goal is to be in the upper-right-hand corner — the top right corner (1, 1) means that we classified all positives as positive (Recall=1) and that everything we are classifying as positive is true positive (Precision=1) — the latter translates to zero False Positives. In this case, the “curve” for a no-skill classifier2 is a horizontal line obtained by P/(N+P) which is represented by the dashed line — it the case where the classifier always predicts the minority class, i.e. positive. Each point in the ROC space or PR space represents a specific threshold that changes the confusion matrix (TP, TN, FP, FN) and thus the Recall, Precision, and FPR. There is generally a trade-off between precision and recall, which is determined by the threshold that separates the positive cases from the negative cases — this trade-off is generally discussed with the business decision-makers to make a final decision on where it should sit. Another dummy example follows where we are not able to get a perfect separation through thresholding: Lets put into practice what we just learned and look at the following animation that will serve as the template for what’s coming next: Notice how the threshold always jumps to the next sample: this is because in between samples the metrics are kept the same — so the lines connecting the points in the ROC and PR curves are meaningless. The distance in between points in the ROC curve is constant: it only depends on the total number of samples — one dot per sample as long as no score is exactly the same, then moving the threshold changes the decision for two data points. The distance in between points in the PR curve changes with the direction: if the step is moving horizontally (Recall) then it is constant as it is with the ROC curve. With vertical steps (Precision) it depends on how many negative samples there are — high number of False Positives (FP) leads to smaller steps — Precision = TP / (TP + FP). By design the ROC curve always develops in a U-shape unless there’s something wrong — so regarding the animation above, as the threshold goes up, there are only two options: step to the left or downwards. Step left: Turn a False Positive (blue cross) into a True Negative (blue dot). This behavior represents a correct decision and thus it reduces the False Positive Rate (x-axis). It is easily observed when the threshold is at the bottom moving from -1.5 up to -0.5 where every transition reduces the number False Positives successively.Step downwards: Turn a True Positive (orange dot) into a False Negative (blue cross). This behavior represents a wrong decision and thus it reduces the Recall (y-axis). It is easily observed when the threshold is at 0.5 up to 1.5 where every transition is wrongly classifying positive samples as negative. Step left: Turn a False Positive (blue cross) into a True Negative (blue dot). This behavior represents a correct decision and thus it reduces the False Positive Rate (x-axis). It is easily observed when the threshold is at the bottom moving from -1.5 up to -0.5 where every transition reduces the number False Positives successively. Step downwards: Turn a True Positive (orange dot) into a False Negative (blue cross). This behavior represents a wrong decision and thus it reduces the Recall (y-axis). It is easily observed when the threshold is at 0.5 up to 1.5 where every transition is wrongly classifying positive samples as negative. So far we looked into two examples that have one thing in common: both data sets were perfectly balanced — the same number of positive and negative samples. Where the PR curve shines compared with the ROC curve is when we are dealing with imbalanced datasets and we are interested in the minority class. So let us look at an example. Judging by the ROC curve we could be overly optimistic about our classifier — there are several thresholds we can pick from that have performance. Nevertheless, the PR curve tells us a different story — as does the plot with the data points. With large skew in the class distribution, PR curves are more insightful regarding an algorithm’s performance1: when the number of negative samples greatly exceeds the number of positive samples, a large change in the number of false positives can lead to a small change in the false positive rate used in ROC analysis. Precision, on the other hand, by comparing false positives to true positives rather than true negatives, captures the effect of a large number of negative samples on the algorithm’s performance. The way we decide on which curve we want to optimize is context-dependant. If we are dealing with fraud detection, then optimizing for the PR curve gives the most benefit by flagging fraud without overloading the checks for false positives, whereas if we are dealing with let’s say cancer detection, there’s a high cost on false negatives and thus optimizing over the ROC curve is preferable — Nevertheless, it requires business expertise in order to decide on where should the algorithm stand in the trade-off. Here we will show two other scenarios that are not seen that often, the reason being that it means the problem was wrongly formulated — so we will still see it when we do something wrong and it is a good reminder of what it should not look like. Classes are set the other way around: what is positive should be negative and vice-versa. This is easily identified by the ROC curve — whenever the curve is on the wrong side of the diagonal it means we got the labels wrong. The minority class is wrongly set as the negative class. By definition the class of interest, what we call the positive class, is the minority class. This is easily identified by the PR curve where we see that at Recall=1 the precision is 0.9 which tells us the data class imbalance is towards class 1. And here is what it looks like when we get both wrong: the labels and the minority class. Here both curves tell us that there’s something odd — both scenarios above show up. I hope this post made you more familiar with both the ROC curve and the PR curve in a way that it is possible to infer knowledge about the data and the classifier itself. Let me know if you feel that something is missing and that it would make sense to add to this post. I’m always open to explore the foundations in detail. Here’s the github repo used to create the content for this post. References [1] Davis, Jesse, and Mark Goadrich. “The relationship between Precision-Recall and ROC curves.” Proceedings of the 23rd international conference on Machine learning. 2006.
[ { "code": null, "e": 380, "s": 172, "text": "In machine learning, when facing binary classification problems, there are two main metric tools that every data scientist uses: Receiver Operating Characteristic (ROC) curve and Precision-Recall (PR) curve." }, { "code": null, "e": 513, "s": 380, "text": "The main goal of this article is to cover how to interpret these curves along with their inherent confusion matrices and thresholds." }, { "code": null, "e": 721, "s": 513, "text": "We start by covering the raw data for these curves: the confusion matrix. Then we go through the actual curves and to finish, we show how these curves could look like when the problem is not properly set up." }, { "code": null, "e": 1517, "s": 721, "text": "The Confusion Matrix is the raw data for everything we will be showing here: it’s a table that contains the number of True Positives (TP), True Negatives (TN), False Positives (FP), and False Negatives (FN). The advantage of using ROC and PR curves is that they summarise performance information that is relevant to binary classification problems. It makes it easier to read and to interpret compared to having several confusion matrices — one for every threshold — and then compute some ratios to have glimpse of what those numbers (TP, TN, FP, FN) mean. And voilá, we just defined what ROC and PR curves represent — ratios of numbers we get from several confusion matrices. The Confusion Matrix supports several classes but in this article, we will focus on the binary classification problem." }, { "code": null, "e": 2008, "s": 1517, "text": " | predicted negative | predicted positive ||-----------------|---------------------|---------------------|| actual negative | True Negative (TN) | False Positive (FP) || actual positive | False Negative (FN) | True Positive (TP) |True Positives (TP): Positive samples predicted as positiveTrue Negatives (TN): Negative samples predicted as negativeFalse Positives (FP): Negative samples predicted as positiveFalse Negatives (FN): Positive samples predicted as negative" }, { "code": null, "e": 2252, "s": 2008, "text": "The Confusion Matrix as it is is perfectly fine when dealing with balanced data sets. It’s when we are working with imbalanced data sets that we need a more sophisticated evaluation metric that allows us to reason clearly about the trade-offs." }, { "code": null, "e": 2510, "s": 2252, "text": "Wikipedia has a great page on all the metrics regarding binary classification. I find it confusing that there are several names for the same metric. Here I’ll list mainly the ones that matter for this article with the variations that are most commonly used:" }, { "code": null, "e": 3093, "s": 2510, "text": "Negatives (N): Total number of negative samples.N = FP + TNTrue Positive Rate (TPR): ratio of correct positive predictions to the overral number of positive examples in the dataset.TPR = Recall = Sensitivity = TP / PFalse Positive Rate (FPR): ratio of correct negative predictions to the overral number of negative samples in the dataset.FPR = 1 - Specificity = FP / NPrecision: From the positive predictions what proportion of it is correct.Precision = TP / (TP + FP)Important: Note that the y-axis of the ROC curve (Sensitivity) is the same as the x-axis of the PR curve (Recall)." }, { "code": null, "e": 3619, "s": 3093, "text": "Left plot: Along the y-axis, we have the score while the x-axis just helps with the visualization by making it more spread so we can easily see the score data points. There are 5 different horizontal lines that represent different thresholds: below this line, all the data points are classified as negative (class 0) and if the data point is above the line or at the same score it is classified as positive (class 1). Each of these lines has a different color in order to map them into the other two plots: ROC and PR curves." }, { "code": null, "e": 4361, "s": 3619, "text": "Top right plot: This is the ROC curve. The x-axis is the FPR and the y-axis is the Sensitivity (or Recall or TPR). As the threshold on the left plot goes from the bottom to top the ROC curve develops from right to left. Each data point in this plot represents a different threshold that at each step turns a positive prediction into a negative prediction.The goal in ROC space is to be in the upper-left-hand corner — that is the point (0, 1) meaning that we have zero False Positives (FPR=0) and that we classified all positives as positive (Recall=1). The diagonal dashed line (the “curve” for a no-skill classifier2) is what we have, on average, when drawing randomly scores on the unit interval3 or if our predictions are all 0 or all 1." }, { "code": null, "e": 5153, "s": 4361, "text": "Bottom right plot: This is the PR curve. Both the x-axis of the PR curve and the y-axis of the ROC curve stand for Recall so we see that they develop similarly. This curve focuses mainly on the performance of the positive class which is crucial when dealing with imbalanced classes. In the PR space, the goal is to be in the upper-right-hand corner — the top right corner (1, 1) means that we classified all positives as positive (Recall=1) and that everything we are classifying as positive is true positive (Precision=1) — the latter translates to zero False Positives. In this case, the “curve” for a no-skill classifier2 is a horizontal line obtained by P/(N+P) which is represented by the dashed line — it the case where the classifier always predicts the minority class, i.e. positive." }, { "code": null, "e": 5317, "s": 5153, "text": "Each point in the ROC space or PR space represents a specific threshold that changes the confusion matrix (TP, TN, FP, FN) and thus the Recall, Precision, and FPR." }, { "code": null, "e": 5596, "s": 5317, "text": "There is generally a trade-off between precision and recall, which is determined by the threshold that separates the positive cases from the negative cases — this trade-off is generally discussed with the business decision-makers to make a final decision on where it should sit." }, { "code": null, "e": 5698, "s": 5596, "text": "Another dummy example follows where we are not able to get a perfect separation through thresholding:" }, { "code": null, "e": 5834, "s": 5698, "text": "Lets put into practice what we just learned and look at the following animation that will serve as the template for what’s coming next:" }, { "code": null, "e": 6036, "s": 5834, "text": "Notice how the threshold always jumps to the next sample: this is because in between samples the metrics are kept the same — so the lines connecting the points in the ROC and PR curves are meaningless." }, { "code": null, "e": 6274, "s": 6036, "text": "The distance in between points in the ROC curve is constant: it only depends on the total number of samples — one dot per sample as long as no score is exactly the same, then moving the threshold changes the decision for two data points." }, { "code": null, "e": 6615, "s": 6274, "text": "The distance in between points in the PR curve changes with the direction: if the step is moving horizontally (Recall) then it is constant as it is with the ROC curve. With vertical steps (Precision) it depends on how many negative samples there are — high number of False Positives (FP) leads to smaller steps — Precision = TP / (TP + FP)." }, { "code": null, "e": 6820, "s": 6615, "text": "By design the ROC curve always develops in a U-shape unless there’s something wrong — so regarding the animation above, as the threshold goes up, there are only two options: step to the left or downwards." }, { "code": null, "e": 7460, "s": 6820, "text": "Step left: Turn a False Positive (blue cross) into a True Negative (blue dot). This behavior represents a correct decision and thus it reduces the False Positive Rate (x-axis). It is easily observed when the threshold is at the bottom moving from -1.5 up to -0.5 where every transition reduces the number False Positives successively.Step downwards: Turn a True Positive (orange dot) into a False Negative (blue cross). This behavior represents a wrong decision and thus it reduces the Recall (y-axis). It is easily observed when the threshold is at 0.5 up to 1.5 where every transition is wrongly classifying positive samples as negative." }, { "code": null, "e": 7795, "s": 7460, "text": "Step left: Turn a False Positive (blue cross) into a True Negative (blue dot). This behavior represents a correct decision and thus it reduces the False Positive Rate (x-axis). It is easily observed when the threshold is at the bottom moving from -1.5 up to -0.5 where every transition reduces the number False Positives successively." }, { "code": null, "e": 8101, "s": 7795, "text": "Step downwards: Turn a True Positive (orange dot) into a False Negative (blue cross). This behavior represents a wrong decision and thus it reduces the Recall (y-axis). It is easily observed when the threshold is at 0.5 up to 1.5 where every transition is wrongly classifying positive samples as negative." }, { "code": null, "e": 8435, "s": 8101, "text": "So far we looked into two examples that have one thing in common: both data sets were perfectly balanced — the same number of positive and negative samples. Where the PR curve shines compared with the ROC curve is when we are dealing with imbalanced datasets and we are interested in the minority class. So let us look at an example." }, { "code": null, "e": 9192, "s": 8435, "text": "Judging by the ROC curve we could be overly optimistic about our classifier — there are several thresholds we can pick from that have performance. Nevertheless, the PR curve tells us a different story — as does the plot with the data points. With large skew in the class distribution, PR curves are more insightful regarding an algorithm’s performance1: when the number of negative samples greatly exceeds the number of positive samples, a large change in the number of false positives can lead to a small change in the false positive rate used in ROC analysis. Precision, on the other hand, by comparing false positives to true positives rather than true negatives, captures the effect of a large number of negative samples on the algorithm’s performance." }, { "code": null, "e": 9704, "s": 9192, "text": "The way we decide on which curve we want to optimize is context-dependant. If we are dealing with fraud detection, then optimizing for the PR curve gives the most benefit by flagging fraud without overloading the checks for false positives, whereas if we are dealing with let’s say cancer detection, there’s a high cost on false negatives and thus optimizing over the ROC curve is preferable — Nevertheless, it requires business expertise in order to decide on where should the algorithm stand in the trade-off." }, { "code": null, "e": 9950, "s": 9704, "text": "Here we will show two other scenarios that are not seen that often, the reason being that it means the problem was wrongly formulated — so we will still see it when we do something wrong and it is a good reminder of what it should not look like." }, { "code": null, "e": 10175, "s": 9950, "text": "Classes are set the other way around: what is positive should be negative and vice-versa. This is easily identified by the ROC curve — whenever the curve is on the wrong side of the diagonal it means we got the labels wrong." }, { "code": null, "e": 10478, "s": 10175, "text": "The minority class is wrongly set as the negative class. By definition the class of interest, what we call the positive class, is the minority class. This is easily identified by the PR curve where we see that at Recall=1 the precision is 0.9 which tells us the data class imbalance is towards class 1." }, { "code": null, "e": 10652, "s": 10478, "text": "And here is what it looks like when we get both wrong: the labels and the minority class. Here both curves tell us that there’s something odd — both scenarios above show up." }, { "code": null, "e": 10977, "s": 10652, "text": "I hope this post made you more familiar with both the ROC curve and the PR curve in a way that it is possible to infer knowledge about the data and the classifier itself. Let me know if you feel that something is missing and that it would make sense to add to this post. I’m always open to explore the foundations in detail." }, { "code": null, "e": 11042, "s": 10977, "text": "Here’s the github repo used to create the content for this post." }, { "code": null, "e": 11053, "s": 11042, "text": "References" } ]
Voice search Wikipedia using Python - GeeksforGeeks
23 Jan, 2020 Every day, we visit so many applications, be it messaging platforms like Messenger, Telegram or ordering products on Amazon, Flipkart, or knowing about weather and the list can go on. And we see that these websites have their own software program for initiating conversations with human beings using rules or artificial intelligence. Users interact with the software program via a conversational interface through written or spoken text. This can be referred to as an assistant. Example: Input: what is coding Output: What/If (stylized as WHAT/ IF) is an American thriller web television miniseries, created by Mike Kelley, that premiered on May 24, 2019, on Netflix. The series stars Renée Zellweger, Jane Levy, Blake Jenner, Daniella Pineda, Keith Powers, Samantha Ware, Dave Annable, Saamer Usmani, John Clarence Stewart and Louis Herthum. == Premise ==What/If is a neo-noir thriller that explores “the ripple effects of what happens when acceptable people start doing unacceptable things.User: An assistant can be made using Natural Language Processing(NLP) one of the most promising fields of artificial intelligence that uses natural languages to enable human interactions with machines. There are two main approaches to NLP: rule-based methods: That follow some pre specified rules and answer as per those rules.statistical methods: i.e. methods related to machine learning that learn on their own according to user inputs. rule-based methods: That follow some pre specified rules and answer as per those rules. statistical methods: i.e. methods related to machine learning that learn on their own according to user inputs. And this article will learn about how to create your own assistant using statistical methods. To create an assistant, we’ll use the Python programming language, for it has all the modules required for building it. Secondly, Python is easy to understand, even if you don’t have much experience with programming. Before, getting into the actual code, we need to understand, that this chatbot or assistant will be voice-based, so we need to import the following modules. pyttsx3: A python package that supports common text to speech engines on Mac OS, Windows and Linux. speech_recognition: Library for performing speech recognition, with support for several engines and APIs, like CMU Sphinx, Microsoft Bing Voice Recognition, Google Cloud Speech API etc. wolframalpha: Python’s support library for WolframAlpha computational intelligence . wikipedia: Python’s library that makes it easy to access and parse data from Wikipedia. To install the above modules on your system, use the following : pip install pyttsx3 pip install SpeechRecognition pip install wolframalpha pip install wikipedia Since, this chatbot uses WolframAlpha API to find answers, the user must create a free account by signing up at . Follow the steps required to set up a student account that is free and is for personal use only. Generate your app-id and copy it for further reference. Speech Recognition: Speech recognition is the ability of a machine or program to identify words and phrases in spoken language and convert them to a machine-readable format. TTS – text to speech: a form of speech synthesis that converts text into spoken voice output. Computational Knowledge Integration: Integrating your bot with computational knowledge intelligence using Wolfram|Alpha. Below is the implementation. # Python package supporting common text-to-speech enginesimport pyttsx3 # For understanding speechimport speech_recognition as sr # For fetching the answers # to computational queriesimport wolframalpha # for fetching wikipedia articlesimport wikipedia # Function to search the query# that is either entered or spoken# by userdef search(query): # try is used for searching with wolframAlpha try: # Generate your App ID from WolframAlpha app_id = "Your WolframAlpha App ID here" client = wolframalpha.Client(app_id) res = client.query(query) answer = next(res.results).text print(answer) SpeakText("Your answer is " + answer) # If the query cannot be searched using # WolframAlpha then it is searched in # wikipedia except: query = query.split(' ') query = " ".join(query[0:]) SpeakText("I am searching for " + query) print(wikipedia.summary(query, sentences = 3)) SpeakText(wikipedia.summary(query, sentences = 3)) # Function to convert text to # speech def SpeakText(command): # Initialize the engine engine = pyttsx3.init() engine.say(command) engine.runAndWait() # Driver's code# input query from the user by # typing or by voicequery = input()query = query.lower() # if query is blank then user # is prompted to speak something.if query == '': r = sr.Recognizer() # uses the default microphone # as the source to record voice with sr.Microphone() as source: print("Say Something ") # reduces the background disturbances # and noise for 2 seconds r.adjust_for_ambient_noise(source, 2) # listening to source audio = r.listen(source) try: speech = r.recognize_google(audio) search(speech) # Handling Exceptions if speech # is not understood. except sr.UnknownValueError: print("Google Speech Recognition could not \ understand audio") # Couldn't handle requests, occurs # mainly because of network errors except sr.RequestError as e: print("Could not request results from Google \ Speech Recognition service;{0}".format(e))else: search(query) Output: Note: The voice output of the output text is also generated. python-utility Technical Scripter 2019 Python Technical Scripter 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": 25973, "s": 25945, "text": "\n23 Jan, 2020" }, { "code": null, "e": 26452, "s": 25973, "text": "Every day, we visit so many applications, be it messaging platforms like Messenger, Telegram or ordering products on Amazon, Flipkart, or knowing about weather and the list can go on. And we see that these websites have their own software program for initiating conversations with human beings using rules or artificial intelligence. Users interact with the software program via a conversational interface through written or spoken text. This can be referred to as an assistant." }, { "code": null, "e": 26461, "s": 26452, "text": "Example:" }, { "code": null, "e": 26483, "s": 26461, "text": "Input: what is coding" }, { "code": null, "e": 26817, "s": 26483, "text": "Output: What/If (stylized as WHAT/ IF) is an American thriller web television miniseries, created by Mike Kelley, that premiered on May 24, 2019, on Netflix. The series stars Renée Zellweger, Jane Levy, Blake Jenner, Daniella Pineda, Keith Powers, Samantha Ware, Dave Annable, Saamer Usmani, John Clarence Stewart and Louis Herthum." }, { "code": null, "e": 26972, "s": 26817, "text": "== Premise ==What/If is a neo-noir thriller that explores “the ripple effects of what happens when acceptable people start doing unacceptable things.User:" }, { "code": null, "e": 27168, "s": 26972, "text": "An assistant can be made using Natural Language Processing(NLP) one of the most promising fields of artificial intelligence that uses natural languages to enable human interactions with machines." }, { "code": null, "e": 27206, "s": 27168, "text": "There are two main approaches to NLP:" }, { "code": null, "e": 27405, "s": 27206, "text": "rule-based methods: That follow some pre specified rules and answer as per those rules.statistical methods: i.e. methods related to machine learning that learn on their own according to user inputs." }, { "code": null, "e": 27493, "s": 27405, "text": "rule-based methods: That follow some pre specified rules and answer as per those rules." }, { "code": null, "e": 27605, "s": 27493, "text": "statistical methods: i.e. methods related to machine learning that learn on their own according to user inputs." }, { "code": null, "e": 27699, "s": 27605, "text": "And this article will learn about how to create your own assistant using statistical methods." }, { "code": null, "e": 27916, "s": 27699, "text": "To create an assistant, we’ll use the Python programming language, for it has all the modules required for building it. Secondly, Python is easy to understand, even if you don’t have much experience with programming." }, { "code": null, "e": 28073, "s": 27916, "text": "Before, getting into the actual code, we need to understand, that this chatbot or assistant will be voice-based, so we need to import the following modules." }, { "code": null, "e": 28173, "s": 28073, "text": "pyttsx3: A python package that supports common text to speech engines on Mac OS, Windows and Linux." }, { "code": null, "e": 28359, "s": 28173, "text": "speech_recognition: Library for performing speech recognition, with support for several engines and APIs, like CMU Sphinx, Microsoft Bing Voice Recognition, Google Cloud Speech API etc." }, { "code": null, "e": 28444, "s": 28359, "text": "wolframalpha: Python’s support library for WolframAlpha computational intelligence ." }, { "code": null, "e": 28532, "s": 28444, "text": "wikipedia: Python’s library that makes it easy to access and parse data from Wikipedia." }, { "code": null, "e": 28597, "s": 28532, "text": "To install the above modules on your system, use the following :" }, { "code": null, "e": 28694, "s": 28597, "text": "pip install pyttsx3\npip install SpeechRecognition\npip install wolframalpha\npip install wikipedia" }, { "code": null, "e": 28961, "s": 28694, "text": "Since, this chatbot uses WolframAlpha API to find answers, the user must create a free account by signing up at . Follow the steps required to set up a student account that is free and is for personal use only. Generate your app-id and copy it for further reference." }, { "code": null, "e": 29135, "s": 28961, "text": "Speech Recognition: Speech recognition is the ability of a machine or program to identify words and phrases in spoken language and convert them to a machine-readable format." }, { "code": null, "e": 29229, "s": 29135, "text": "TTS – text to speech: a form of speech synthesis that converts text into spoken voice output." }, { "code": null, "e": 29350, "s": 29229, "text": "Computational Knowledge Integration: Integrating your bot with computational knowledge intelligence using Wolfram|Alpha." }, { "code": null, "e": 29379, "s": 29350, "text": "Below is the implementation." }, { "code": "# Python package supporting common text-to-speech enginesimport pyttsx3 # For understanding speechimport speech_recognition as sr # For fetching the answers # to computational queriesimport wolframalpha # for fetching wikipedia articlesimport wikipedia # Function to search the query# that is either entered or spoken# by userdef search(query): # try is used for searching with wolframAlpha try: # Generate your App ID from WolframAlpha app_id = \"Your WolframAlpha App ID here\" client = wolframalpha.Client(app_id) res = client.query(query) answer = next(res.results).text print(answer) SpeakText(\"Your answer is \" + answer) # If the query cannot be searched using # WolframAlpha then it is searched in # wikipedia except: query = query.split(' ') query = \" \".join(query[0:]) SpeakText(\"I am searching for \" + query) print(wikipedia.summary(query, sentences = 3)) SpeakText(wikipedia.summary(query, sentences = 3)) # Function to convert text to # speech def SpeakText(command): # Initialize the engine engine = pyttsx3.init() engine.say(command) engine.runAndWait() # Driver's code# input query from the user by # typing or by voicequery = input()query = query.lower() # if query is blank then user # is prompted to speak something.if query == '': r = sr.Recognizer() # uses the default microphone # as the source to record voice with sr.Microphone() as source: print(\"Say Something \") # reduces the background disturbances # and noise for 2 seconds r.adjust_for_ambient_noise(source, 2) # listening to source audio = r.listen(source) try: speech = r.recognize_google(audio) search(speech) # Handling Exceptions if speech # is not understood. except sr.UnknownValueError: print(\"Google Speech Recognition could not \\ understand audio\") # Couldn't handle requests, occurs # mainly because of network errors except sr.RequestError as e: print(\"Could not request results from Google \\ Speech Recognition service;{0}\".format(e))else: search(query) ", "e": 31717, "s": 29379, "text": null }, { "code": null, "e": 31725, "s": 31717, "text": "Output:" }, { "code": null, "e": 31786, "s": 31725, "text": "Note: The voice output of the output text is also generated." }, { "code": null, "e": 31801, "s": 31786, "text": "python-utility" }, { "code": null, "e": 31825, "s": 31801, "text": "Technical Scripter 2019" }, { "code": null, "e": 31832, "s": 31825, "text": "Python" }, { "code": null, "e": 31851, "s": 31832, "text": "Technical Scripter" }, { "code": null, "e": 31949, "s": 31851, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31967, "s": 31949, "text": "Python Dictionary" }, { "code": null, "e": 32002, "s": 31967, "text": "Read a file line by line in Python" }, { "code": null, "e": 32034, "s": 32002, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32056, "s": 32034, "text": "Enumerate() in Python" }, { "code": null, "e": 32098, "s": 32056, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 32128, "s": 32098, "text": "Iterate over a list in Python" }, { "code": null, "e": 32154, "s": 32128, "text": "Python String | replace()" }, { "code": null, "e": 32198, "s": 32154, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 32227, "s": 32198, "text": "*args and **kwargs in Python" } ]
Circular Prime Number | Practice | GeeksforGeeks
A prime number is a Circular Prime Number if all of its possible rotations are itself prime numbers. Now given a number N check if it is Circular Prime or Not. Example 1: Input: N = 197 Output: 1 Explanation: 197 is a Circular Prime because all rotations of 197 are 197, 719, 971 all of the 3 are prime number's hence 197 is a circular prime. Example 2: Input: N = 101 Output: 0 Explanation: 101 and 11 is prime but 110 is not a prime number. Your Task: You don't need to read or print anything. Your task is to complete the function isCircularPrime() which takes N as input parameter and returns 1 if it is Circular Prime otherwise returns 0. Expected Time Complexity: O(Nlog(log(N)) Expected Space Complexity: O(N) Constraints: 1 <= N <= 105 0 raunakgiri212 days ago C++ time=0.01s public:int highPow(int n){ int count=0; while(n) { count++; n=n/10; } return count;}bool isPrime(int n){ if(n<=1)return 0; for(int i=2;i<=sqrt(n);i++) { if(n%i==0)return 0; } return 1;}int isCircularPrime(int n) { // Code here if(!isPrime(n))return 0; if(!n/10)return 1; int p=highPow(n); int m=n; for(int i=0;i<p;i++) { m=m/10+(m%10)*pow(10,p-1); if(!isPrime(m))return 0; } return 1;} +1 ozodtagoev2 months ago C++ solution. Time: O(sqrt(N)*log(N)), Space: O(1) bool isPrime(int n) { if(n <= 1) return false; for(int i = 2; i*i <= n; i++) if(n%i == 0) return false; return true; } int isCircularPrime(int n) { // Code here if(n <= 1) return 0; int digitCount = ceil(log10(n)); int p = digitCount-1; while(digitCount--) { if(!isPrime(n)) return 0; n = (n%10*pow(10,p)) + n/10; } return 1; } -1 ncln538jsgdizpte5utrdkgdmv73rde23vovyyh52 months ago v.push_back(n); 0 immodi_303 months ago c++ soln bool isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } int isCircularPrime(int n) { string s = to_string(n); int nn=s.length(); if(isPrime(n)==false) return 0; if(s.size() ==1) return 1; for(int i=0;i<nn-1;i++) { string lst; lst = s[s.length()-1]; s=s.substr(0,s.length()-1); //cout<<lst <<" "<<s<<" "<<endl; s= lst+s; //this appoints s as 7 19 then 9 71 then main last 1 97 but we dont need to check that stringstream geek(s); int x; geek>>x; if(isPrime(x)==false) return 0; } return 1; } 0 aloksinghbais025 months ago public:bool isPrime[100001];Solution(){ memset(isPrime,true,sizeof(isPrime));}void precomputation(){ for(int num=2; num<=100000; num++){ long long int j = 1LL*num*num; if(j>100000) return; for(int d=num*num; d<=100000; d+=num){ isPrime[d] = false; } }}int convertToInt(vector<int> v){ int num = 0; int base = 1; for(int i=v.size()-1; i>=0; i--){ num += v[i]*base; base *= 10; } return (num);}bool checkAllRotations(int num){ if(!isPrime[num]) return (false); int temp = num; vector<int> dnum; while(temp > 0){ dnum.push_back(temp%10); temp /= 10; } reverse(dnum.begin(),dnum.end()); int sz = dnum.size(); for(int cnt=1; cnt<sz; cnt++){ int last = dnum[sz-1]; for(int i=sz-1; i>0; i--) dnum[i] = dnum[i-1]; dnum[0] = last; int temp = convertToInt(dnum); if(!isPrime[temp]) return (false); } return (true);}int isCircularPrime(int n) { if(n==1) return(false); precomputation(); return (checkAllRotations(n) ? 1 : 0);} +1 aloksinghbais02 This comment was deleted. 0 anutiger6 months ago vector<int> dp(1e5 + 1,1); for(int i = 2; i <= 1e5; i++){ if(dp[i] == 1){ int j = 2; while(i * j <= 1e5){ dp[i * j] = 0; j++; } } } int size = 0; int s = to_string(n).length(); if(dp[n] == 0 or n == 1) return 0; while(size < s){ int a = n % 10; n/= 10; n += (a * pow(10, s - 1)); size++; if(dp[n] == 0) return 0; } return 1; 0 humblefool2point0 This comment was deleted. -1 siddharthdhaka146 months ago class Solution { public int isCircularPrime(int n) { if(n == 1) return 0; if(n == 2) return 1; int nn = n; while(true){ if(!primeChecker(nn)) return 0; nn = (int)nn%10 * (int)java.lang.Math.pow(10,(int)java.lang.Math.log10(nn)) + (int)nn/10; if(nn == n) break; } return 1; } public boolean primeChecker(int n){ int sqroot1 = (int)java.lang.Math.sqrt(n) + 1; for (int i = 2; i <= sqroot1; i++){ if(n%i == 0) return false; } return true; } } 0 harsheopro6 months ago public:bool isprime(int n){ for(int i=2;i<n;i++){ if(n%i==0) return false; } return true;}int isCircularPrime(int n) { if(n==1) return 0; int d=n; int count =0; int p=1; while(d!=0){ int r=d%10; count++; p*=10; d/=10; } for(int i=0;i<count;i++){ if(isprime(n)){ } else return 0; n=(n%10)*(p/10)+(n/10); } return 1;}}; 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": 400, "s": 238, "text": "A prime number is a Circular Prime Number if all of its possible rotations are itself prime numbers. Now given a number N check if it is Circular Prime or Not.\n " }, { "code": null, "e": 411, "s": 400, "text": "Example 1:" }, { "code": null, "e": 586, "s": 411, "text": "Input: N = 197\nOutput: 1\nExplanation: 197 is a Circular Prime because\nall rotations of 197 are 197, 719, 971 all of \nthe 3 are prime number's hence 197 is a \ncircular prime.\n" }, { "code": null, "e": 597, "s": 586, "text": "Example 2:" }, { "code": null, "e": 687, "s": 597, "text": "Input: N = 101\nOutput: 0\nExplanation: 101 and 11 is prime but 110 is\nnot a prime number.\n" }, { "code": null, "e": 892, "s": 689, "text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function isCircularPrime() which takes N as input parameter and returns 1 if it is Circular Prime otherwise returns 0.\n " }, { "code": null, "e": 967, "s": 892, "text": "Expected Time Complexity: O(Nlog(log(N))\nExpected Space Complexity: O(N)\n " }, { "code": null, "e": 994, "s": 967, "text": "Constraints:\n1 <= N <= 105" }, { "code": null, "e": 996, "s": 994, "text": "0" }, { "code": null, "e": 1019, "s": 996, "text": "raunakgiri212 days ago" }, { "code": null, "e": 1034, "s": 1019, "text": "C++ time=0.01s" }, { "code": null, "e": 1514, "s": 1036, "text": "public:int highPow(int n){ int count=0; while(n) { count++; n=n/10; } return count;}bool isPrime(int n){ if(n<=1)return 0; for(int i=2;i<=sqrt(n);i++) { if(n%i==0)return 0; } return 1;}int isCircularPrime(int n) { // Code here if(!isPrime(n))return 0; if(!n/10)return 1; int p=highPow(n); int m=n; for(int i=0;i<p;i++) { m=m/10+(m%10)*pow(10,p-1); if(!isPrime(m))return 0; } return 1;}" }, { "code": null, "e": 1517, "s": 1514, "text": "+1" }, { "code": null, "e": 1540, "s": 1517, "text": "ozodtagoev2 months ago" }, { "code": null, "e": 1592, "s": 1540, "text": "C++ solution. Time: O(sqrt(N)*log(N)), Space: O(1)" }, { "code": null, "e": 1977, "s": 1592, "text": "bool isPrime(int n) {\n if(n <= 1) return false;\n for(int i = 2; i*i <= n; i++) if(n%i == 0) return false;\n return true;\n}\nint isCircularPrime(int n) {\n // Code here\n if(n <= 1) return 0;\n int digitCount = ceil(log10(n));\n int p = digitCount-1;\n while(digitCount--) {\n if(!isPrime(n)) return 0;\n n = (n%10*pow(10,p)) + n/10;\n }\n return 1;\n}\n" }, { "code": null, "e": 1980, "s": 1977, "text": "-1" }, { "code": null, "e": 2033, "s": 1980, "text": "ncln538jsgdizpte5utrdkgdmv73rde23vovyyh52 months ago" }, { "code": null, "e": 2055, "s": 2033, "text": " v.push_back(n); " }, { "code": null, "e": 2057, "s": 2055, "text": "0" }, { "code": null, "e": 2079, "s": 2057, "text": "immodi_303 months ago" }, { "code": null, "e": 2088, "s": 2079, "text": "c++ soln" }, { "code": null, "e": 3118, "s": 2088, "text": "bool isPrime(int n)\n {\n // Corner cases\n if (n <= 1)\n return false;\n if (n <= 3)\n return true;\n \n // This is checked so that we can skip\n // middle five numbers in below loop\n if (n % 2 == 0 || n % 3 == 0)\n return false;\n \n for (int i = 5; i * i <= n; i = i + 6)\n if (n % i == 0 || n % (i + 2) == 0)\n return false;\n \n return true;\n }\n \n\tint isCircularPrime(int n) \n\t{\n\t string s = to_string(n);\n\t int nn=s.length();\n\t \n\t if(isPrime(n)==false)\n\t return 0;\n\t \n\t if(s.size() ==1)\n\t return 1;\n\t \n\t for(int i=0;i<nn-1;i++)\n\t {\n\t string lst;\n\t lst = s[s.length()-1];\n\t s=s.substr(0,s.length()-1);\n\t //cout<<lst <<\" \"<<s<<\" \"<<endl;\n\t \n\t s= lst+s; //this appoints s as 7 19 then 9 71 then main last 1 97 but we dont need to check that\n\t \n\t stringstream geek(s);\n\t int x;\n\t geek>>x;\n\t if(isPrime(x)==false)\n\t return 0;\n\t }\n\t return 1;\n\t}\n " }, { "code": null, "e": 3120, "s": 3118, "text": "0" }, { "code": null, "e": 3148, "s": 3120, "text": "aloksinghbais025 months ago" }, { "code": null, "e": 4245, "s": 3148, "text": "public:bool isPrime[100001];Solution(){ memset(isPrime,true,sizeof(isPrime));}void precomputation(){ for(int num=2; num<=100000; num++){ long long int j = 1LL*num*num; if(j>100000) return; for(int d=num*num; d<=100000; d+=num){ isPrime[d] = false; } }}int convertToInt(vector<int> v){ int num = 0; int base = 1; for(int i=v.size()-1; i>=0; i--){ num += v[i]*base; base *= 10; } return (num);}bool checkAllRotations(int num){ if(!isPrime[num]) return (false); int temp = num; vector<int> dnum; while(temp > 0){ dnum.push_back(temp%10); temp /= 10; } reverse(dnum.begin(),dnum.end()); int sz = dnum.size(); for(int cnt=1; cnt<sz; cnt++){ int last = dnum[sz-1]; for(int i=sz-1; i>0; i--) dnum[i] = dnum[i-1]; dnum[0] = last; int temp = convertToInt(dnum); if(!isPrime[temp]) return (false); } return (true);}int isCircularPrime(int n) { if(n==1) return(false); precomputation(); return (checkAllRotations(n) ? 1 : 0);}" }, { "code": null, "e": 4248, "s": 4245, "text": "+1" }, { "code": null, "e": 4264, "s": 4248, "text": "aloksinghbais02" }, { "code": null, "e": 4290, "s": 4264, "text": "This comment was deleted." }, { "code": null, "e": 4292, "s": 4290, "text": "0" }, { "code": null, "e": 4313, "s": 4292, "text": "anutiger6 months ago" }, { "code": null, "e": 4841, "s": 4313, "text": "\t vector<int> dp(1e5 + 1,1);\n\t for(int i = 2; i <= 1e5; i++){\n\t if(dp[i] == 1){\n\t int j = 2;\n\t while(i * j <= 1e5){\n\t dp[i * j] = 0;\n\t j++;\n\t }\n\t }\n\t }\n\t int size = 0;\n\t int s = to_string(n).length();\n\t if(dp[n] == 0 or n == 1)\n\t return 0;\n\t while(size < s){\n\t int a = n % 10;\n\t n/= 10;\n\t n += (a * pow(10, s - 1));\n\t size++;\n\t if(dp[n] == 0)\n\t return 0;\n\t }\n\t return 1;" }, { "code": null, "e": 4843, "s": 4841, "text": "0" }, { "code": null, "e": 4861, "s": 4843, "text": "humblefool2point0" }, { "code": null, "e": 4887, "s": 4861, "text": "This comment was deleted." }, { "code": null, "e": 4890, "s": 4887, "text": "-1" }, { "code": null, "e": 4919, "s": 4890, "text": "siddharthdhaka146 months ago" }, { "code": null, "e": 5548, "s": 4919, "text": "class Solution\n{\n public int isCircularPrime(int n)\n {\n if(n == 1) return 0;\n if(n == 2) return 1;\n \n int nn = n;\n \n while(true){\n if(!primeChecker(nn)) return 0;\n \n nn = (int)nn%10 * (int)java.lang.Math.pow(10,(int)java.lang.Math.log10(nn)) + (int)nn/10;\n\n \n if(nn == n) break;\n }\n return 1; \n }\n \n \n public boolean primeChecker(int n){\n int sqroot1 = (int)java.lang.Math.sqrt(n) + 1;\n\n for (int i = 2; i <= sqroot1; i++){\n if(n%i == 0) return false; \n } \n return true;\n }\n}" }, { "code": null, "e": 5550, "s": 5548, "text": "0" }, { "code": null, "e": 5573, "s": 5550, "text": "harsheopro6 months ago" }, { "code": null, "e": 6019, "s": 5573, "text": "public:bool isprime(int n){ for(int i=2;i<n;i++){ if(n%i==0) return false; } return true;}int isCircularPrime(int n) { if(n==1) return 0; int d=n; int count =0; int p=1; while(d!=0){ int r=d%10; count++; p*=10; d/=10; } for(int i=0;i<count;i++){ if(isprime(n)){ } else return 0; n=(n%10)*(p/10)+(n/10); } return 1;}};" }, { "code": null, "e": 6165, "s": 6019, "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": 6201, "s": 6165, "text": " Login to access your submissions. " }, { "code": null, "e": 6211, "s": 6201, "text": "\nProblem\n" }, { "code": null, "e": 6221, "s": 6211, "text": "\nContest\n" }, { "code": null, "e": 6284, "s": 6221, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6432, "s": 6284, "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": 6640, "s": 6432, "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": 6746, "s": 6640, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Namespace in C++ | Set 3 (Accessing, creating header, nesting and aliasing) - GeeksforGeeks
29 May, 2017 Namespace in C++ | Set 1 (Introduction)Namespace in C++ | Set 2 (Extending namespace and Unnamed namespace) Normal way// C++ program to demonstrate accessing of variables// in normal way, i.e., using "::"#include <iostream>using namespace std; namespace geek{ int rel = 300; } int main(){ // variable ‘rel’ accessed // using scope resolution operator cout << geek::rel << "\n"; // prints 300 return 0;}Output :300 “using” directive// C++ program to demonstrate accessing of variables// in normal way, i.e., using "using" directive#include <iostream>using namespace std; namespace geek{ int rel = 300; } // use of ‘using’ directiveusing namespace geek; int main(){ // variable ‘rel’ accessed // without using scope resolution variable cout << rel << "\n"; //prints 300 return 0;}Output:300 Normal way// C++ program to demonstrate accessing of variables// in normal way, i.e., using "::"#include <iostream>using namespace std; namespace geek{ int rel = 300; } int main(){ // variable ‘rel’ accessed // using scope resolution operator cout << geek::rel << "\n"; // prints 300 return 0;}Output :300 // C++ program to demonstrate accessing of variables// in normal way, i.e., using "::"#include <iostream>using namespace std; namespace geek{ int rel = 300; } int main(){ // variable ‘rel’ accessed // using scope resolution operator cout << geek::rel << "\n"; // prints 300 return 0;} Output : 300 “using” directive// C++ program to demonstrate accessing of variables// in normal way, i.e., using "using" directive#include <iostream>using namespace std; namespace geek{ int rel = 300; } // use of ‘using’ directiveusing namespace geek; int main(){ // variable ‘rel’ accessed // without using scope resolution variable cout << rel << "\n"; //prints 300 return 0;}Output:300 // C++ program to demonstrate accessing of variables// in normal way, i.e., using "using" directive#include <iostream>using namespace std; namespace geek{ int rel = 300; } // use of ‘using’ directiveusing namespace geek; int main(){ // variable ‘rel’ accessed // without using scope resolution variable cout << rel << "\n"; //prints 300 return 0;} Output: 300 We need to create two files. One containing the namespace and all the data members and member functions we want to use later. And the other program can directly call the first program to use all the data members and member functions in it. File 1 // file1.h namespace foo{ int value() { return 5; }} File 2 // file2.cpp - Not to be executed online#include <iostream>#include “file1.h” // Including file1using namespace std; int main () { cout << foo::value(); return 0;} Here we can see that the namespace is created in file1.h and the value() of that namespace is getting called in file2.cpp. // C++ program to demonstrate nesting of namespaces#include <iostream>using namespace std; // Nested namespacenamespace out{ int val = 5; namespace in { int val2 = val; }} // Driver codeint main(){ cout << out::in::val2; // prints 5 return 0;} OUTPUT : 5 namespace new_name = current_name; #include <iostream> namespace name1 { namespace name2 { namespace name3 { int var = 42; } }} // Aliasing namespace alias = name1::name2::name3; int main(){ std::cout << alias::var << '\n';} Output : 42 This article is contributed by Abhinav Tiwari .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. cpp-namespaces C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Left Shift and Right Shift Operators in C/C++ fork() in C Core Dump (Segmentation fault) in C/C++ Function Pointer in C Substring in C++ Inheritance in C++ Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) Virtual Function in C++ C++ Classes and Objects
[ { "code": null, "e": 26073, "s": 26045, "text": "\n29 May, 2017" }, { "code": null, "e": 26181, "s": 26073, "text": "Namespace in C++ | Set 1 (Introduction)Namespace in C++ | Set 2 (Extending namespace and Unnamed namespace)" }, { "code": null, "e": 26910, "s": 26181, "text": "Normal way// C++ program to demonstrate accessing of variables// in normal way, i.e., using \"::\"#include <iostream>using namespace std; namespace geek{ int rel = 300; } int main(){ // variable ‘rel’ accessed // using scope resolution operator cout << geek::rel << \"\\n\"; // prints 300 return 0;}Output :300\n“using” directive// C++ program to demonstrate accessing of variables// in normal way, i.e., using \"using\" directive#include <iostream>using namespace std; namespace geek{ int rel = 300; } // use of ‘using’ directiveusing namespace geek; int main(){ // variable ‘rel’ accessed // without using scope resolution variable cout << rel << \"\\n\"; //prints 300 return 0;}Output:300\n" }, { "code": null, "e": 27238, "s": 26910, "text": "Normal way// C++ program to demonstrate accessing of variables// in normal way, i.e., using \"::\"#include <iostream>using namespace std; namespace geek{ int rel = 300; } int main(){ // variable ‘rel’ accessed // using scope resolution operator cout << geek::rel << \"\\n\"; // prints 300 return 0;}Output :300\n" }, { "code": "// C++ program to demonstrate accessing of variables// in normal way, i.e., using \"::\"#include <iostream>using namespace std; namespace geek{ int rel = 300; } int main(){ // variable ‘rel’ accessed // using scope resolution operator cout << geek::rel << \"\\n\"; // prints 300 return 0;}", "e": 27544, "s": 27238, "text": null }, { "code": null, "e": 27553, "s": 27544, "text": "Output :" }, { "code": null, "e": 27558, "s": 27553, "text": "300\n" }, { "code": null, "e": 27960, "s": 27558, "text": "“using” directive// C++ program to demonstrate accessing of variables// in normal way, i.e., using \"using\" directive#include <iostream>using namespace std; namespace geek{ int rel = 300; } // use of ‘using’ directiveusing namespace geek; int main(){ // variable ‘rel’ accessed // without using scope resolution variable cout << rel << \"\\n\"; //prints 300 return 0;}Output:300\n" }, { "code": "// C++ program to demonstrate accessing of variables// in normal way, i.e., using \"using\" directive#include <iostream>using namespace std; namespace geek{ int rel = 300; } // use of ‘using’ directiveusing namespace geek; int main(){ // variable ‘rel’ accessed // without using scope resolution variable cout << rel << \"\\n\"; //prints 300 return 0;}", "e": 28334, "s": 27960, "text": null }, { "code": null, "e": 28342, "s": 28334, "text": "Output:" }, { "code": null, "e": 28347, "s": 28342, "text": "300\n" }, { "code": null, "e": 28473, "s": 28347, "text": "We need to create two files. One containing the namespace and all the data members and member functions we want to use later." }, { "code": null, "e": 28587, "s": 28473, "text": "And the other program can directly call the first program to use all the data members and member functions in it." }, { "code": null, "e": 28594, "s": 28587, "text": "File 1" }, { "code": "// file1.h namespace foo{ int value() { return 5; }}", "e": 28668, "s": 28594, "text": null }, { "code": null, "e": 28675, "s": 28668, "text": "File 2" }, { "code": "// file2.cpp - Not to be executed online#include <iostream>#include “file1.h” // Including file1using namespace std; int main () { cout << foo::value(); return 0;}", "e": 28846, "s": 28675, "text": null }, { "code": null, "e": 28969, "s": 28846, "text": "Here we can see that the namespace is created in file1.h and the value() of that namespace is getting called in file2.cpp." }, { "code": "// C++ program to demonstrate nesting of namespaces#include <iostream>using namespace std; // Nested namespacenamespace out{ int val = 5; namespace in { int val2 = val; }} // Driver codeint main(){ cout << out::in::val2; // prints 5 return 0;}", "e": 29233, "s": 28969, "text": null }, { "code": null, "e": 29242, "s": 29233, "text": "OUTPUT :" }, { "code": null, "e": 29245, "s": 29242, "text": "5\n" }, { "code": null, "e": 29281, "s": 29245, "text": "namespace new_name = current_name;\n" }, { "code": "#include <iostream> namespace name1 { namespace name2 { namespace name3 { int var = 42; } }} // Aliasing namespace alias = name1::name2::name3; int main(){ std::cout << alias::var << '\\n';}", "e": 29525, "s": 29281, "text": null }, { "code": null, "e": 29534, "s": 29525, "text": "Output :" }, { "code": null, "e": 29538, "s": 29534, "text": "42\n" }, { "code": null, "e": 29840, "s": 29538, "text": "This article is contributed by Abhinav Tiwari .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": 29965, "s": 29840, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29980, "s": 29965, "text": "cpp-namespaces" }, { "code": null, "e": 29991, "s": 29980, "text": "C Language" }, { "code": null, "e": 29995, "s": 29991, "text": "C++" }, { "code": null, "e": 29999, "s": 29995, "text": "CPP" }, { "code": null, "e": 30097, "s": 29999, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30143, "s": 30097, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 30155, "s": 30143, "text": "fork() in C" }, { "code": null, "e": 30195, "s": 30155, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 30217, "s": 30195, "text": "Function Pointer in C" }, { "code": null, "e": 30234, "s": 30217, "text": "Substring in C++" }, { "code": null, "e": 30253, "s": 30234, "text": "Inheritance in C++" }, { "code": null, "e": 30299, "s": 30253, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 30342, "s": 30299, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 30366, "s": 30342, "text": "Virtual Function in C++" } ]
Background and foreground thread in C#
A thread is defined as the execution path of a program. Each thread defines a unique flow of control When the foreground threads will close, the background threads will be terminated. The property used for background thread is IsBackground that gets or sets a value indicating whether a thread is a background thread. The default value of this property would be false because the default threads created are Foreground Threads. To create a background thread − Thread bgThread = new Thread(tStart); bgThread.IsBackground = true; bgThread.Start(); Foreground threads continue to run until the last foreground thread is terminated. When all the foreground threads are stopped, the application is closed. The default threads that are created are foreground threads.
[ { "code": null, "e": 1163, "s": 1062, "text": "A thread is defined as the execution path of a program. Each thread defines a unique flow of control" }, { "code": null, "e": 1246, "s": 1163, "text": "When the foreground threads will close, the background threads will be terminated." }, { "code": null, "e": 1490, "s": 1246, "text": "The property used for background thread is IsBackground that gets or sets a value indicating whether a thread is a background thread. The default value of this property would be false because the default threads created are Foreground Threads." }, { "code": null, "e": 1522, "s": 1490, "text": "To create a background thread −" }, { "code": null, "e": 1608, "s": 1522, "text": "Thread bgThread = new Thread(tStart);\nbgThread.IsBackground = true;\nbgThread.Start();" }, { "code": null, "e": 1691, "s": 1608, "text": "Foreground threads continue to run until the last foreground thread is terminated." }, { "code": null, "e": 1824, "s": 1691, "text": "When all the foreground threads are stopped, the application is closed. The default threads that are created are foreground threads." } ]
Cisco Interview Experience for Experienced - GeeksforGeeks
17 Oct, 2021 CISCO Java and spring boot interview experience for 2+ years experience There were total 5 rounds Hackerrank online coding test1st technical round2nd technical roundManagerial roundHR discussion (Over phone call) Hackerrank online coding test 1st technical round 2nd technical round Managerial round HR discussion (Over phone call) Summery Role: Java + Angular full stack developer. Applied from LinkedIn, after that received Hackerrank test link and was required to finish it in the next 48 hours. After completing the online test, HR called and explained about next steps. those are as follows, There will be 3 rounds, the first round will be the general tech round without your CV. The second round will be a tech round based on your CV. If you perform well in any of these two rounds then you will be sent to 3rd round. The third round will be the tech + managerial round. Note: All rounds will be on a single day and those will be continuous, giving 10min breaks in between two rounds. My interview started at 11 AM and all three rounds ended at around 1:45 PM (HR discussion was on a different day) all were around 1hr long Round 1: Hackerrank online coding test 5 coding questions were there, 3 were easy and 2 were medium-level questions. There were 2 hours of the time limit. Round 2: Technical Round 1 Tell me about yourself. Given use cases and asked for solution approaches. There is a career portal and there are two types of data, username, experience, etc, and resume as some files. You have to upload a resume in MongoDB and you have to add other data in MYSQL, if any of the ones fails you have to roll back the other data that you inserted. How do you achieve this in spring boot? (He was expecting to use @Transactional annotation) There is a job portal and you have posted 5 new jobs and the job description is available in DB. assume there are 1000 people trying to get a job description, how will you implement to minimize database hits (He was expecting some caching and I answered the same) Write a rest controller class and write one GET endpoint which takes user-id as a query parameter and returns that user details. Add one more feature to the same REST endpoint, that should return user details of that user and if his name is “William” (In this case I took user-id as path parameter and name as a request parameter and achieved the task) What does @RequestMapping annotation do? What happens if we add the below annotations to the same rest controller class?@RestController(“\user”) , @RequestMapping(“\user”) Why spring boot used over spring framework In System.out.println() explain each component https://www.geeksforgeeks.org/system-out-println-in-java/ Give me an example where you used overloaded methods from a built-in java library (Gave Arrays. sort() as an example) Write a query to get employee details on who has the third-highest salary. https://www.geeksforgeeks.org/find-nth-highest-salary-table/ Round 3: Technical Round 2 Tell me about projects that you worked on in the past. A similar question was asked in 1st technical round(use case 1) Explain the architecture of any one project that you worked What is an immutable class, how to create an immutable class? What is a deep copy What happens when you do the below thing s1 = "ABC" s1 = s1+"xyz" Explained about string immutability and string pool concept in java Write SQL query for below scenario There are two tables Employee and Department, every employee may or may not have a department. Employee table has departments as the foreign key. Asked to fetch all employees’ details along with their department details. (Left join b/w Employee and Department table) Use case: Assume you have some REST service and it will throw some error message, how will you return the same error message in different languages, ex: Indians should get an error message in English where Japanese get it in Japanese, etc. I didn’t know about it. So I directly told that since I have not worked on such similar cases I am not aware of it. Round 4: Managerial Round + Technical Round Tell me about yourself Tell me your hobby Tell me your weakness and strength Puzzle to measure 4L of water from 3L and 5L jar. https://practice.geeksforgeeks.org/problems/the-3-5-litre-die-hard-water-puzzle Write a query to find the second highest salary from employee table What all test cases do you write for login scenario, where service takes user id and password. Write logic to validate the username and age of an employee. where username should only contain caps or small alphabets, numbers, and space. And age should be more than zero and less than 100. She was expecting to write in javascript but I wrote it in java but she was okay with it. Round 5: HR discussion Discussed salary compensations and company benefits. Verdict: Received offer Tips: If you are not aware of the answer that is completely fine, just tell them I am not aware of it since I have not worked on anything related to that. Have a smile on your face always and don’t forget to ask your doubt at the end of the interview. All the best. Cisco Marketing Experienced Interview Experiences Cisco Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE1 (8 Months Experienced) 2022 Goldman Sachs Interview Experience for Technology Analyst (1.8 Years Experienced) Amazon Interview Experience for System Development Engineer (Exp - 6 months) FactSet Interview Experience (Off-Campus) 8 Months Experienced Walmart Interview Experience for SDE-III Amazon Interview Questions Commonly Asked Java Programming Interview Questions | Set 2 Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Zoho Interview | Set 3 (Off-Campus)
[ { "code": null, "e": 25698, "s": 25670, "text": "\n17 Oct, 2021" }, { "code": null, "e": 25797, "s": 25698, "text": "CISCO Java and spring boot interview experience for 2+ years experience There were total 5 rounds" }, { "code": null, "e": 25912, "s": 25797, "text": "Hackerrank online coding test1st technical round2nd technical roundManagerial roundHR discussion (Over phone call)" }, { "code": null, "e": 25942, "s": 25912, "text": "Hackerrank online coding test" }, { "code": null, "e": 25962, "s": 25942, "text": "1st technical round" }, { "code": null, "e": 25982, "s": 25962, "text": "2nd technical round" }, { "code": null, "e": 25999, "s": 25982, "text": "Managerial round" }, { "code": null, "e": 26031, "s": 25999, "text": "HR discussion (Over phone call)" }, { "code": null, "e": 26039, "s": 26031, "text": "Summery" }, { "code": null, "e": 26082, "s": 26039, "text": "Role: Java + Angular full stack developer." }, { "code": null, "e": 26296, "s": 26082, "text": "Applied from LinkedIn, after that received Hackerrank test link and was required to finish it in the next 48 hours. After completing the online test, HR called and explained about next steps. those are as follows," }, { "code": null, "e": 26576, "s": 26296, "text": "There will be 3 rounds, the first round will be the general tech round without your CV. The second round will be a tech round based on your CV. If you perform well in any of these two rounds then you will be sent to 3rd round. The third round will be the tech + managerial round." }, { "code": null, "e": 26829, "s": 26576, "text": "Note: All rounds will be on a single day and those will be continuous, giving 10min breaks in between two rounds. My interview started at 11 AM and all three rounds ended at around 1:45 PM (HR discussion was on a different day) all were around 1hr long" }, { "code": null, "e": 26868, "s": 26829, "text": "Round 1: Hackerrank online coding test" }, { "code": null, "e": 26984, "s": 26868, "text": "5 coding questions were there, 3 were easy and 2 were medium-level questions. There were 2 hours of the time limit." }, { "code": null, "e": 27011, "s": 26984, "text": "Round 2: Technical Round 1" }, { "code": null, "e": 27035, "s": 27011, "text": "Tell me about yourself." }, { "code": null, "e": 27086, "s": 27035, "text": "Given use cases and asked for solution approaches." }, { "code": null, "e": 27197, "s": 27086, "text": "There is a career portal and there are two types of data, username, experience, etc, and resume as some files." }, { "code": null, "e": 27450, "s": 27197, "text": "You have to upload a resume in MongoDB and you have to add other data in MYSQL, if any of the ones fails you have to roll back the other data that you inserted. How do you achieve this in spring boot? (He was expecting to use @Transactional annotation)" }, { "code": null, "e": 27714, "s": 27450, "text": "There is a job portal and you have posted 5 new jobs and the job description is available in DB. assume there are 1000 people trying to get a job description, how will you implement to minimize database hits (He was expecting some caching and I answered the same)" }, { "code": null, "e": 27843, "s": 27714, "text": "Write a rest controller class and write one GET endpoint which takes user-id as a query parameter and returns that user details." }, { "code": null, "e": 28067, "s": 27843, "text": "Add one more feature to the same REST endpoint, that should return user details of that user and if his name is “William” (In this case I took user-id as path parameter and name as a request parameter and achieved the task)" }, { "code": null, "e": 28108, "s": 28067, "text": "What does @RequestMapping annotation do?" }, { "code": null, "e": 28239, "s": 28108, "text": "What happens if we add the below annotations to the same rest controller class?@RestController(“\\user”) , @RequestMapping(“\\user”)" }, { "code": null, "e": 28282, "s": 28239, "text": "Why spring boot used over spring framework" }, { "code": null, "e": 28388, "s": 28282, "text": "In System.out.println() explain each component https://www.geeksforgeeks.org/system-out-println-in-java/" }, { "code": null, "e": 28506, "s": 28388, "text": "Give me an example where you used overloaded methods from a built-in java library (Gave Arrays. sort() as an example)" }, { "code": null, "e": 28642, "s": 28506, "text": "Write a query to get employee details on who has the third-highest salary. https://www.geeksforgeeks.org/find-nth-highest-salary-table/" }, { "code": null, "e": 28669, "s": 28642, "text": "Round 3: Technical Round 2" }, { "code": null, "e": 28724, "s": 28669, "text": "Tell me about projects that you worked on in the past." }, { "code": null, "e": 28788, "s": 28724, "text": "A similar question was asked in 1st technical round(use case 1)" }, { "code": null, "e": 28848, "s": 28788, "text": "Explain the architecture of any one project that you worked" }, { "code": null, "e": 28910, "s": 28848, "text": "What is an immutable class, how to create an immutable class?" }, { "code": null, "e": 28930, "s": 28910, "text": "What is a deep copy" }, { "code": null, "e": 28971, "s": 28930, "text": "What happens when you do the below thing" }, { "code": null, "e": 28996, "s": 28971, "text": "s1 = \"ABC\"\ns1 = s1+\"xyz\"" }, { "code": null, "e": 29065, "s": 28996, "text": "Explained about string immutability and string pool concept in java" }, { "code": null, "e": 29100, "s": 29065, "text": "Write SQL query for below scenario" }, { "code": null, "e": 29246, "s": 29100, "text": "There are two tables Employee and Department, every employee may or may not have a department. Employee table has departments as the foreign key." }, { "code": null, "e": 29367, "s": 29246, "text": "Asked to fetch all employees’ details along with their department details. (Left join b/w Employee and Department table)" }, { "code": null, "e": 29607, "s": 29367, "text": "Use case: Assume you have some REST service and it will throw some error message, how will you return the same error message in different languages, ex: Indians should get an error message in English where Japanese get it in Japanese, etc." }, { "code": null, "e": 29723, "s": 29607, "text": "I didn’t know about it. So I directly told that since I have not worked on such similar cases I am not aware of it." }, { "code": null, "e": 29767, "s": 29723, "text": "Round 4: Managerial Round + Technical Round" }, { "code": null, "e": 29790, "s": 29767, "text": "Tell me about yourself" }, { "code": null, "e": 29809, "s": 29790, "text": "Tell me your hobby" }, { "code": null, "e": 29844, "s": 29809, "text": "Tell me your weakness and strength" }, { "code": null, "e": 29974, "s": 29844, "text": "Puzzle to measure 4L of water from 3L and 5L jar. https://practice.geeksforgeeks.org/problems/the-3-5-litre-die-hard-water-puzzle" }, { "code": null, "e": 30042, "s": 29974, "text": "Write a query to find the second highest salary from employee table" }, { "code": null, "e": 30137, "s": 30042, "text": "What all test cases do you write for login scenario, where service takes user id and password." }, { "code": null, "e": 30420, "s": 30137, "text": "Write logic to validate the username and age of an employee. where username should only contain caps or small alphabets, numbers, and space. And age should be more than zero and less than 100. She was expecting to write in javascript but I wrote it in java but she was okay with it." }, { "code": null, "e": 30443, "s": 30420, "text": "Round 5: HR discussion" }, { "code": null, "e": 30496, "s": 30443, "text": "Discussed salary compensations and company benefits." }, { "code": null, "e": 30520, "s": 30496, "text": "Verdict: Received offer" }, { "code": null, "e": 30526, "s": 30520, "text": "Tips:" }, { "code": null, "e": 30675, "s": 30526, "text": "If you are not aware of the answer that is completely fine, just tell them I am not aware of it since I have not worked on anything related to that." }, { "code": null, "e": 30772, "s": 30675, "text": "Have a smile on your face always and don’t forget to ask your doubt at the end of the interview." }, { "code": null, "e": 30786, "s": 30772, "text": "All the best." }, { "code": null, "e": 30792, "s": 30786, "text": "Cisco" }, { "code": null, "e": 30802, "s": 30792, "text": "Marketing" }, { "code": null, "e": 30814, "s": 30802, "text": "Experienced" }, { "code": null, "e": 30836, "s": 30814, "text": "Interview Experiences" }, { "code": null, "e": 30842, "s": 30836, "text": "Cisco" }, { "code": null, "e": 30940, "s": 30842, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31005, "s": 30940, "text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022" }, { "code": null, "e": 31087, "s": 31005, "text": "Goldman Sachs Interview Experience for Technology Analyst (1.8 Years Experienced)" }, { "code": null, "e": 31164, "s": 31087, "text": "Amazon Interview Experience for System Development Engineer (Exp - 6 months)" }, { "code": null, "e": 31227, "s": 31164, "text": "FactSet Interview Experience (Off-Campus) 8 Months Experienced" }, { "code": null, "e": 31268, "s": 31227, "text": "Walmart Interview Experience for SDE-III" }, { "code": null, "e": 31295, "s": 31268, "text": "Amazon Interview Questions" }, { "code": null, "e": 31355, "s": 31295, "text": "Commonly Asked Java Programming Interview Questions | Set 2" }, { "code": null, "e": 31406, "s": 31355, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 31448, "s": 31406, "text": "Amazon AWS Interview Experience for SDE-1" } ]
GATE | GATE CS 2018 | Question 57 - GeeksforGeeks
09 Mar, 2018 The number of possible min-heaps containing each value from {1, 2, 3, 4, 5, 6, 7} exactly once is _______. Note –This was Numerical Type question.(A) 80(B) 8(C) 20(D) 210Answer: (A)Explanation: Set minimum element as root (i.e 1), now 6 are remaining and left subtree will have 3 elements, each left subtree combination can be permuted in 2! ways. Total ways to design min-heap with 7-elements = *2! * 2! = 20*2*2 = 80 Alternative approach – Total number of min or max heap tree with 1 to N elements are using recurrence relation: T(N) =(N-1)Ck * T(k) * T(N-k-1), where k = number of nodes on left subtree T(1) = 1 T(2) = 1 T(3) = 2 T(4) = 3C2 * T(2) * T(1) = 3 T(5) = 4C3 * T(3) * T(1) = 8 T(6) = 5C3 * T(3) * T(2) = 20 T(7) = 5C3 * T(3) * T(3) = 80 So, answer is 80. Quiz of this Question GATE CS 2018 GATE-GATE CS 2018 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25768, "s": 25740, "text": "\n09 Mar, 2018" }, { "code": null, "e": 25875, "s": 25768, "text": "The number of possible min-heaps containing each value from {1, 2, 3, 4, 5, 6, 7} exactly once is _______." }, { "code": null, "e": 26116, "s": 25875, "text": "Note –This was Numerical Type question.(A) 80(B) 8(C) 20(D) 210Answer: (A)Explanation: Set minimum element as root (i.e 1), now 6 are remaining and left subtree will have 3 elements, each left subtree combination can be permuted in 2! ways." }, { "code": null, "e": 26188, "s": 26116, "text": "Total ways to design min-heap with 7-elements = *2! * 2! = 20*2*2 = 80" }, { "code": null, "e": 26300, "s": 26188, "text": "Alternative approach – Total number of min or max heap tree with 1 to N elements are using recurrence relation:" }, { "code": null, "e": 26522, "s": 26300, "text": "T(N) =(N-1)Ck * T(k) * T(N-k-1), where k = number of nodes on left subtree\n\nT(1) = 1\nT(2) = 1\nT(3) = 2\nT(4) = 3C2 * T(2) * T(1) = 3\nT(5) = 4C3 * T(3) * T(1) = 8\nT(6) = 5C3 * T(3) * T(2) = 20\nT(7) = 5C3 * T(3) * T(3) = 80\n" }, { "code": null, "e": 26540, "s": 26522, "text": "So, answer is 80." }, { "code": null, "e": 26562, "s": 26540, "text": "Quiz of this Question" }, { "code": null, "e": 26575, "s": 26562, "text": "GATE CS 2018" }, { "code": null, "e": 26593, "s": 26575, "text": "GATE-GATE CS 2018" }, { "code": null, "e": 26598, "s": 26593, "text": "GATE" }, { "code": null, "e": 26696, "s": 26598, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26730, "s": 26696, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26764, "s": 26730, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 26798, "s": 26764, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26831, "s": 26798, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26867, "s": 26831, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 26901, "s": 26867, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 26937, "s": 26901, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 26971, "s": 26937, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 27005, "s": 26971, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Access Azure Database for MySQL from Azure functions with SSL Certificate Verification | by Christopher Tao | Towards Data Science
Recently I got a customer who has relatively small volume data to be managed. So, I suggested Azure Database for MySQL. Basically, the smallest instance cost about $560 AUD per month will be enough. Also, because this is DBaaS, the customer does not need to hire more people to maintain it. The customer also wants to automate the ETL processes to this MySQL DB. Although I think Data Factory would be the ideal solution, the cost can be a big issue because the ETL has to be done every 5 minutes which will trigger the orchestration too frequently and cause a “shock” bill. Therefore, I suggest using Azure Functions which is a serverless computing solution to do this ETL. Another reason is that the data transformation is not too complicated and will rarely be changed once done. However, I met an issue when I use python to implement this Azure function to connect to the Azure MySQL server. That is, the MySQL has enforced the SSL encryption, but the Azure Function side doesn’t provide a certificate. In our case, disabling the SSL enforcement is not an option because we don’t want to put customer’s data in a risky situation such as man-in-the-middle attacks. Therefore, I’ll need to solve this problem and finally, I did it. Here are the steps to reproduce the issue and how to solve it. Go to your Azure subscription and click Create a resource -> search for Azure Database for MySQL -> Create In the Create MySQL server page, fill in the resource group, server name and other required fields. In this example, I choose MySQL v8.0, then click Review + create -> Create To be able to test your Azure Functions on your local machine. Don’t forget to add your local IP address to the connection security settings. Specifically, Go to the Azure MySQL we just created. On the left navigation select Connection security in Settings section. Then on the right main view click + Add client IP button. This will automatically add your current IP address to whitelist. Then, click Save. I prefer to create Azure Functions in VS code for the simplicity of development. You’ll need to install the Azure Functions extension for VS code. Once you’re done, you should be able to see the extra Azure button on the left side. Click the button and follow the instructions to log in to your Azure account. Press cmd+shit+p on Mac or ctrl+shift+p on Windows to call the command palette then choose Create New Project In this example, I’ll use python as the development language. Then, choose HTTP trigger because it is easier for testing purpose. Then, complete the rest steps for the instructions. In your VS code terminal, using pip to install the mysql-connector library for Python. $ pip install mysql-connector Also, don’t forget to add the dependencies to requirements.txt, as Azure Functions rely on this file to install Python dependencies for your app. Go to the Azure Database for MySQL that you just created. Note down the server name and login name. The code is simply connecting to the MySQL server and show all the databases. import loggingimport azure.functions as funcimport mysql.connectordef main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') # Connect to MySQL cnx = mysql.connector.connect( user="ctao@mysql80-test-chris", password='<your_password>', host="mysql80-test-chris.mysql.database.azure.com", port=3306 ) logging.info(cnx) # Show databases cursor = cnx.cursor() cursor.execute("SHOW DATABASES") result_list = cursor.fetchall() # Build result response text result_str_list = [] for row in result_list: row_str = ', '.join([str(v) for v in row]) result_str_list.append(row_str) result_str = '\n'.join(result_str_list) return func.HttpResponse( result_str, status_code=200 ) You can either deploy the Azure Function to test it in a production environment or run the following command in VS code terminal to test it locally. $ func start run Once the Azure Function is running, access the URL to try to get the list of databases. If you are running this locally, the URL should be as follows http://localhost:7071/api/<your_app_name> Unsurprisingly, your browser will complain with a HTTP error 500. If you go back to your VS code terminal, you’ll see some error messages in the console. The key to this issue is highlighted in the image Exception: ProgrammingError: 9002 (28000): SSL connection is required. Please specify SSL options and retry. Honestly, this issue bothered me for a while, But I solved it eventually. Firstly, It is not difficult the get the certificate file. You can download it from Microsoft Azure official documentation website, on this page. I’ll post the download link directly here: https://www.digicert.com/CACerts/BaltimoreCyberTrustRoot.crt.pem It is also not difficult to refer to it in Python. Usually, you can use either relative path: crtpath = '../BaltimoreCyberTrustRoot.crt.pem' or an absolute path: crtpath = '/User/.../BaltimoreCyberTrustRoot.crt.pem' Then, just simply put the path variable in the connect function: # Connect to MySQLcnx = mysql.connector.connect( user="ctao@azure-mysql-test", password='<your_password>', host="azure-mysql-test.mysql.database.azure.com", port=3306, ssl_ca=crtpath) However, this will NOT work after you deploy the Azure Function. This is because Azure Function will automatically deploy your code somewhere under /var on the actual back-end server, and you don’t have access to this server at all. In this case, we have to let Python to find the correct location of the cert file, and that’s definitely doable. We can use __file__. Let’s put the cert file in the root path of your project. So, if later on we have more Azure Functions and want to reuse this cert file, it makes sure we can reference it in the right way. Then, write a function to get this file import pathlibdef get_ssl_cert(): current_path = pathlib.Path(__file__).parent.parent return str(current_path / 'BaltimoreCyberTrustRoot.crt.pem') Note that the first .parent will return the root path of the Azure Function, and we need another .parent to make sure it returns the root path of the project. That means, you only need one .parent if you prefer to put the cert file in the root path of your Azure Function. After that, change the connecting code as follows: cnx = mysql.connector.connect( user="ctao@mysql80-test-chris", password='<your_password>', host="mysql80-test-chris.mysql.database.azure.com", port=3306, ssl_ca=get_ssl_cert()) Access the URL again, you will be able to see the list of databases! This will work both on your local machine and after deployed your Azure Functions. medium.com If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)
[ { "code": null, "e": 462, "s": 171, "text": "Recently I got a customer who has relatively small volume data to be managed. So, I suggested Azure Database for MySQL. Basically, the smallest instance cost about $560 AUD per month will be enough. Also, because this is DBaaS, the customer does not need to hire more people to maintain it." }, { "code": null, "e": 954, "s": 462, "text": "The customer also wants to automate the ETL processes to this MySQL DB. Although I think Data Factory would be the ideal solution, the cost can be a big issue because the ETL has to be done every 5 minutes which will trigger the orchestration too frequently and cause a “shock” bill. Therefore, I suggest using Azure Functions which is a serverless computing solution to do this ETL. Another reason is that the data transformation is not too complicated and will rarely be changed once done." }, { "code": null, "e": 1468, "s": 954, "text": "However, I met an issue when I use python to implement this Azure function to connect to the Azure MySQL server. That is, the MySQL has enforced the SSL encryption, but the Azure Function side doesn’t provide a certificate. In our case, disabling the SSL enforcement is not an option because we don’t want to put customer’s data in a risky situation such as man-in-the-middle attacks. Therefore, I’ll need to solve this problem and finally, I did it. Here are the steps to reproduce the issue and how to solve it." }, { "code": null, "e": 1575, "s": 1468, "text": "Go to your Azure subscription and click Create a resource -> search for Azure Database for MySQL -> Create" }, { "code": null, "e": 1750, "s": 1575, "text": "In the Create MySQL server page, fill in the resource group, server name and other required fields. In this example, I choose MySQL v8.0, then click Review + create -> Create" }, { "code": null, "e": 2158, "s": 1750, "text": "To be able to test your Azure Functions on your local machine. Don’t forget to add your local IP address to the connection security settings. Specifically, Go to the Azure MySQL we just created. On the left navigation select Connection security in Settings section. Then on the right main view click + Add client IP button. This will automatically add your current IP address to whitelist. Then, click Save." }, { "code": null, "e": 2468, "s": 2158, "text": "I prefer to create Azure Functions in VS code for the simplicity of development. You’ll need to install the Azure Functions extension for VS code. Once you’re done, you should be able to see the extra Azure button on the left side. Click the button and follow the instructions to log in to your Azure account." }, { "code": null, "e": 2578, "s": 2468, "text": "Press cmd+shit+p on Mac or ctrl+shift+p on Windows to call the command palette then choose Create New Project" }, { "code": null, "e": 2640, "s": 2578, "text": "In this example, I’ll use python as the development language." }, { "code": null, "e": 2708, "s": 2640, "text": "Then, choose HTTP trigger because it is easier for testing purpose." }, { "code": null, "e": 2760, "s": 2708, "text": "Then, complete the rest steps for the instructions." }, { "code": null, "e": 2847, "s": 2760, "text": "In your VS code terminal, using pip to install the mysql-connector library for Python." }, { "code": null, "e": 2877, "s": 2847, "text": "$ pip install mysql-connector" }, { "code": null, "e": 3023, "s": 2877, "text": "Also, don’t forget to add the dependencies to requirements.txt, as Azure Functions rely on this file to install Python dependencies for your app." }, { "code": null, "e": 3123, "s": 3023, "text": "Go to the Azure Database for MySQL that you just created. Note down the server name and login name." }, { "code": null, "e": 3201, "s": 3123, "text": "The code is simply connecting to the MySQL server and show all the databases." }, { "code": null, "e": 4032, "s": 3201, "text": "import loggingimport azure.functions as funcimport mysql.connectordef main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') # Connect to MySQL cnx = mysql.connector.connect( user=\"ctao@mysql80-test-chris\", password='<your_password>', host=\"mysql80-test-chris.mysql.database.azure.com\", port=3306 ) logging.info(cnx) # Show databases cursor = cnx.cursor() cursor.execute(\"SHOW DATABASES\") result_list = cursor.fetchall() # Build result response text result_str_list = [] for row in result_list: row_str = ', '.join([str(v) for v in row]) result_str_list.append(row_str) result_str = '\\n'.join(result_str_list) return func.HttpResponse( result_str, status_code=200 )" }, { "code": null, "e": 4181, "s": 4032, "text": "You can either deploy the Azure Function to test it in a production environment or run the following command in VS code terminal to test it locally." }, { "code": null, "e": 4198, "s": 4181, "text": "$ func start run" }, { "code": null, "e": 4286, "s": 4198, "text": "Once the Azure Function is running, access the URL to try to get the list of databases." }, { "code": null, "e": 4348, "s": 4286, "text": "If you are running this locally, the URL should be as follows" }, { "code": null, "e": 4390, "s": 4348, "text": "http://localhost:7071/api/<your_app_name>" }, { "code": null, "e": 4594, "s": 4390, "text": "Unsurprisingly, your browser will complain with a HTTP error 500. If you go back to your VS code terminal, you’ll see some error messages in the console. The key to this issue is highlighted in the image" }, { "code": null, "e": 4703, "s": 4594, "text": "Exception: ProgrammingError: 9002 (28000): SSL connection is required. Please specify SSL options and retry." }, { "code": null, "e": 4777, "s": 4703, "text": "Honestly, this issue bothered me for a while, But I solved it eventually." }, { "code": null, "e": 4966, "s": 4777, "text": "Firstly, It is not difficult the get the certificate file. You can download it from Microsoft Azure official documentation website, on this page. I’ll post the download link directly here:" }, { "code": null, "e": 5031, "s": 4966, "text": "https://www.digicert.com/CACerts/BaltimoreCyberTrustRoot.crt.pem" }, { "code": null, "e": 5125, "s": 5031, "text": "It is also not difficult to refer to it in Python. Usually, you can use either relative path:" }, { "code": null, "e": 5172, "s": 5125, "text": "crtpath = '../BaltimoreCyberTrustRoot.crt.pem'" }, { "code": null, "e": 5193, "s": 5172, "text": "or an absolute path:" }, { "code": null, "e": 5247, "s": 5193, "text": "crtpath = '/User/.../BaltimoreCyberTrustRoot.crt.pem'" }, { "code": null, "e": 5312, "s": 5247, "text": "Then, just simply put the path variable in the connect function:" }, { "code": null, "e": 5514, "s": 5312, "text": "# Connect to MySQLcnx = mysql.connector.connect( user=\"ctao@azure-mysql-test\", password='<your_password>', host=\"azure-mysql-test.mysql.database.azure.com\", port=3306, ssl_ca=crtpath)" }, { "code": null, "e": 5579, "s": 5514, "text": "However, this will NOT work after you deploy the Azure Function." }, { "code": null, "e": 5747, "s": 5579, "text": "This is because Azure Function will automatically deploy your code somewhere under /var on the actual back-end server, and you don’t have access to this server at all." }, { "code": null, "e": 5881, "s": 5747, "text": "In this case, we have to let Python to find the correct location of the cert file, and that’s definitely doable. We can use __file__." }, { "code": null, "e": 6070, "s": 5881, "text": "Let’s put the cert file in the root path of your project. So, if later on we have more Azure Functions and want to reuse this cert file, it makes sure we can reference it in the right way." }, { "code": null, "e": 6110, "s": 6070, "text": "Then, write a function to get this file" }, { "code": null, "e": 6263, "s": 6110, "text": "import pathlibdef get_ssl_cert(): current_path = pathlib.Path(__file__).parent.parent return str(current_path / 'BaltimoreCyberTrustRoot.crt.pem')" }, { "code": null, "e": 6536, "s": 6263, "text": "Note that the first .parent will return the root path of the Azure Function, and we need another .parent to make sure it returns the root path of the project. That means, you only need one .parent if you prefer to put the cert file in the root path of your Azure Function." }, { "code": null, "e": 6587, "s": 6536, "text": "After that, change the connecting code as follows:" }, { "code": null, "e": 6782, "s": 6587, "text": "cnx = mysql.connector.connect( user=\"ctao@mysql80-test-chris\", password='<your_password>', host=\"mysql80-test-chris.mysql.database.azure.com\", port=3306, ssl_ca=get_ssl_cert())" }, { "code": null, "e": 6851, "s": 6782, "text": "Access the URL again, you will be able to see the list of databases!" }, { "code": null, "e": 6934, "s": 6851, "text": "This will work both on your local machine and after deployed your Azure Functions." }, { "code": null, "e": 6945, "s": 6934, "text": "medium.com" } ]
Google Maps Selenium automation using Python - GeeksforGeeks
04 Jan, 2021 Prerequisites: Browser Automation using Selenium Selenium is a powerful tool for controlling a web browser through the program. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python. It can be installed using the below command: pip install selenium In this article, we are going to see how to automate the Google Maps search using selenium by getting the location of a place and its transportation details to another location. Step 1) Import modules Python3 # import required modulesfrom selenium import webdriverfrom time import sleep Step 2) Mention the path of your chrome driver in the driver variable that you downloaded. And then we need to get a Google Maps website. Python3 # assign url in the webdriver objectdriver = webdriver.Chrome()driver.get("https://www.google.co.in/maps/@10.8091781,78.2885026,7z")sleep(2) Step 3) Next step Declare a function under this function you need to inspect the search bar on the Google maps website. And Copy the Class name in the variable place. You need to send keys to a particular web element. Give your destination as an input. Provide the xpath value in the submit variable this is used to press the search button Python3 # search locationsdef searchplace(): Place = driver.find_element_by_class_name("tactile-searchbox-input") Place.send_keys("Tiruchirappalli") Submit = driver.find_element_by_xpath( "/html/body/jsl/div[3]/div[9]/div[3]/div[1]/div[1]/div[1]/div[2]/div[1]/button") Submit.click() searchplace() Step 4) Declare a function called directions. Under this function, you need to send a click to the direction button. Copy the X path value of the directions button from the Google maps website. And paste the value in the variable. Python3 # get directionsdef directions(): sleep(10) directions = driver.find_element_by_xpath( "/html/body/jsl/div[3]/div[9]/div[7]/div/div[1]/div/div/div[5]/div[1]/div/button") directions.click() directions() Step 5) Declare a function called as find. Under this function, you need to create a variable and in this variable, you need to copy the xpath of the value of the search bar and paste the value in the variable. Next, Send the starting point to the particular search box. And You need to send a click button to the search button to follow the Step 1 Process. Python3 # find placedef find(): sleep(6) find = driver.find_element_by_xpath( "/html/body/jsl/div[3]/div[9]/div[3]/div[1]/div[2]/div/div[3]/div[1]/div[1]/div[2]/div/div/input") find.send_keys("Tirunelveli") sleep(2) search = driver.find_element_by_xpath( "/html/body/jsl/div[3]/div[9]/div[3]/div[1]/div[2]/div/div[3]/div[1]/div[1]/div[2]/button[1]") search.click() find() Step 6) Now we need to scrap the essential data to complete our automation process. Here we need to copy the xpath values of Total kilometers between two places Bus travel time and Train travel time between these two places. Here I extracted the data from the Google maps website by using the Web-Elements. Python3 # get transportation detailsdef kilometers(): sleep(5) Totalkilometers = driver.find_element_by_xpath( "/html/body/jsl/div[3]/div[9]/div[7]/div/div[1]/div/div/div[5]/div[1]/div[1]/div[1]/div[1]/div[2]/div") print("Total Kilometers:", Totalkilometers.text) sleep(5) Bus = driver.find_element_by_xpath( "/html/body/jsl/div[3]/div[9]/div[7]/div/div[1]/div/div/div[5]/div[1]/div[1]/div[1]/div[1]/div[1]/span[1]") print("Bus Travel:", Bus.text) sleep(7) Train = driver.find_element_by_xpath( "/html/body/jsl/div[3]/div[9]/div[7]/div/div[1]/div/div/div[5]/div[2]/div[1]/div[2]/div[1]/div") print("Train Travel:", Train.text) sleep(7) kilometers() Below is the complete program based on the above approach: Python3 # import required modulesfrom selenium import webdriverfrom time import sleep # assign url in the webdriver objectdriver = webdriver.Chrome()driver.get("https://www.google.co.in/maps/@10.8091781,78.2885026,7z")sleep(2) # search locationsdef searchplace(): Place = driver.find_element_by_class_name("tactile-searchbox-input") Place.send_keys("Tiruchirappalli") Submit = driver.find_element_by_xpath( "/html/body/jsl/div[3]/div[9]/div[3]/div[1]/div[1]/div[1]/div[2]/div[1]/button") Submit.click() searchplace() # get directionsdef directions(): sleep(10) directions = driver.find_element_by_xpath( "/html/body/jsl/div[3]/div[9]/div[7]/div/div[1]/div/div/div[5]/div[1]/div/button") directions.click() directions() # find placedef find(): sleep(6) find = driver.find_element_by_xpath( "/html/body/jsl/div[3]/div[9]/div[3]/div[1]/div[2]/div/div[3]/div[1]/div[1]/div[2]/div/div/input") find.send_keys("Tirunelveli") sleep(2) search = driver.find_element_by_xpath( "/html/body/jsl/div[3]/div[9]/div[3]/div[1]/div[2]/div/div[3]/div[1]/div[1]/div[2]/button[1]") search.click() find() # get transportation detailsdef kilometers(): sleep(5) Totalkilometers = driver.find_element_by_xpath( "/html/body/jsl/div[3]/div[9]/div[7]/div/div[1]/div/div/div[5]/div[1]/div[1]/div[1]/div[1]/div[2]/div") print("Total Kilometers:", Totalkilometers.text) sleep(5) Bus = driver.find_element_by_xpath( "/html/body/jsl/div[3]/div[9]/div[7]/div/div[1]/div/div/div[5]/div[1]/div[1]/div[1]/div[1]/div[1]/span[1]") print("Bus Travel:", Bus.text) sleep(7) Train = driver.find_element_by_xpath( "/html/body/jsl/div[3]/div[9]/div[7]/div/div[1]/div/div/div[5]/div[2]/div[1]/div[2]/div[1]/div") print("Train Travel:", Train.text) sleep(7) kilometers() Output: Python Selenium-Exercises Python-selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25665, "s": 25637, "text": "\n04 Jan, 2021" }, { "code": null, "e": 25714, "s": 25665, "text": "Prerequisites: Browser Automation using Selenium" }, { "code": null, "e": 26003, "s": 25714, "text": "Selenium is a powerful tool for controlling a web browser through the program. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python. It can be installed using the below command:" }, { "code": null, "e": 26025, "s": 26003, "text": "pip install selenium\n" }, { "code": null, "e": 26203, "s": 26025, "text": "In this article, we are going to see how to automate the Google Maps search using selenium by getting the location of a place and its transportation details to another location." }, { "code": null, "e": 26226, "s": 26203, "text": "Step 1) Import modules" }, { "code": null, "e": 26234, "s": 26226, "text": "Python3" }, { "code": "# import required modulesfrom selenium import webdriverfrom time import sleep", "e": 26312, "s": 26234, "text": null }, { "code": null, "e": 26450, "s": 26312, "text": "Step 2) Mention the path of your chrome driver in the driver variable that you downloaded. And then we need to get a Google Maps website." }, { "code": null, "e": 26458, "s": 26450, "text": "Python3" }, { "code": "# assign url in the webdriver objectdriver = webdriver.Chrome()driver.get(\"https://www.google.co.in/maps/@10.8091781,78.2885026,7z\")sleep(2)", "e": 26599, "s": 26458, "text": null }, { "code": null, "e": 26940, "s": 26599, "text": "Step 3) Next step Declare a function under this function you need to inspect the search bar on the Google maps website. And Copy the Class name in the variable place. You need to send keys to a particular web element. Give your destination as an input. Provide the xpath value in the submit variable this is used to press the search button " }, { "code": null, "e": 26948, "s": 26940, "text": "Python3" }, { "code": "# search locationsdef searchplace(): Place = driver.find_element_by_class_name(\"tactile-searchbox-input\") Place.send_keys(\"Tiruchirappalli\") Submit = driver.find_element_by_xpath( \"/html/body/jsl/div[3]/div[9]/div[3]/div[1]/div[1]/div[1]/div[2]/div[1]/button\") Submit.click() searchplace()", "e": 27258, "s": 26948, "text": null }, { "code": null, "e": 27489, "s": 27258, "text": "Step 4) Declare a function called directions. Under this function, you need to send a click to the direction button. Copy the X path value of the directions button from the Google maps website. And paste the value in the variable." }, { "code": null, "e": 27497, "s": 27489, "text": "Python3" }, { "code": "# get directionsdef directions(): sleep(10) directions = driver.find_element_by_xpath( \"/html/body/jsl/div[3]/div[9]/div[7]/div/div[1]/div/div/div[5]/div[1]/div/button\") directions.click() directions()", "e": 27716, "s": 27497, "text": null }, { "code": null, "e": 27927, "s": 27716, "text": "Step 5) Declare a function called as find. Under this function, you need to create a variable and in this variable, you need to copy the xpath of the value of the search bar and paste the value in the variable." }, { "code": null, "e": 28074, "s": 27927, "text": "Next, Send the starting point to the particular search box. And You need to send a click button to the search button to follow the Step 1 Process." }, { "code": null, "e": 28082, "s": 28074, "text": "Python3" }, { "code": "# find placedef find(): sleep(6) find = driver.find_element_by_xpath( \"/html/body/jsl/div[3]/div[9]/div[3]/div[1]/div[2]/div/div[3]/div[1]/div[1]/div[2]/div/div/input\") find.send_keys(\"Tirunelveli\") sleep(2) search = driver.find_element_by_xpath( \"/html/body/jsl/div[3]/div[9]/div[3]/div[1]/div[2]/div/div[3]/div[1]/div[1]/div[2]/button[1]\") search.click() find()", "e": 28479, "s": 28082, "text": null }, { "code": null, "e": 28640, "s": 28479, "text": "Step 6) Now we need to scrap the essential data to complete our automation process. Here we need to copy the xpath values of Total kilometers between two places" }, { "code": null, "e": 28786, "s": 28640, "text": "Bus travel time and Train travel time between these two places. Here I extracted the data from the Google maps website by using the Web-Elements." }, { "code": null, "e": 28794, "s": 28786, "text": "Python3" }, { "code": "# get transportation detailsdef kilometers(): sleep(5) Totalkilometers = driver.find_element_by_xpath( \"/html/body/jsl/div[3]/div[9]/div[7]/div/div[1]/div/div/div[5]/div[1]/div[1]/div[1]/div[1]/div[2]/div\") print(\"Total Kilometers:\", Totalkilometers.text) sleep(5) Bus = driver.find_element_by_xpath( \"/html/body/jsl/div[3]/div[9]/div[7]/div/div[1]/div/div/div[5]/div[1]/div[1]/div[1]/div[1]/div[1]/span[1]\") print(\"Bus Travel:\", Bus.text) sleep(7) Train = driver.find_element_by_xpath( \"/html/body/jsl/div[3]/div[9]/div[7]/div/div[1]/div/div/div[5]/div[2]/div[1]/div[2]/div[1]/div\") print(\"Train Travel:\", Train.text) sleep(7) kilometers()", "e": 29487, "s": 28794, "text": null }, { "code": null, "e": 29546, "s": 29487, "text": "Below is the complete program based on the above approach:" }, { "code": null, "e": 29554, "s": 29546, "text": "Python3" }, { "code": "# import required modulesfrom selenium import webdriverfrom time import sleep # assign url in the webdriver objectdriver = webdriver.Chrome()driver.get(\"https://www.google.co.in/maps/@10.8091781,78.2885026,7z\")sleep(2) # search locationsdef searchplace(): Place = driver.find_element_by_class_name(\"tactile-searchbox-input\") Place.send_keys(\"Tiruchirappalli\") Submit = driver.find_element_by_xpath( \"/html/body/jsl/div[3]/div[9]/div[3]/div[1]/div[1]/div[1]/div[2]/div[1]/button\") Submit.click() searchplace() # get directionsdef directions(): sleep(10) directions = driver.find_element_by_xpath( \"/html/body/jsl/div[3]/div[9]/div[7]/div/div[1]/div/div/div[5]/div[1]/div/button\") directions.click() directions() # find placedef find(): sleep(6) find = driver.find_element_by_xpath( \"/html/body/jsl/div[3]/div[9]/div[3]/div[1]/div[2]/div/div[3]/div[1]/div[1]/div[2]/div/div/input\") find.send_keys(\"Tirunelveli\") sleep(2) search = driver.find_element_by_xpath( \"/html/body/jsl/div[3]/div[9]/div[3]/div[1]/div[2]/div/div[3]/div[1]/div[1]/div[2]/button[1]\") search.click() find() # get transportation detailsdef kilometers(): sleep(5) Totalkilometers = driver.find_element_by_xpath( \"/html/body/jsl/div[3]/div[9]/div[7]/div/div[1]/div/div/div[5]/div[1]/div[1]/div[1]/div[1]/div[2]/div\") print(\"Total Kilometers:\", Totalkilometers.text) sleep(5) Bus = driver.find_element_by_xpath( \"/html/body/jsl/div[3]/div[9]/div[7]/div/div[1]/div/div/div[5]/div[1]/div[1]/div[1]/div[1]/div[1]/span[1]\") print(\"Bus Travel:\", Bus.text) sleep(7) Train = driver.find_element_by_xpath( \"/html/body/jsl/div[3]/div[9]/div[7]/div/div[1]/div/div/div[5]/div[2]/div[1]/div[2]/div[1]/div\") print(\"Train Travel:\", Train.text) sleep(7) kilometers()", "e": 31407, "s": 29554, "text": null }, { "code": null, "e": 31415, "s": 31407, "text": "Output:" }, { "code": null, "e": 31441, "s": 31415, "text": "Python Selenium-Exercises" }, { "code": null, "e": 31457, "s": 31441, "text": "Python-selenium" }, { "code": null, "e": 31464, "s": 31457, "text": "Python" }, { "code": null, "e": 31562, "s": 31464, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31594, "s": 31562, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31636, "s": 31594, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 31678, "s": 31636, "text": "Check if element exists in list in Python" }, { "code": null, "e": 31734, "s": 31678, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 31761, "s": 31734, "text": "Python Classes and Objects" }, { "code": null, "e": 31792, "s": 31761, "text": "Python | os.path.join() method" }, { "code": null, "e": 31821, "s": 31792, "text": "Create a directory in Python" }, { "code": null, "e": 31843, "s": 31821, "text": "Defaultdict in Python" }, { "code": null, "e": 31882, "s": 31843, "text": "Python | Get unique values from a list" } ]
Arrays in C/C++ - GeeksforGeeks
27 Jan, 2022 An array in C/C++ or be it in any programming language is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They can be used to store collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in C/C++ can store derived data types such as the structures, pointers etc. Given below is the picture representation of an array. Why do we need arrays? We can use normal variables (v1, v2, v3, ..) when we have a small number of objects, but if we want to store a large number of instances, it becomes difficult to manage them with normal variables. The idea of an array is to represent many instances in one variable.Array declaration in C/C++: Note: In above image int a[3]={[0...1]=3}; this kind of declaration has been obsolete since GCC 2.5 There are various ways in which we can declare an array. It can be done by specifying its type and size, by initializing it or both. Array declaration by specifying size C // Array declaration by specifying sizeint arr1[10]; // With recent C/C++ versions, we can also// declare an array of user specified sizeint n = 10;int arr2[n]; Array declaration by initializing elements C // Array declaration by initializing elementsint arr[] = { 10, 20, 30, 40 } // Compiler creates an array of size 4.// above is same as "int arr[4] = {10, 20, 30, 40}" Array declaration by specifying size and initializing elements C // Array declaration by specifying size and initializing// elementsint arr[6] = { 10, 20, 30, 40 } // Compiler creates an array of size 6, initializes first// 4 elements as specified by user and rest two elements as// 0. above is same as "int arr[] = {10, 20, 30, 40, 0, 0}" Advantages of an Array in C/C++: Random access of elements using array index.Use of fewer line of code as it creates a single array of multiple elements.Easy access to all the elements.Traversal through the array becomes easy using a single loop.Sorting becomes easy as it can be accomplished by writing fewer line of code. Random access of elements using array index. Use of fewer line of code as it creates a single array of multiple elements. Easy access to all the elements. Traversal through the array becomes easy using a single loop. Sorting becomes easy as it can be accomplished by writing fewer line of code. Disadvantages of an Array in C/C++: Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in C is not dynamic.Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation. Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in C is not dynamic. Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation. Facts about Array in C/C++: Accessing Array Elements: Array elements are accessed by using an integer index. Array index starts with 0 and goes till size of array minus 1. Name of the array is also a pointer to the first element of array. Example: C C++ #include <stdio.h> int main(){ int arr[5]; arr[0] = 5; arr[2] = -10; arr[3 / 2] = 2; // this is same as arr[1] = 2 arr[3] = arr[0]; printf("%d %d %d %d", arr[0], arr[1], arr[2], arr[3]); return 0;} #include <iostream>using namespace std; int main(){ int arr[5]; arr[0] = 5; arr[2] = -10; // this is same as arr[1] = 2 arr[3 / 2] = 2; arr[3] = arr[0]; cout << arr[0] << " " << arr[1] << " " << arr[2] << " " << arr[3]; return 0;} Output 5 2 -10 5 No Index Out of bound Checking: There is no index out of bounds checking in C/C++, for example, the following program compiles fine but may produce unexpected output when run. C C++ // This C program compiles fine// as index out of bound// is not checked in C. #include <stdio.h> int main(){ int arr[2]; printf("%d ", arr[3]); printf("%d ", arr[-2]); return 0;} // This C++ program compiles fine// as index out of bound// is not checked in C. #include <iostream>using namespace std; int main(){ int arr[2]; cout << arr[3] << " "; cout << arr[-2] << " "; return 0;} -449684907 4195777 In C, it is not a compiler error to initialize an array with more elements than the specified size. For example, the below program compiles fine and shows just Warning. C #include <stdio.h>int main(){ // Array declaration by initializing it // with more elements than specified size. int arr[2] = { 10, 20, 30, 40, 50 }; return 0;} Warnings: prog.c: In function 'main': prog.c:7:25: warning: excess elements in array initializer int arr[2] = { 10, 20, 30, 40, 50 }; ^ prog.c:7:25: note: (near initialization for 'arr') prog.c:7:29: warning: excess elements in array initializer int arr[2] = { 10, 20, 30, 40, 50 }; ^ prog.c:7:29: note: (near initialization for 'arr') prog.c:7:33: warning: excess elements in array initializer int arr[2] = { 10, 20, 30, 40, 50 }; ^ prog.c:7:33: note: (near initialization for 'arr') Note: The program won’t compile in C++. If we save the above program as a .cpp, the program generates compiler error “error: too many initializers for ‘int [2]'”. The elements are stored at contiguous memory locations Example: C C++ // C program to demonstrate that// array elements are stored// contiguous locations #include <stdio.h>int main(){ // an array of 10 integers. // If arr[0] is stored at // address x, then arr[1] is // stored at x + sizeof(int) // arr[2] is stored at x + // sizeof(int) + sizeof(int) // and so on. int arr[5], i; printf("Size of integer in this compiler is %lu\n", sizeof(int)); for (i = 0; i < 5; i++) // The use of '&' before a variable name, yields // address of variable. printf("Address arr[%d] is %p\n", i, &arr[i]); return 0;} // C++ program to demonstrate that array elements// are stored contiguous locations #include <iostream>using namespace std; int main(){ // an array of 10 integers. // If arr[0] is stored at // address x, then arr[1] is // stored at x + sizeof(int) // arr[2] is stored at x + // sizeof(int) + sizeof(int) // and so on. int arr[5], i; cout << "Size of integer in this compiler is " << sizeof(int) << "\n"; for (i = 0; i < 5; i++) // The use of '&' before a variable name, yields // address of variable. cout << "Address arr[" << i << "] is " << &arr[i] << "\n"; return 0;} Size of integer in this compiler is 4 Address arr[0] is 0x7ffe75c32210 Address arr[1] is 0x7ffe75c32214 Address arr[2] is 0x7ffe75c32218 Address arr[3] is 0x7ffe75c3221c Address arr[4] is 0x7ffe75c32220 Another way to traverse the array C++ #include<bits/stdc++.h>using namespace std; int main(){ int arr[6]={11,12,13,14,15,16}; // Way 1 for(int i=0;i<6;i++) cout<<arr[i]<<" "; cout<<endl; // Way 2 cout<<"By Other Method:"<<endl; for(int i=0;i<6;i++) cout<<i[arr]<<" "; cout<<endl; return 0;} // Contributed by Akshay Pawar ( Username - akshaypawar4) 11 12 13 14 15 16 By Other Method: 11 12 13 14 15 16 Array vs Pointers Arrays and pointers are two different things (we can check by applying sizeof). The confusion happens because array name indicates the address of first element and arrays are always passed as pointers (even if we use square bracket). Please see Difference between pointer and array in C? for more details.What is vector in C++? A vector in C++ is a class in STL that represents an array. The advantages of vector over normal arrays are, We do not need pass size as an extra parameter when we declare a vector i.e, Vectors support dynamic sizes (we do not have to initially specify size of a vector). We can also resize a vector. Vectors have many in-built functions like, removing an element, etc. To know more about functionalities provided by vector, please refer vector in C++ for more details. YouTubeGeeksforGeeks500K subscribersC++ Programming Language Tutorial | Introduction to Arrays in C++ | 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 / 2:34•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=eOdNhPwOInc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> sameer2209 RishabhPrabhu AnkurVineet jsanjana96 hrishi007 akshaypawar4 prathamjainyt nikhilpanchal kumarv456 venodpi bharadwajramendra1 kumarnitin akhilesh80025 C Array and String C Basics CBSE - Class 11 cpp-array CPP-Basics Arrays C Language C++ School Programming Arrays CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray Linear Search Multidimensional Arrays in Java Maximum and minimum of an array using minimum number of comparisons Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() std::sort() in C++ STL Multidimensional Arrays in C / C++ Bitwise Operators in C/C++ rand() and srand() in C/C++
[ { "code": null, "e": 37678, "s": 37650, "text": "\n27 Jan, 2022" }, { "code": null, "e": 38153, "s": 37678, "text": "An array in C/C++ or be it in any programming language is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They can be used to store collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in C/C++ can store derived data types such as the structures, pointers etc. Given below is the picture representation of an array. " }, { "code": null, "e": 38471, "s": 38153, "text": "Why do we need arrays? We can use normal variables (v1, v2, v3, ..) when we have a small number of objects, but if we want to store a large number of instances, it becomes difficult to manage them with normal variables. The idea of an array is to represent many instances in one variable.Array declaration in C/C++: " }, { "code": null, "e": 38573, "s": 38473, "text": "Note: In above image int a[3]={[0...1]=3}; this kind of declaration has been obsolete since GCC 2.5" }, { "code": null, "e": 38706, "s": 38573, "text": "There are various ways in which we can declare an array. It can be done by specifying its type and size, by initializing it or both." }, { "code": null, "e": 38744, "s": 38706, "text": "Array declaration by specifying size " }, { "code": null, "e": 38746, "s": 38744, "text": "C" }, { "code": "// Array declaration by specifying sizeint arr1[10]; // With recent C/C++ versions, we can also// declare an array of user specified sizeint n = 10;int arr2[n];", "e": 38908, "s": 38746, "text": null }, { "code": null, "e": 38951, "s": 38908, "text": "Array declaration by initializing elements" }, { "code": null, "e": 38953, "s": 38951, "text": "C" }, { "code": "// Array declaration by initializing elementsint arr[] = { 10, 20, 30, 40 } // Compiler creates an array of size 4.// above is same as \"int arr[4] = {10, 20, 30, 40}\"", "e": 39122, "s": 38953, "text": null }, { "code": null, "e": 39185, "s": 39122, "text": "Array declaration by specifying size and initializing elements" }, { "code": null, "e": 39187, "s": 39185, "text": "C" }, { "code": "// Array declaration by specifying size and initializing// elementsint arr[6] = { 10, 20, 30, 40 } // Compiler creates an array of size 6, initializes first// 4 elements as specified by user and rest two elements as// 0. above is same as \"int arr[] = {10, 20, 30, 40, 0, 0}\"", "e": 39464, "s": 39187, "text": null }, { "code": null, "e": 39498, "s": 39464, "text": "Advantages of an Array in C/C++: " }, { "code": null, "e": 39789, "s": 39498, "text": "Random access of elements using array index.Use of fewer line of code as it creates a single array of multiple elements.Easy access to all the elements.Traversal through the array becomes easy using a single loop.Sorting becomes easy as it can be accomplished by writing fewer line of code." }, { "code": null, "e": 39834, "s": 39789, "text": "Random access of elements using array index." }, { "code": null, "e": 39911, "s": 39834, "text": "Use of fewer line of code as it creates a single array of multiple elements." }, { "code": null, "e": 39944, "s": 39911, "text": "Easy access to all the elements." }, { "code": null, "e": 40006, "s": 39944, "text": "Traversal through the array becomes easy using a single loop." }, { "code": null, "e": 40084, "s": 40006, "text": "Sorting becomes easy as it can be accomplished by writing fewer line of code." }, { "code": null, "e": 40121, "s": 40084, "text": "Disadvantages of an Array in C/C++: " }, { "code": null, "e": 40404, "s": 40121, "text": "Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in C is not dynamic.Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation." }, { "code": null, "e": 40549, "s": 40404, "text": "Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in C is not dynamic." }, { "code": null, "e": 40688, "s": 40549, "text": "Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation." }, { "code": null, "e": 40717, "s": 40688, "text": "Facts about Array in C/C++: " }, { "code": null, "e": 40861, "s": 40717, "text": "Accessing Array Elements: Array elements are accessed by using an integer index. Array index starts with 0 and goes till size of array minus 1." }, { "code": null, "e": 40929, "s": 40861, "text": "Name of the array is also a pointer to the first element of array. " }, { "code": null, "e": 40939, "s": 40929, "text": "Example: " }, { "code": null, "e": 40941, "s": 40939, "text": "C" }, { "code": null, "e": 40945, "s": 40941, "text": "C++" }, { "code": "#include <stdio.h> int main(){ int arr[5]; arr[0] = 5; arr[2] = -10; arr[3 / 2] = 2; // this is same as arr[1] = 2 arr[3] = arr[0]; printf(\"%d %d %d %d\", arr[0], arr[1], arr[2], arr[3]); return 0;}", "e": 41180, "s": 40945, "text": null }, { "code": "#include <iostream>using namespace std; int main(){ int arr[5]; arr[0] = 5; arr[2] = -10; // this is same as arr[1] = 2 arr[3 / 2] = 2; arr[3] = arr[0]; cout << arr[0] << \" \" << arr[1] << \" \" << arr[2] << \" \" << arr[3]; return 0;}", "e": 41450, "s": 41180, "text": null }, { "code": null, "e": 41457, "s": 41450, "text": "Output" }, { "code": null, "e": 41467, "s": 41457, "text": "5 2 -10 5" }, { "code": null, "e": 41645, "s": 41467, "text": "No Index Out of bound Checking: There is no index out of bounds checking in C/C++, for example, the following program compiles fine but may produce unexpected output when run. " }, { "code": null, "e": 41647, "s": 41645, "text": "C" }, { "code": null, "e": 41651, "s": 41647, "text": "C++" }, { "code": "// This C program compiles fine// as index out of bound// is not checked in C. #include <stdio.h> int main(){ int arr[2]; printf(\"%d \", arr[3]); printf(\"%d \", arr[-2]); return 0;}", "e": 41849, "s": 41651, "text": null }, { "code": "// This C++ program compiles fine// as index out of bound// is not checked in C. #include <iostream>using namespace std; int main(){ int arr[2]; cout << arr[3] << \" \"; cout << arr[-2] << \" \"; return 0;}", "e": 42070, "s": 41849, "text": null }, { "code": null, "e": 42090, "s": 42070, "text": "-449684907 4195777 " }, { "code": null, "e": 42259, "s": 42090, "text": "In C, it is not a compiler error to initialize an array with more elements than the specified size. For example, the below program compiles fine and shows just Warning." }, { "code": null, "e": 42261, "s": 42259, "text": "C" }, { "code": "#include <stdio.h>int main(){ // Array declaration by initializing it // with more elements than specified size. int arr[2] = { 10, 20, 30, 40, 50 }; return 0;}", "e": 42439, "s": 42261, "text": null }, { "code": null, "e": 42450, "s": 42439, "text": "Warnings: " }, { "code": null, "e": 43018, "s": 42450, "text": "prog.c: In function 'main':\nprog.c:7:25: warning: excess elements in array initializer\n int arr[2] = { 10, 20, 30, 40, 50 };\n ^\nprog.c:7:25: note: (near initialization for 'arr')\nprog.c:7:29: warning: excess elements in array initializer\n int arr[2] = { 10, 20, 30, 40, 50 };\n ^\nprog.c:7:29: note: (near initialization for 'arr')\nprog.c:7:33: warning: excess elements in array initializer\n int arr[2] = { 10, 20, 30, 40, 50 };\n ^\nprog.c:7:33: note: (near initialization for 'arr')" }, { "code": null, "e": 43183, "s": 43018, "text": "Note: The program won’t compile in C++. If we save the above program as a .cpp, the program generates compiler error “error: too many initializers for ‘int [2]'”. " }, { "code": null, "e": 43248, "s": 43183, "text": "The elements are stored at contiguous memory locations Example: " }, { "code": null, "e": 43250, "s": 43248, "text": "C" }, { "code": null, "e": 43254, "s": 43250, "text": "C++" }, { "code": "// C program to demonstrate that// array elements are stored// contiguous locations #include <stdio.h>int main(){ // an array of 10 integers. // If arr[0] is stored at // address x, then arr[1] is // stored at x + sizeof(int) // arr[2] is stored at x + // sizeof(int) + sizeof(int) // and so on. int arr[5], i; printf(\"Size of integer in this compiler is %lu\\n\", sizeof(int)); for (i = 0; i < 5; i++) // The use of '&' before a variable name, yields // address of variable. printf(\"Address arr[%d] is %p\\n\", i, &arr[i]); return 0;}", "e": 43860, "s": 43254, "text": null }, { "code": "// C++ program to demonstrate that array elements// are stored contiguous locations #include <iostream>using namespace std; int main(){ // an array of 10 integers. // If arr[0] is stored at // address x, then arr[1] is // stored at x + sizeof(int) // arr[2] is stored at x + // sizeof(int) + sizeof(int) // and so on. int arr[5], i; cout << \"Size of integer in this compiler is \" << sizeof(int) << \"\\n\"; for (i = 0; i < 5; i++) // The use of '&' before a variable name, yields // address of variable. cout << \"Address arr[\" << i << \"] is \" << &arr[i] << \"\\n\"; return 0;}", "e": 44517, "s": 43860, "text": null }, { "code": null, "e": 44720, "s": 44517, "text": "Size of integer in this compiler is 4\nAddress arr[0] is 0x7ffe75c32210\nAddress arr[1] is 0x7ffe75c32214\nAddress arr[2] is 0x7ffe75c32218\nAddress arr[3] is 0x7ffe75c3221c\nAddress arr[4] is 0x7ffe75c32220" }, { "code": null, "e": 44754, "s": 44720, "text": "Another way to traverse the array" }, { "code": null, "e": 44758, "s": 44754, "text": "C++" }, { "code": "#include<bits/stdc++.h>using namespace std; int main(){ int arr[6]={11,12,13,14,15,16}; // Way 1 for(int i=0;i<6;i++) cout<<arr[i]<<\" \"; cout<<endl; // Way 2 cout<<\"By Other Method:\"<<endl; for(int i=0;i<6;i++) cout<<i[arr]<<\" \"; cout<<endl; return 0;} // Contributed by Akshay Pawar ( Username - akshaypawar4)", "e": 45125, "s": 44758, "text": null }, { "code": null, "e": 45180, "s": 45125, "text": "11 12 13 14 15 16 \nBy Other Method:\n11 12 13 14 15 16 " }, { "code": null, "e": 45636, "s": 45180, "text": "Array vs Pointers Arrays and pointers are two different things (we can check by applying sizeof). The confusion happens because array name indicates the address of first element and arrays are always passed as pointers (even if we use square bracket). Please see Difference between pointer and array in C? for more details.What is vector in C++? A vector in C++ is a class in STL that represents an array. The advantages of vector over normal arrays are, " }, { "code": null, "e": 45828, "s": 45636, "text": "We do not need pass size as an extra parameter when we declare a vector i.e, Vectors support dynamic sizes (we do not have to initially specify size of a vector). We can also resize a vector." }, { "code": null, "e": 45897, "s": 45828, "text": "Vectors have many in-built functions like, removing an element, etc." }, { "code": null, "e": 45997, "s": 45897, "text": "To know more about functionalities provided by vector, please refer vector in C++ for more details." }, { "code": null, "e": 46863, "s": 45999, "text": "YouTubeGeeksforGeeks500K subscribersC++ Programming Language Tutorial | Introduction to Arrays in C++ | 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 / 2:34•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=eOdNhPwOInc\" 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": 46876, "s": 46865, "text": "sameer2209" }, { "code": null, "e": 46890, "s": 46876, "text": "RishabhPrabhu" }, { "code": null, "e": 46902, "s": 46890, "text": "AnkurVineet" }, { "code": null, "e": 46913, "s": 46902, "text": "jsanjana96" }, { "code": null, "e": 46923, "s": 46913, "text": "hrishi007" }, { "code": null, "e": 46936, "s": 46923, "text": "akshaypawar4" }, { "code": null, "e": 46950, "s": 46936, "text": "prathamjainyt" }, { "code": null, "e": 46964, "s": 46950, "text": "nikhilpanchal" }, { "code": null, "e": 46974, "s": 46964, "text": "kumarv456" }, { "code": null, "e": 46982, "s": 46974, "text": "venodpi" }, { "code": null, "e": 47001, "s": 46982, "text": "bharadwajramendra1" }, { "code": null, "e": 47012, "s": 47001, "text": "kumarnitin" }, { "code": null, "e": 47026, "s": 47012, "text": "akhilesh80025" }, { "code": null, "e": 47045, "s": 47026, "text": "C Array and String" }, { "code": null, "e": 47054, "s": 47045, "text": "C Basics" }, { "code": null, "e": 47070, "s": 47054, "text": "CBSE - Class 11" }, { "code": null, "e": 47080, "s": 47070, "text": "cpp-array" }, { "code": null, "e": 47091, "s": 47080, "text": "CPP-Basics" }, { "code": null, "e": 47098, "s": 47091, "text": "Arrays" }, { "code": null, "e": 47109, "s": 47098, "text": "C Language" }, { "code": null, "e": 47113, "s": 47109, "text": "C++" }, { "code": null, "e": 47132, "s": 47113, "text": "School Programming" }, { "code": null, "e": 47139, "s": 47132, "text": "Arrays" }, { "code": null, "e": 47143, "s": 47139, "text": "CPP" }, { "code": null, "e": 47241, "s": 47143, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47250, "s": 47241, "text": "Comments" }, { "code": null, "e": 47263, "s": 47250, "text": "Old Comments" }, { "code": null, "e": 47307, "s": 47263, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 47339, "s": 47307, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 47353, "s": 47339, "text": "Linear Search" }, { "code": null, "e": 47385, "s": 47353, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 47453, "s": 47385, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 47531, "s": 47453, "text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()" }, { "code": null, "e": 47554, "s": 47531, "text": "std::sort() in C++ STL" }, { "code": null, "e": 47589, "s": 47554, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 47616, "s": 47589, "text": "Bitwise Operators in C/C++" } ]
C++ Dynamic Memory
A good understanding of how dynamic memory really works in C++ is essential to becoming a good C++ programmer. Memory in your C++ program is divided into two parts − The stack − All variables declared inside the function will take up memory from the stack. The stack − All variables declared inside the function will take up memory from the stack. The heap − This is unused memory of the program and can be used to allocate the memory dynamically when program runs. The heap − This is unused memory of the program and can be used to allocate the memory dynamically when program runs. Many times, you are not aware in advance how much memory you will need to store particular information in a defined variable and the size of required memory can be determined at run time. You can allocate memory at run time within the heap for the variable of a given type using a special operator in C++ which returns the address of the space allocated. This operator is called new operator. If you are not in need of dynamically allocated memory anymore, you can use delete operator, which de-allocates memory that was previously allocated by new operator. There is following generic syntax to use new operator to allocate memory dynamically for any data-type. new data-type; Here, data-type could be any built-in data type including an array or any user defined data types include class or structure. Let us start with built-in data types. For example we can define a pointer to type double and then request that the memory be allocated at execution time. We can do this using the new operator with the following statements − double* pvalue = NULL; // Pointer initialized with null pvalue = new double; // Request memory for the variable The memory may not have been allocated successfully, if the free store had been used up. So it is good practice to check if new operator is returning NULL pointer and take appropriate action as below − double* pvalue = NULL; if( !(pvalue = new double )) { cout << "Error: out of memory." <<endl; exit(1); } The malloc() function from C, still exists in C++, but it is recommended to avoid using malloc() function. The main advantage of new over malloc() is that new doesn't just allocate memory, it constructs objects which is prime purpose of C++. At any point, when you feel a variable that has been dynamically allocated is not anymore required, you can free up the memory that it occupies in the free store with the ‘delete’ operator as follows − delete pvalue; // Release memory pointed to by pvalue Let us put above concepts and form the following example to show how ‘new’ and ‘delete’ work − #include <iostream> using namespace std; int main () { double* pvalue = NULL; // Pointer initialized with null pvalue = new double; // Request memory for the variable *pvalue = 29494.99; // Store value at allocated address cout << "Value of pvalue : " << *pvalue << endl; delete pvalue; // free up the memory. return 0; } If we compile and run above code, this would produce the following result − Value of pvalue : 29495 Consider you want to allocate memory for an array of characters, i.e., string of 20 characters. Using the same syntax what we have used above we can allocate memory dynamically as shown below. char* pvalue = NULL; // Pointer initialized with null pvalue = new char[20]; // Request memory for the variable To remove the array that we have just created the statement would look like this − delete [] pvalue; // Delete array pointed to by pvalue Following the similar generic syntax of new operator, you can allocate for a multi-dimensional array as follows − double** pvalue = NULL; // Pointer initialized with null pvalue = new double [3][4]; // Allocate memory for a 3x4 array However, the syntax to release the memory for multi-dimensional array will still remain same as above − delete [] pvalue; // Delete array pointed to by pvalue Objects are no different from simple data types. For example, consider the following code where we are going to use an array of objects to clarify the concept − #include <iostream> using namespace std; class Box { public: Box() { cout << "Constructor called!" <<endl; } ~Box() { cout << "Destructor called!" <<endl; } }; int main() { Box* myBoxArray = new Box[4]; delete [] myBoxArray; // Delete array return 0; } If you were to allocate an array of four Box objects, the Simple constructor would be called four times and similarly while deleting these objects, destructor will also be called same number of times. If we compile and run above code, this would produce the following result − Constructor called! Constructor called! Constructor called! Constructor called! Destructor called! Destructor called! Destructor called! Destructor called! 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2484, "s": 2318, "text": "A good understanding of how dynamic memory really works in C++ is essential to becoming a good C++ programmer. Memory in your C++ program is divided into two parts −" }, { "code": null, "e": 2575, "s": 2484, "text": "The stack − All variables declared inside the function will take up memory from the stack." }, { "code": null, "e": 2666, "s": 2575, "text": "The stack − All variables declared inside the function will take up memory from the stack." }, { "code": null, "e": 2784, "s": 2666, "text": "The heap − This is unused memory of the program and can be used to allocate the memory dynamically when program runs." }, { "code": null, "e": 2902, "s": 2784, "text": "The heap − This is unused memory of the program and can be used to allocate the memory dynamically when program runs." }, { "code": null, "e": 3090, "s": 2902, "text": "Many times, you are not aware in advance how much memory you will need to store particular information in a defined variable and the size of required memory can be determined at run time." }, { "code": null, "e": 3295, "s": 3090, "text": "You can allocate memory at run time within the heap for the variable of a given type using a special operator in C++ which returns the address of the space allocated. This operator is called new operator." }, { "code": null, "e": 3461, "s": 3295, "text": "If you are not in need of dynamically allocated memory anymore, you can use delete operator, which de-allocates memory that was previously allocated by new operator." }, { "code": null, "e": 3565, "s": 3461, "text": "There is following generic syntax to use new operator to allocate memory dynamically for any data-type." }, { "code": null, "e": 3581, "s": 3565, "text": "new data-type;\n" }, { "code": null, "e": 3933, "s": 3581, "text": "Here, data-type could be any built-in data type including an array or any user defined data types include class or structure. Let us start with built-in data types. For example we can define a pointer to type double and then request that the memory be allocated at execution time. We can do this using the new operator with the following statements −" }, { "code": null, "e": 4050, "s": 3933, "text": "double* pvalue = NULL; // Pointer initialized with null\npvalue = new double; // Request memory for the variable\n" }, { "code": null, "e": 4252, "s": 4050, "text": "The memory may not have been allocated successfully, if the free store had been used up. So it is good practice to check if new operator is returning NULL pointer and take appropriate action as below −" }, { "code": null, "e": 4366, "s": 4252, "text": "double* pvalue = NULL;\nif( !(pvalue = new double )) {\n cout << \"Error: out of memory.\" <<endl;\n exit(1);\n}\n" }, { "code": null, "e": 4608, "s": 4366, "text": "The malloc() function from C, still exists in C++, but it is recommended to avoid using malloc() function. The main advantage of new over malloc() is that new doesn't just allocate memory, it constructs objects which is prime purpose of C++." }, { "code": null, "e": 4810, "s": 4608, "text": "At any point, when you feel a variable that has been dynamically allocated is not anymore required, you can free up the memory that it occupies in the free store with the ‘delete’ operator as follows −" }, { "code": null, "e": 4872, "s": 4810, "text": "delete pvalue; // Release memory pointed to by pvalue\n" }, { "code": null, "e": 4967, "s": 4872, "text": "Let us put above concepts and form the following example to show how ‘new’ and ‘delete’ work −" }, { "code": null, "e": 5328, "s": 4967, "text": "#include <iostream>\nusing namespace std;\n\nint main () {\n double* pvalue = NULL; // Pointer initialized with null\n pvalue = new double; // Request memory for the variable\n \n *pvalue = 29494.99; // Store value at allocated address\n cout << \"Value of pvalue : \" << *pvalue << endl;\n\n delete pvalue; // free up the memory.\n\n return 0;\n}" }, { "code": null, "e": 5404, "s": 5328, "text": "If we compile and run above code, this would produce the following result −" }, { "code": null, "e": 5429, "s": 5404, "text": "Value of pvalue : 29495\n" }, { "code": null, "e": 5622, "s": 5429, "text": "Consider you want to allocate memory for an array of characters, i.e., string of 20 characters. Using the same syntax what we have used above we can allocate memory dynamically as shown below." }, { "code": null, "e": 5751, "s": 5622, "text": "char* pvalue = NULL; // Pointer initialized with null\npvalue = new char[20]; // Request memory for the variable\n" }, { "code": null, "e": 5834, "s": 5751, "text": "To remove the array that we have just created the statement would look like this −" }, { "code": null, "e": 5902, "s": 5834, "text": "delete [] pvalue; // Delete array pointed to by pvalue\n" }, { "code": null, "e": 6016, "s": 5902, "text": "Following the similar generic syntax of new operator, you can allocate for a multi-dimensional array as follows −" }, { "code": null, "e": 6147, "s": 6016, "text": "double** pvalue = NULL; // Pointer initialized with null \npvalue = new double [3][4]; // Allocate memory for a 3x4 array \n" }, { "code": null, "e": 6251, "s": 6147, "text": "However, the syntax to release the memory for multi-dimensional array will still remain same as above −" }, { "code": null, "e": 6318, "s": 6251, "text": "delete [] pvalue; // Delete array pointed to by pvalue\n" }, { "code": null, "e": 6479, "s": 6318, "text": "Objects are no different from simple data types. For example, consider the following code where we are going to use an array of objects to clarify the concept −" }, { "code": null, "e": 6792, "s": 6479, "text": "#include <iostream>\nusing namespace std;\n\nclass Box {\n public:\n Box() { \n cout << \"Constructor called!\" <<endl; \n }\n ~Box() { \n cout << \"Destructor called!\" <<endl; \n }\n};\nint main() {\n Box* myBoxArray = new Box[4];\n delete [] myBoxArray; // Delete array\n\n return 0;\n}" }, { "code": null, "e": 6993, "s": 6792, "text": "If you were to allocate an array of four Box objects, the Simple constructor would be called four times and similarly while deleting these objects, destructor will also be called same number of times." }, { "code": null, "e": 7069, "s": 6993, "text": "If we compile and run above code, this would produce the following result −" }, { "code": null, "e": 7226, "s": 7069, "text": "Constructor called!\nConstructor called!\nConstructor called!\nConstructor called!\nDestructor called!\nDestructor called!\nDestructor called!\nDestructor called!\n" }, { "code": null, "e": 7263, "s": 7226, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 7282, "s": 7263, "text": " Arnab Chakraborty" }, { "code": null, "e": 7314, "s": 7282, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 7337, "s": 7314, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 7373, "s": 7337, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 7390, "s": 7373, "text": " Frahaan Hussain" }, { "code": null, "e": 7425, "s": 7390, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7442, "s": 7425, "text": " Frahaan Hussain" }, { "code": null, "e": 7477, "s": 7442, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7494, "s": 7477, "text": " Frahaan Hussain" }, { "code": null, "e": 7529, "s": 7494, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7546, "s": 7529, "text": " Frahaan Hussain" }, { "code": null, "e": 7553, "s": 7546, "text": " Print" }, { "code": null, "e": 7564, "s": 7553, "text": " Add Notes" } ]
Using the Pandas Append Function for Dataframes | by Matt Przybyla | Towards Data Science
DatasetPandasAppendTutorial CodeSummaryReferences Dataset Pandas Append Tutorial Code Summary References The dataset used in this analysis and tutorial for the pandas append function is a dummy dataset created to mimic a dataframe with both text and numeric features. Feel free to use your own csv file with either or both text and numeric columns to follow the tutorial below. Pandas [2] is one of the most common libraries used by data scientists and machine learning engineers. It is mainly used in the exploratory data analysis step of building a model, as well as the ad-hoc analysis of model results. It also contains several functions, including the append function. While I previously wrote an article [3] about the pandas query function that referenced adding multiple rows, I thought it would be useful to highlight the benefits of the append function itself. The append function works by adding new rows to an existing dataframe. The rows are created by utilizing the Series function, which stores values that will then be appended to the order of columns that are listed in the index argument. Some benefits of the append function include: works with pandas dataframe works in conjunction with pandas Series function quick method of adding new data to existing data In the code snippet below, the dummy data was missing some information. In order to solve this issue, I looked to the append method. Using the append function, I could easily add new rows without losing the data and integrity of the original dataframe. First, I imported the pandas library and created the alias ‘pd’ — this alias helped to use the pandas library in a short-hand format. Next, I read in my dataframe from an existing csv file, referencing the location and path that it is on my local drive. I printed out the dataframe to see what the first five rows looked like. The next step is where I setup up the code for the append function. Using the Series function to, in order, place values — either text or numeric in this case as a list, and then indexing it on the respective columns itself, the new rows were written out and saved as ‘rows’. The actual append function itself is fairly simple; passing the rows as the first argument, and then setting the ‘ignore_index’ to ‘True’, the index labels were not used. Lastly, I checked to see if my rows were made correctly by using the tail function that returns the dataframe with the last three rows from the append code. Here is a screenshot of all the code I used below: Here is the code [5] for easy referencing. Feel free to import your own data and reference your own file pathway, as well as change the data values in the Series to see how appending works in your python environment or jupyter notebook. # All the python code below for use:# import libraryimport pandas as pd# read in your dataframedf = pd.read_csv('/Users/data.csv')# print out your first five rowsdf.head()# write out new rowsrows = [pd.Series([200, 200, 30,'Yellow','Label_1'], index=df.columns),pd.Series([200, 120, 40,'Red','Label_2'], index=df.columns),pd.Series([120, 40, 200,'Red','Label_3'], index=df.columns)]# append the multiple rowsnew_df = df.append(rows, ignore_index=True)# check the newest 3 rows you madenew_df.tail(3) To see my code in python-format rather than a screenshot or written out, here is the embedded gist [5]: The append function is a simple and fast way to add new data to your dataframe. The Series function was also referenced in order to save the rows that would later be appended. I hope this tutorial is helpful to you when creating your data and performing exploratory data analysis on your dataframe, before ultimately creating a data science and machine learning model. Thank you for reading! As mentioned above, please feel free to read my similar article that goes over that pandas query function. [1] T.Lundqvist, Unsplash (2017) [2] pandas, pandas (2020) [3] M.Przybyla, article (2020) [4] M.Przybyla, screenshot (2020) [5] M.Przybyla, gist (2020)
[ { "code": null, "e": 222, "s": 172, "text": "DatasetPandasAppendTutorial CodeSummaryReferences" }, { "code": null, "e": 230, "s": 222, "text": "Dataset" }, { "code": null, "e": 237, "s": 230, "text": "Pandas" }, { "code": null, "e": 244, "s": 237, "text": "Append" }, { "code": null, "e": 258, "s": 244, "text": "Tutorial Code" }, { "code": null, "e": 266, "s": 258, "text": "Summary" }, { "code": null, "e": 277, "s": 266, "text": "References" }, { "code": null, "e": 550, "s": 277, "text": "The dataset used in this analysis and tutorial for the pandas append function is a dummy dataset created to mimic a dataframe with both text and numeric features. Feel free to use your own csv file with either or both text and numeric columns to follow the tutorial below." }, { "code": null, "e": 846, "s": 550, "text": "Pandas [2] is one of the most common libraries used by data scientists and machine learning engineers. It is mainly used in the exploratory data analysis step of building a model, as well as the ad-hoc analysis of model results. It also contains several functions, including the append function." }, { "code": null, "e": 1278, "s": 846, "text": "While I previously wrote an article [3] about the pandas query function that referenced adding multiple rows, I thought it would be useful to highlight the benefits of the append function itself. The append function works by adding new rows to an existing dataframe. The rows are created by utilizing the Series function, which stores values that will then be appended to the order of columns that are listed in the index argument." }, { "code": null, "e": 1324, "s": 1278, "text": "Some benefits of the append function include:" }, { "code": null, "e": 1352, "s": 1324, "text": "works with pandas dataframe" }, { "code": null, "e": 1401, "s": 1352, "text": "works in conjunction with pandas Series function" }, { "code": null, "e": 1450, "s": 1401, "text": "quick method of adding new data to existing data" }, { "code": null, "e": 2306, "s": 1450, "text": "In the code snippet below, the dummy data was missing some information. In order to solve this issue, I looked to the append method. Using the append function, I could easily add new rows without losing the data and integrity of the original dataframe. First, I imported the pandas library and created the alias ‘pd’ — this alias helped to use the pandas library in a short-hand format. Next, I read in my dataframe from an existing csv file, referencing the location and path that it is on my local drive. I printed out the dataframe to see what the first five rows looked like. The next step is where I setup up the code for the append function. Using the Series function to, in order, place values — either text or numeric in this case as a list, and then indexing it on the respective columns itself, the new rows were written out and saved as ‘rows’." }, { "code": null, "e": 2634, "s": 2306, "text": "The actual append function itself is fairly simple; passing the rows as the first argument, and then setting the ‘ignore_index’ to ‘True’, the index labels were not used. Lastly, I checked to see if my rows were made correctly by using the tail function that returns the dataframe with the last three rows from the append code." }, { "code": null, "e": 2685, "s": 2634, "text": "Here is a screenshot of all the code I used below:" }, { "code": null, "e": 2922, "s": 2685, "text": "Here is the code [5] for easy referencing. Feel free to import your own data and reference your own file pathway, as well as change the data values in the Series to see how appending works in your python environment or jupyter notebook." }, { "code": null, "e": 3422, "s": 2922, "text": "# All the python code below for use:# import libraryimport pandas as pd# read in your dataframedf = pd.read_csv('/Users/data.csv')# print out your first five rowsdf.head()# write out new rowsrows = [pd.Series([200, 200, 30,'Yellow','Label_1'], index=df.columns),pd.Series([200, 120, 40,'Red','Label_2'], index=df.columns),pd.Series([120, 40, 200,'Red','Label_3'], index=df.columns)]# append the multiple rowsnew_df = df.append(rows, ignore_index=True)# check the newest 3 rows you madenew_df.tail(3)" }, { "code": null, "e": 3526, "s": 3422, "text": "To see my code in python-format rather than a screenshot or written out, here is the embedded gist [5]:" }, { "code": null, "e": 4025, "s": 3526, "text": "The append function is a simple and fast way to add new data to your dataframe. The Series function was also referenced in order to save the rows that would later be appended. I hope this tutorial is helpful to you when creating your data and performing exploratory data analysis on your dataframe, before ultimately creating a data science and machine learning model. Thank you for reading! As mentioned above, please feel free to read my similar article that goes over that pandas query function." }, { "code": null, "e": 4058, "s": 4025, "text": "[1] T.Lundqvist, Unsplash (2017)" }, { "code": null, "e": 4084, "s": 4058, "text": "[2] pandas, pandas (2020)" }, { "code": null, "e": 4115, "s": 4084, "text": "[3] M.Przybyla, article (2020)" }, { "code": null, "e": 4149, "s": 4115, "text": "[4] M.Przybyla, screenshot (2020)" } ]
How to set the margins of an element with JavaScript?
Use the margin property in JavaScript, to set the margins. You can try to run the following code to set the margins of an element with JavaScript − Live Demo <!DOCTYPE html> <html> <body> <button type="button" onclick="display()">Set all four margins</button> <p id="myID">This is demo text.</p> <script> function display() { document.getElementById("myID").style.margin = "30px 20px 40px 40px"; } </script> </body> </html>
[ { "code": null, "e": 1210, "s": 1062, "text": "Use the margin property in JavaScript, to set the margins. You can try to run the following code to set the margins of an element with JavaScript −" }, { "code": null, "e": 1220, "s": 1210, "text": "Live Demo" }, { "code": null, "e": 1546, "s": 1220, "text": "<!DOCTYPE html>\n<html>\n <body>\n <button type=\"button\" onclick=\"display()\">Set all four margins</button>\n <p id=\"myID\">This is demo text.</p>\n <script>\n function display() {\n document.getElementById(\"myID\").style.margin = \"30px 20px 40px 40px\";\n }\n </script>\n </body>\n</html>" } ]
How to create an ArrayList from an Array in Java?
The asList() method is used to convert an array to list. Example: import java.util.Arrays; import java.util.List; public class ArrayToList { public static void main(String args[]){ Integer[] myArray = {23, 93, 56, 92, 39}; List list = Arrays.asList(myArray); System.out.println(list); } } Output: [23, 93, 56, 92, 39]
[ { "code": null, "e": 1119, "s": 1062, "text": "The asList() method is used to convert an array to list." }, { "code": null, "e": 1128, "s": 1119, "text": "Example:" }, { "code": null, "e": 1376, "s": 1128, "text": "import java.util.Arrays;\nimport java.util.List;\n\npublic class ArrayToList {\n public static void main(String args[]){\n Integer[] myArray = {23, 93, 56, 92, 39};\n List list = Arrays.asList(myArray);\n System.out.println(list);\n }\n}" }, { "code": null, "e": 1384, "s": 1376, "text": "Output:" }, { "code": null, "e": 1405, "s": 1384, "text": "[23, 93, 56, 92, 39]" } ]
Creating a MySQL Docker Container
One of the most important features of Docker Containerization is that it creates a bounded environment for running the Application with all the necessary dependencies and packages installed. Most applications require a backend database to store data points. Oracle provides Docker Images for running MySQL inside Containers and thus it becomes an excellent choice for testing your database applications. It provides lightweight MySQL Image instances with cleanup features once your testing is completed. Docker allows you to download the Image containing the MySQL binaries and dependencies and creates a virtual filesystem. Note that if you start a Docker Container with the −−rm flag, after you stop the Container, the entire file system along with the Container Instance gets deleted and hence combining this flag with the run command would give you automatic cleanup feature for testing your applications. In this article, we will see how to create MySQL Docker Containers for testing your application. The below command creates an instance for the MySQL Image with the latest version and along with it, the −−rm flag helps in eliminating the Container along with the file system once the Container is stopped. sudo docker run −−rm −−name=mysql−test −e MYSQL_ALLOW_EMPTY_PASSWORD=yes −d mysql/mysql−server In the above command, the −−rm flag instructs the Docker daemon to delete the Container file system after it’s stopped. The −−name flag provides the name to the Container. The “−e MYSQL_ALLOW_EMPTY_PASSWORD=yes” instructs the Container to create an empty root password. The MySQL Client programs use the local socket connections i.e. they connect via the localhost. To create a local MySQL connection, you can use the following command. sudo docker exec −it mysql−test mysql −uroot The exec instruction tells the Docker daemon to execute the command specified inside the Docker Container. The −it flag instructs the Docker to open the Container in an interactive shell. The shell command that executes inside the Docker Container is “mysql −uroot”. After you execute the commands in the previous steps, Docker assigns a private IP address to the Docker Containers. It also creates a Network interface on your system. These can be used as endpoints to create a TCP/IP connection to the service. You cannot access the MySQL service unless you create a TCP/IP connection between the two endpoints. To do so, you need to find out the IP addresses for the Virtual Network Interface in your system and the Docker Container instance. You can do so by using the commands below. To find the IP address of the network interface in your system, execute − ip addr show docker0 The IP address you get using the above command becomes one of the endpoints that your client application will connect to and you will use it to create users for your MySQL. To find out the other endpoint, which is the IP address of your Docker Container Instance for MySQL, you can use this command − sudo docker mysql−test Using these two IP addresses, you can now move forward and create your TCP/IP connection and create a user to run your client application. To make your local system as a root user without any password, you can use these commands. Inside the terminal of your system, execute the mysql−test Docker Container to access the mysql shell. sudo docker exec −it mysql−test mysql −uroot Once you have access to the mysql shell, inside it execute this command to create your local system as the root user. create user root@<virtual network interface IP> identified by ''; Note that the IP address used in the above command should be that of the virtual network interface in your local machine that we found in the earlier steps. To grant all the access to the user created above, use this command. grant all on *.* to root@<virtual network interface IP> with grant option; To perform auto cleanup after you have performed all your testings, you can simply stop the Container and remove it using the stop and rm commands. To conclude, in this article, we discussed how to create and launch a MySQL Docker Container and access it by creating a TCP/IP connection between the Virtual Network Interface on your Linux Machine and the Docker Container. We created the root user and granted all access to it.
[ { "code": null, "e": 1566, "s": 1062, "text": "One of the most important features of Docker Containerization is that it creates a bounded environment for running the Application with all the necessary dependencies and packages installed. Most applications require a backend database to store data points. Oracle provides Docker Images for running MySQL inside Containers and thus it becomes an excellent choice for testing your database applications. It provides lightweight MySQL Image instances with cleanup features once your testing is completed." }, { "code": null, "e": 1972, "s": 1566, "text": "Docker allows you to download the Image containing the MySQL binaries and dependencies and creates a virtual filesystem. Note that if you start a Docker Container with the −−rm flag, after you stop the Container, the entire file system along with the Container Instance gets deleted and hence combining this flag with the run command would give you automatic cleanup feature for testing your applications." }, { "code": null, "e": 2069, "s": 1972, "text": "In this article, we will see how to create MySQL Docker Containers for testing your application." }, { "code": null, "e": 2277, "s": 2069, "text": "The below command creates an instance for the MySQL Image with the latest version and along with it, the −−rm flag helps in eliminating the Container along with the file system once the Container is stopped." }, { "code": null, "e": 2372, "s": 2277, "text": "sudo docker run −−rm −−name=mysql−test −e MYSQL_ALLOW_EMPTY_PASSWORD=yes −d mysql/mysql−server" }, { "code": null, "e": 2642, "s": 2372, "text": "In the above command, the −−rm flag instructs the Docker daemon to delete the Container file system after it’s stopped. The −−name flag provides the name to the Container. The “−e MYSQL_ALLOW_EMPTY_PASSWORD=yes” instructs the Container to create an empty root password." }, { "code": null, "e": 2809, "s": 2642, "text": "The MySQL Client programs use the local socket connections i.e. they connect via the localhost. To create a local MySQL connection, you can use the following command." }, { "code": null, "e": 2854, "s": 2809, "text": "sudo docker exec −it mysql−test mysql −uroot" }, { "code": null, "e": 3121, "s": 2854, "text": "The exec instruction tells the Docker daemon to execute the command specified inside the Docker Container. The −it flag instructs the Docker to open the Container in an interactive shell. The shell command that executes inside the Docker Container is “mysql −uroot”." }, { "code": null, "e": 3366, "s": 3121, "text": "After you execute the commands in the previous steps, Docker assigns a private IP address to the Docker Containers. It also creates a Network interface on your system. These can be used as endpoints to create a TCP/IP connection to the service." }, { "code": null, "e": 3642, "s": 3366, "text": "You cannot access the MySQL service unless you create a TCP/IP connection between the two endpoints. To do so, you need to find out the IP addresses for the Virtual Network Interface in your system and the Docker Container instance. You can do so by using the commands below." }, { "code": null, "e": 3716, "s": 3642, "text": "To find the IP address of the network interface in your system, execute −" }, { "code": null, "e": 3737, "s": 3716, "text": "ip addr show docker0" }, { "code": null, "e": 3910, "s": 3737, "text": "The IP address you get using the above command becomes one of the endpoints that your client application will connect to and you will use it to create users for your MySQL." }, { "code": null, "e": 4038, "s": 3910, "text": "To find out the other endpoint, which is the IP address of your Docker Container Instance for MySQL, you can use this command −" }, { "code": null, "e": 4062, "s": 4038, "text": "sudo docker mysql−test\n" }, { "code": null, "e": 4201, "s": 4062, "text": "Using these two IP addresses, you can now move forward and create your TCP/IP connection and create a user to run your client application." }, { "code": null, "e": 4292, "s": 4201, "text": "To make your local system as a root user without any password, you can use these commands." }, { "code": null, "e": 4395, "s": 4292, "text": "Inside the terminal of your system, execute the mysql−test Docker Container to access the mysql shell." }, { "code": null, "e": 4440, "s": 4395, "text": "sudo docker exec −it mysql−test mysql −uroot" }, { "code": null, "e": 4558, "s": 4440, "text": "Once you have access to the mysql shell, inside it execute this command to create your local system as the root user." }, { "code": null, "e": 4624, "s": 4558, "text": "create user root@<virtual network interface IP> identified by '';" }, { "code": null, "e": 4781, "s": 4624, "text": "Note that the IP address used in the above command should be that of the virtual network interface in your local machine that we found in the earlier steps." }, { "code": null, "e": 4850, "s": 4781, "text": "To grant all the access to the user created above, use this command." }, { "code": null, "e": 4925, "s": 4850, "text": "grant all on *.* to root@<virtual network interface IP> with grant option;" }, { "code": null, "e": 5073, "s": 4925, "text": "To perform auto cleanup after you have performed all your testings, you can simply stop the Container and remove it using the stop and rm commands." }, { "code": null, "e": 5353, "s": 5073, "text": "To conclude, in this article, we discussed how to create and launch a MySQL Docker Container and access it by creating a TCP/IP connection between the Virtual Network Interface on your Linux Machine and the Docker Container. We created the root user and granted all access to it." } ]
How to access elements of nested lists in R?
Sometimes the lists are contained in another list but we want to access the nested list’s elements. Since these elements are part of a list then cannot be directly accessed, first we need to access the broader list and then the list that contains the element to reach the actual element. Consider the lists x1, x2, x3, x4, and x4 and the Total_List that contains these lists − > x1<-c(list(1:5),list(6:10),list(11:15)) > x2<-c(list(letters[1:5]),list(letters[6:10], list(letters[11:15]))) > x3<-c(list(c("India","Australia"),list("Canada"),list(c("Russia","Malaysia")))) > x4<-c(list("Europe"),list(c("Asia","America"),list(c("Africa","Antartica")))) > x5<-c(list("Red"),list("Green"),list("Yellow"),list(c("White","Pink"))) > Total_Lists<-list(x1,x2,x3,x4,x5) Printing the Total_Lists − > Total_Lists [[1]] [[1]][[1]] [1] 1 2 3 4 5 [[1]][[2]] [1] 6 7 8 9 10 [[1]][[3]] [1] 11 12 13 14 15 [[2]] [[2]][[1]] [1] "a" "b" "c" "d" "e" [[2]][[2]] [1] "f" "g" "h" "i" "j" [[2]][[3]] [[2]][[3]][[1]] [1] "k" "l" "m" "n" "o" [[3]] [[3]][[1]] [1] "India" "Australia" [[3]][[2]] [[3]][[2]][[1]] [1] "Canada" [[3]][[3]] [[3]][[3]][[1]] [1] "Russia" "Malaysia" [[4]] [[4]][[1]] [1] "Europe" [[4]][[2]] [1] "Asia" "America" [[4]][[3]] [[4]][[3]][[1]] [1] "Africa" "Antartica" [[5]] [[5]][[1]] [1] "Red" [[5]][[2]] [1] "Green" [[5]][[3]] [1] "Yellow" [[5]][[4]] [1] "White" "Pink" Now to access the first element in each of x1, x2, x3, x4, and x4 we can use the following code − > lapply(Total_Lists,'[[',1) [[1]] [1] 1 2 3 4 5 [[2]] [1] "a" "b" "c" "d" "e" [[3]] [1] "India" "Australia" [[4]] [1] "Europe" [[5]] [1] "Red" Similarly, to access the third element in each of x1, x2, x3, x4, and x4 we just need to change 1 to 3 as shown below − > lapply(Total_Lists,'[[',3) [[1]] [1] 11 12 13 14 15 [[2]] [[2]][[1]] [1] "k" "l" "m" "n" "o" [[3]] [[3]][[1]] [1] "Russia" "Malaysia" [[4]] [[4]][[1]] [1] "Africa" "Antartica" [[5]] [1] "Yellow"
[ { "code": null, "e": 1350, "s": 1062, "text": "Sometimes the lists are contained in another list but we want to access the nested list’s elements. Since these elements are part of a list then cannot be directly accessed, first we need to access the broader list and then the list that contains the element to reach the actual element." }, { "code": null, "e": 1439, "s": 1350, "text": "Consider the lists x1, x2, x3, x4, and x4 and the Total_List that contains these lists −" }, { "code": null, "e": 1823, "s": 1439, "text": "> x1<-c(list(1:5),list(6:10),list(11:15))\n> x2<-c(list(letters[1:5]),list(letters[6:10], list(letters[11:15])))\n> x3<-c(list(c(\"India\",\"Australia\"),list(\"Canada\"),list(c(\"Russia\",\"Malaysia\"))))\n> x4<-c(list(\"Europe\"),list(c(\"Asia\",\"America\"),list(c(\"Africa\",\"Antartica\"))))\n> x5<-c(list(\"Red\"),list(\"Green\"),list(\"Yellow\"),list(c(\"White\",\"Pink\")))\n> Total_Lists<-list(x1,x2,x3,x4,x5)" }, { "code": null, "e": 1850, "s": 1823, "text": "Printing the Total_Lists −" }, { "code": null, "e": 2428, "s": 1850, "text": "> Total_Lists\n[[1]]\n[[1]][[1]]\n[1] 1 2 3 4 5\n[[1]][[2]]\n[1] 6 7 8 9 10\n[[1]][[3]]\n[1] 11 12 13 14 15\n[[2]]\n[[2]][[1]]\n[1] \"a\" \"b\" \"c\" \"d\" \"e\"\n[[2]][[2]]\n[1] \"f\" \"g\" \"h\" \"i\" \"j\"\n[[2]][[3]]\n[[2]][[3]][[1]]\n[1] \"k\" \"l\" \"m\" \"n\" \"o\"\n[[3]]\n[[3]][[1]]\n[1] \"India\" \"Australia\"\n[[3]][[2]]\n[[3]][[2]][[1]]\n[1] \"Canada\"\n[[3]][[3]]\n[[3]][[3]][[1]]\n[1] \"Russia\" \"Malaysia\"\n[[4]]\n[[4]][[1]]\n[1] \"Europe\"\n[[4]][[2]]\n[1] \"Asia\" \"America\"\n[[4]][[3]]\n[[4]][[3]][[1]]\n[1] \"Africa\" \"Antartica\"\n[[5]]\n[[5]][[1]]\n[1] \"Red\"\n[[5]][[2]]\n[1] \"Green\"\n[[5]][[3]]\n[1] \"Yellow\"\n[[5]][[4]]\n[1] \"White\" \"Pink\"" }, { "code": null, "e": 2526, "s": 2428, "text": "Now to access the first element in each of x1, x2, x3, x4, and x4 we can use the following code −" }, { "code": null, "e": 2670, "s": 2526, "text": "> lapply(Total_Lists,'[[',1)\n[[1]]\n[1] 1 2 3 4 5\n[[2]]\n[1] \"a\" \"b\" \"c\" \"d\" \"e\"\n[[3]]\n[1] \"India\" \"Australia\"\n[[4]]\n[1] \"Europe\"\n[[5]]\n[1] \"Red\"" }, { "code": null, "e": 2790, "s": 2670, "text": "Similarly, to access the third element in each of x1, x2, x3, x4, and x4 we just need to change 1 to 3 as shown below −" }, { "code": null, "e": 2987, "s": 2790, "text": "> lapply(Total_Lists,'[[',3)\n[[1]]\n[1] 11 12 13 14 15\n[[2]]\n[[2]][[1]]\n[1] \"k\" \"l\" \"m\" \"n\" \"o\"\n[[3]]\n[[3]][[1]]\n[1] \"Russia\" \"Malaysia\"\n[[4]]\n[[4]][[1]]\n[1] \"Africa\" \"Antartica\"\n[[5]]\n[1] \"Yellow\"" } ]
Ruby on Rails - Render
Usually the view template with the same name as the controller method is used to render the results. # The default. Does not need to be specified # in a controller method called "some_action" render :action => 'some_action' render :action => 'another_action', :layout => false render :action => 'some_action', :layout => 'another_layout' Partials are stored in files called "_subformname" ( _error, _subform, _listitem). render :partial => 'subform' render :partial => 'error', :status => 500 render :partial => 'subform', :locals => { :variable => @other_variable } render :partial => 'listitem', :collection => @list render :partial => 'listitem', :collection => @list, :spacer_template => 'list_divider' Like rendering an action, but finds the template based on the template root (app/views). # renders app/views/weblog/show render :template => 'weblog/show' render :file => '/path/to/some/file.html.erb' render :file => '/path/to/some/filenotfound.html.erb', status => 404, :layout => true render :text => "Hello World" render :text => "This is an error", :status => 500 render :text => "Let's use a layout", :layout => true render :text => 'Specific layout', :layout => 'special' Uses ERb to render the "miniature" template render :inline => "<%= 'hello , ' * 3 + 'again' %>" render :inline => "<%= 'hello ' + name %>", :locals => { :name => "david" } render :nothing render :nothing, :status => 403 # forbidden def refresh render :update do |page| page.replace_html 'user_list', :partial => 'user', :collection => @users page.visual_effect :highlight, 'user_list' end end Change the content-type − render :action => "atom.rxml", :content_type => "application/atom+xml" Print Add Notes Bookmark this page
[ { "code": null, "e": 2204, "s": 2103, "text": "Usually the view template with the same name as the controller method is used to render the results." }, { "code": null, "e": 2446, "s": 2204, "text": "# The default. Does not need to be specified \n# in a controller method called \"some_action\"\n\nrender :action => 'some_action' \nrender :action => 'another_action', :layout => false\nrender :action => 'some_action', :layout => 'another_layout'" }, { "code": null, "e": 2529, "s": 2446, "text": "Partials are stored in files called \"_subformname\" ( _error, _subform, _listitem)." }, { "code": null, "e": 2815, "s": 2529, "text": "render :partial => 'subform'\nrender :partial => 'error', :status => 500\nrender :partial => 'subform', :locals => { :variable => @other_variable }\nrender :partial => 'listitem', :collection => @list\nrender :partial => 'listitem', :collection => @list, :spacer_template => 'list_divider'" }, { "code": null, "e": 2904, "s": 2815, "text": "Like rendering an action, but finds the template based on the template root (app/views)." }, { "code": null, "e": 2971, "s": 2904, "text": "# renders app/views/weblog/show\nrender :template => 'weblog/show' " }, { "code": null, "e": 3107, "s": 2971, "text": "render :file => '/path/to/some/file.html.erb'\nrender :file => '/path/to/some/filenotfound.html.erb', \n status => 404, :layout => true" }, { "code": null, "e": 3298, "s": 3107, "text": "render :text => \"Hello World\"\nrender :text => \"This is an error\", :status => 500\nrender :text => \"Let's use a layout\", :layout => true\nrender :text => 'Specific layout', :layout => 'special'" }, { "code": null, "e": 3342, "s": 3298, "text": "Uses ERb to render the \"miniature\" template" }, { "code": null, "e": 3470, "s": 3342, "text": "render :inline => \"<%= 'hello , ' * 3 + 'again' %>\"\nrender :inline => \"<%= 'hello ' + name %>\", :locals => { :name => \"david\" }" }, { "code": null, "e": 3533, "s": 3470, "text": "render :nothing\nrender :nothing, :status => 403 # forbidden" }, { "code": null, "e": 3721, "s": 3533, "text": "def refresh\n \n render :update do |page|\n page.replace_html 'user_list', :partial => 'user', :collection => @users\n page.visual_effect :highlight, 'user_list'\n end\n \nend" }, { "code": null, "e": 3747, "s": 3721, "text": "Change the content-type −" }, { "code": null, "e": 3818, "s": 3747, "text": "render :action => \"atom.rxml\", :content_type => \"application/atom+xml\"" }, { "code": null, "e": 3825, "s": 3818, "text": " Print" }, { "code": null, "e": 3836, "s": 3825, "text": " Add Notes" } ]
How do I get current URL in Selenium Webdriver 2 Python?
We can get the current URL of a page with Selenium webdriver. The method current_url is available which obtains the present page URL and then we can print the result in the console. s = driver.current_url Let us find the URL of the page presently navigated and we shall get https://www.tutorialspoint.com/index.htm as the output. from selenium import webdriver driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") driver.implicitly_wait(0.5) driver.get("https://www.tutorialspoint.com/index.htm") #identify current URL with current_url l= driver.current_url print(Current URL is: " + l) driver.close()
[ { "code": null, "e": 1244, "s": 1062, "text": "We can get the current URL of a page with Selenium webdriver. The method current_url is available which obtains the present page URL and then we can print the result in the console." }, { "code": null, "e": 1267, "s": 1244, "text": "s = driver.current_url" }, { "code": null, "e": 1392, "s": 1267, "text": "Let us find the URL of the page presently navigated and we shall get https://www.tutorialspoint.com/index.htm as the output." }, { "code": null, "e": 1679, "s": 1394, "text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\ndriver.implicitly_wait(0.5)\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#identify current URL with current_url\nl= driver.current_url\nprint(Current URL is: \" + l)\ndriver.close()" } ]
C++ Program to Add Two Numbers
Addition is a basic arithmetic operation. The program to add two numbers performs addition of two numbers and prints their sum on screen. A program that demonstrates addition of two numbers is given as follows − Live Demo #include <iostream> using namespace std; int main() { int num1=15 ,num2=10, sum; sum = num1 + num2; cout<<"Sum of "<<num1<<" and "<<num2<<" is "<<sum; return 0; } Sum of 15 and 10 is 25 In the above program the sum of two numbers i.e. 15 and 10 is stored in variable sum. sum = num1 + num2; After that it is displayed on screen using the cout object. cout<<"Sum of "<<num1<<" and "<<num2<<" is "<<sum; A program that uses an array to store two numbers and their sum as well is given as follows − Live Demo #include <iostream> using namespace std; int main() { int a[3]; a[0]=7; a[1]=5; a[2]=a[0] + a[1]; cout<<"Sum of "<<a[0]<<" and "<<a[1]<<" is "<<a[2]; return 0; } Sum of 7 and 5 is 12 In the above program, the numbers to be added are stored in the 0 and 1 index of the array. a[0]=7; a[1]=5; After that, the sum is stored in the 2 index of the array. a[2]=a[0] + a[1]; The sum is displayed on screen using the cout object. cout<<"Sum of "<<a[0]<<" and "<<a[1]<<" is "<<a[2];
[ { "code": null, "e": 1200, "s": 1062, "text": "Addition is a basic arithmetic operation. The program to add two numbers performs addition of two numbers and prints their sum on screen." }, { "code": null, "e": 1274, "s": 1200, "text": "A program that demonstrates addition of two numbers is given as follows −" }, { "code": null, "e": 1285, "s": 1274, "text": " Live Demo" }, { "code": null, "e": 1460, "s": 1285, "text": "#include <iostream>\nusing namespace std;\nint main() {\n int num1=15 ,num2=10, sum;\n sum = num1 + num2;\n cout<<\"Sum of \"<<num1<<\" and \"<<num2<<\" is \"<<sum;\n return 0;\n}" }, { "code": null, "e": 1483, "s": 1460, "text": "Sum of 15 and 10 is 25" }, { "code": null, "e": 1569, "s": 1483, "text": "In the above program the sum of two numbers i.e. 15 and 10 is stored in variable sum." }, { "code": null, "e": 1588, "s": 1569, "text": "sum = num1 + num2;" }, { "code": null, "e": 1648, "s": 1588, "text": "After that it is displayed on screen using the cout object." }, { "code": null, "e": 1699, "s": 1648, "text": "cout<<\"Sum of \"<<num1<<\" and \"<<num2<<\" is \"<<sum;" }, { "code": null, "e": 1793, "s": 1699, "text": "A program that uses an array to store two numbers and their sum as well is given as follows −" }, { "code": null, "e": 1804, "s": 1793, "text": " Live Demo" }, { "code": null, "e": 1984, "s": 1804, "text": "#include <iostream>\nusing namespace std;\nint main() {\n int a[3];\n a[0]=7;\n a[1]=5;\n a[2]=a[0] + a[1];\n cout<<\"Sum of \"<<a[0]<<\" and \"<<a[1]<<\" is \"<<a[2];\n return 0;\n}" }, { "code": null, "e": 2005, "s": 1984, "text": "Sum of 7 and 5 is 12" }, { "code": null, "e": 2097, "s": 2005, "text": "In the above program, the numbers to be added are stored in the 0 and 1 index of the array." }, { "code": null, "e": 2113, "s": 2097, "text": "a[0]=7;\na[1]=5;" }, { "code": null, "e": 2172, "s": 2113, "text": "After that, the sum is stored in the 2 index of the array." }, { "code": null, "e": 2190, "s": 2172, "text": "a[2]=a[0] + a[1];" }, { "code": null, "e": 2244, "s": 2190, "text": "The sum is displayed on screen using the cout object." }, { "code": null, "e": 2296, "s": 2244, "text": "cout<<\"Sum of \"<<a[0]<<\" and \"<<a[1]<<\" is \"<<a[2];" } ]
OpenCV - Simple Threshold
Thresholding is a method of image segmentation, in general it is used to create binary images. Thresholding is of two types namely, simple thresholding and adaptive thresholding. In simple thresholding operation the pixels whose values are greater than the specified threshold value, are assigned with a standard value. You can perform simple threshold operation on an image using the method threshold() of the Imgproc class, Following is the syntax of this method. threshold(src, dst, thresh, maxval, type) This method accepts the following parameters − src − An object of the class Mat representing the source (input) image. src − An object of the class Mat representing the source (input) image. dst − An object of the class Mat representing the destination (output) image. dst − An object of the class Mat representing the destination (output) image. thresh − A variable of double type representing the threshold value. thresh − A variable of double type representing the threshold value. maxval − A variable of double type representing the value that is to be given if pixel value is more than the threshold value. maxval − A variable of double type representing the value that is to be given if pixel value is more than the threshold value. type − A variable of integer type representing the type of threshold to be used. type − A variable of integer type representing the type of threshold to be used. The following program demonstrates how to perform simple thresholding operation on an image in OpenCV. import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class Thresh { public static void main(String args[]) { // Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); // Reading the Image from the file and storing it in to a Matrix object String file ="E:/OpenCV/chap14/thresh_input.jpg"; Mat src = Imgcodecs.imread(file); // Creating an empty matrix to store the result Mat dst = new Mat(); Imgproc.threshold(src, dst, 50, 255, Imgproc.THRESH_BINARY); // Writing the image Imgcodecs.imwrite("E:/OpenCV/chap14/thresh_trunc.jpg", dst); System.out.println("Image Processed"); } } Assume that following is the input image thresh_input.jpg specified in the above program. On executing the program, you will get the following output − Image Processed If you open the specified path, you can observe the output image as follows − In addition to the THRESH_BINARY operation demonstrated in the previous example, OpenCV caters various other types of threshold operations. All these types are represented by predefined static fields (fixed values) of Imgproc class. You can choose the type of the threshold operation you need, by passing its respective predefined value to the parameter named type of the threshold() method. Imgproc.threshold(src, dst, 50, 255, Imgproc.THRESH_BINARY); Following are the values representing various types of threshold operations and their respective outputs. 70 Lectures 9 hours Abhilash Nelson 41 Lectures 4 hours Abhilash Nelson 20 Lectures 2 hours Spotle Learn 12 Lectures 46 mins Srikanth Guskra 19 Lectures 2 hours Haithem Gasmi 67 Lectures 6.5 hours Gianluca Mottola Print Add Notes Bookmark this page
[ { "code": null, "e": 3183, "s": 3004, "text": "Thresholding is a method of image segmentation, in general it is used to create binary images. Thresholding is of two types namely, simple thresholding and adaptive thresholding." }, { "code": null, "e": 3324, "s": 3183, "text": "In simple thresholding operation the pixels whose values are greater than the specified threshold value, are assigned with a standard value." }, { "code": null, "e": 3470, "s": 3324, "text": "You can perform simple threshold operation on an image using the method threshold() of the Imgproc class, Following is the syntax of this method." }, { "code": null, "e": 3513, "s": 3470, "text": "threshold(src, dst, thresh, maxval, type)\n" }, { "code": null, "e": 3560, "s": 3513, "text": "This method accepts the following parameters −" }, { "code": null, "e": 3632, "s": 3560, "text": "src − An object of the class Mat representing the source (input) image." }, { "code": null, "e": 3704, "s": 3632, "text": "src − An object of the class Mat representing the source (input) image." }, { "code": null, "e": 3782, "s": 3704, "text": "dst − An object of the class Mat representing the destination (output) image." }, { "code": null, "e": 3860, "s": 3782, "text": "dst − An object of the class Mat representing the destination (output) image." }, { "code": null, "e": 3929, "s": 3860, "text": "thresh − A variable of double type representing the threshold value." }, { "code": null, "e": 3998, "s": 3929, "text": "thresh − A variable of double type representing the threshold value." }, { "code": null, "e": 4125, "s": 3998, "text": "maxval − A variable of double type representing the value that is to be given if pixel value is more than the threshold value." }, { "code": null, "e": 4252, "s": 4125, "text": "maxval − A variable of double type representing the value that is to be given if pixel value is more than the threshold value." }, { "code": null, "e": 4333, "s": 4252, "text": "type − A variable of integer type representing the type of threshold to be used." }, { "code": null, "e": 4414, "s": 4333, "text": "type − A variable of integer type representing the type of threshold to be used." }, { "code": null, "e": 4517, "s": 4414, "text": "The following program demonstrates how to perform simple thresholding operation on an image in OpenCV." }, { "code": null, "e": 5282, "s": 4517, "text": "import org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\n\npublic class Thresh {\n public static void main(String args[]) {\n // Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n\n // Reading the Image from the file and storing it in to a Matrix object\n String file =\"E:/OpenCV/chap14/thresh_input.jpg\";\n Mat src = Imgcodecs.imread(file);\n\n // Creating an empty matrix to store the result\n Mat dst = new Mat();\n Imgproc.threshold(src, dst, 50, 255, Imgproc.THRESH_BINARY);\n\n // Writing the image\n Imgcodecs.imwrite(\"E:/OpenCV/chap14/thresh_trunc.jpg\", dst);\n\n System.out.println(\"Image Processed\");\n }\n}" }, { "code": null, "e": 5372, "s": 5282, "text": "Assume that following is the input image thresh_input.jpg specified in the above program." }, { "code": null, "e": 5434, "s": 5372, "text": "On executing the program, you will get the following output −" }, { "code": null, "e": 5451, "s": 5434, "text": "Image Processed\n" }, { "code": null, "e": 5529, "s": 5451, "text": "If you open the specified path, you can observe the output image as follows −" }, { "code": null, "e": 5762, "s": 5529, "text": "In addition to the THRESH_BINARY operation demonstrated in the previous example, OpenCV caters various other types of threshold operations. All these types are represented by predefined static fields (fixed values) of Imgproc class." }, { "code": null, "e": 5921, "s": 5762, "text": "You can choose the type of the threshold operation you need, by passing its respective predefined value to the parameter named type of the threshold() method." }, { "code": null, "e": 5983, "s": 5921, "text": "Imgproc.threshold(src, dst, 50, 255, Imgproc.THRESH_BINARY);\n" }, { "code": null, "e": 6089, "s": 5983, "text": "Following are the values representing various types of threshold operations and their respective outputs." }, { "code": null, "e": 6122, "s": 6089, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 6139, "s": 6122, "text": " Abhilash Nelson" }, { "code": null, "e": 6172, "s": 6139, "text": "\n 41 Lectures \n 4 hours \n" }, { "code": null, "e": 6189, "s": 6172, "text": " Abhilash Nelson" }, { "code": null, "e": 6222, "s": 6189, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 6236, "s": 6222, "text": " Spotle Learn" }, { "code": null, "e": 6268, "s": 6236, "text": "\n 12 Lectures \n 46 mins\n" }, { "code": null, "e": 6285, "s": 6268, "text": " Srikanth Guskra" }, { "code": null, "e": 6318, "s": 6285, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 6333, "s": 6318, "text": " Haithem Gasmi" }, { "code": null, "e": 6368, "s": 6333, "text": "\n 67 Lectures \n 6.5 hours \n" }, { "code": null, "e": 6386, "s": 6368, "text": " Gianluca Mottola" }, { "code": null, "e": 6393, "s": 6386, "text": " Print" }, { "code": null, "e": 6404, "s": 6393, "text": " Add Notes" } ]
Angular 8 - CLI Commands
Angular CLI helps developers to create projects easily and quickly. As we know already, Angular CLI tool is used for development and built on top of Node.js, installed from NPM.This chapter explains about Angular 8 CLI commands in detail. Before moving to Angular CLI commands, we have to ensure that Angular CLI is installed on your machine. If it is installed, you can verify it by using the below command − ng version You could see the below response − If CLI is not installed, then use the below command to install it. npm install -g @angular/cli@^8.0.0 Let’s understand the commands one by one in brief. To create an application in Angular, use the below syntax − ng new <project-name> If you want to create CustomerApp then, use the below code − ng new CustomerApp It is used to generate or modify files based on a schematic. Type the below command inside your angular project − ng generate Or, you can simply type generate as g. You can also use the below syntax − ng g It will list out the available schematics − Let’s understand some of the repeatedly used ng generate schematics in next section. Components are building block of Angular. To create a component in angular use the below syntax − ng g c <component-name> For example, if user wants to create a Details component then use the below code − ng g c Details After using this command, you could see the below response − CREATE src/app/details/details.component.scss (0 bytes) CREATE src/app/details/details.component.html (22 bytes) CREATE src/app/details/details.component.spec.ts (635 bytes) CREATE src/app/details/details.component.ts (274 bytes) UPDATE src/app/app.module.ts (1201 bytes) It is used to create a new class in Angular. It is defined below− ng g class <class-name> If you want to create a customer class, then type the below command − ng g class Customer After using this command, you could see the below response − CREATE src/app/customer.spec.ts (162 bytes) CREATE src/app/customer.ts (26 bytes) Pipes are used for filtering the data. It is used to create a custom pipe in Angular. It is defined below − ng g pipe <pipe-name> If you want to create a custom digit counts in a pipe, then type the below command − ng g pipe DigitCount After using this command, you could see the below response − CREATE src/app/digit-count.pipe.spec.ts (204 bytes) CREATE src/app/digit-count.pipe.ts (213 bytes) UPDATE src/app/app.module.ts (1274 bytes) It is used to create a new directive in Angular. It is defined below − ng g directive <directive-name> If you want to create a UnderlineText directive, then type the below command − ng g directive UnderlineText After using this command, you could see the below response − CREATE src/app/underline-text.directive.spec.ts (253 bytes) CREATE src/app/underline-text.directive.ts (155 bytes) UPDATE src/app/app.module.ts (1371 bytes) It is used to create a new module in Angular. It is defined below − ng g module <module-name> If you want to create a user information module, then type the below command − ng g module Userinfo After using this command, you could see the below response − CREATE src/app/userinfo/userinfo.module.ts (194 bytes) It is used to create an interface in Angular. It is given below − ng g interface <interface-name> If you want to create a customer class, then type the below command − ng g interface CustomerData After using this command, you could see the below response − CREATE src/app/customer-data.ts (34 bytes) It is used to create a new web worker in Angular. It is stated below − ng g webWorker <webWorker-name> If you want to create a customer class, then type the below command − ng g webWorker CustomerWebWorker After using this command, you could see the below response − CREATE tsconfig.worker.json (212 bytes) CREATE src/app/customer-web-worker.worker.ts (157 bytes) UPDATE tsconfig.app.json (296 bytes) UPDATE angular.json (3863 bytes) It is used to create a service in Angular. It is given below − ng g service <service-name> If you want to create a customer class, then type the below command − ng g service CustomerService After using this command, you could see the below response − CREATE src/app/customer-service.service.spec.ts (379 bytes) CREATE src/app/customer-service.service.ts (144 bytes) It is used to create an enum in Angular. It is given below − ng g enum <enum-name> If you want to create a customer class, then type the below command − ng g enum CustomerRecords After using this command, you could see the below response − CREATE src/app/customer-records.enum.ts (32 bytes) It is used to add support for an external library to your project. It is specified by the below command − ng add [name] It is used to compile or build your angular app. It is defined below − ng build After using this command, you could see the below response − Generating ES5 bundles for differential loading... ES5 bundle generation complete. It is used to retrieve or set Angular configuration values in the angular.json file for the workspace. It is defined below − ng config After using this command, you could see the below response − { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "MyApp": { "projectType": "application", "schematics": { "@schematics/angular:component": { "style": "scss" } }, ............................. ............................. It is used to open the official Angular documentation (angular.io) in a browser, and searches for a given keyword. ng doc <keyword> For example, if you search with component as ng g component then, it will open the documentation. It is used to build and serves an Angular app, then runs end-to-end tests using Protractor. It is stated below − ng e2e <project> [options] It lists out available commands and their short descriptions. It is stated below − ng help It is used to build and serves your app, rebuilding on file changes. It is given below: − ng serve Runs unit tests in a project. It is mentioned below − ng test Updates your application and its dependencies. It is given below − ng update Shows Angular CLI version. It is stated below − ng version 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2627, "s": 2388, "text": "Angular CLI helps developers to create projects easily and quickly. As we know already, Angular CLI tool is used for development and built on top of Node.js, installed from NPM.This chapter explains about Angular 8 CLI commands in detail." }, { "code": null, "e": 2798, "s": 2627, "text": "Before moving to Angular CLI commands, we have to ensure that Angular CLI is installed on your machine. If it is installed, you can verify it by using the below command −" }, { "code": null, "e": 2809, "s": 2798, "text": "ng version" }, { "code": null, "e": 2844, "s": 2809, "text": "You could see the below response −" }, { "code": null, "e": 2911, "s": 2844, "text": "If CLI is not installed, then use the below command to install it." }, { "code": null, "e": 2946, "s": 2911, "text": "npm install -g @angular/cli@^8.0.0" }, { "code": null, "e": 2997, "s": 2946, "text": "Let’s understand the commands one by one in brief." }, { "code": null, "e": 3057, "s": 2997, "text": "To create an application in Angular, use the below syntax −" }, { "code": null, "e": 3079, "s": 3057, "text": "ng new <project-name>" }, { "code": null, "e": 3140, "s": 3079, "text": "If you want to create CustomerApp then, use the below code −" }, { "code": null, "e": 3159, "s": 3140, "text": "ng new CustomerApp" }, { "code": null, "e": 3273, "s": 3159, "text": "It is used to generate or modify files based on a schematic. Type the below command inside your angular project −" }, { "code": null, "e": 3285, "s": 3273, "text": "ng generate" }, { "code": null, "e": 3360, "s": 3285, "text": "Or, you can simply type generate as g. You can also use the below syntax −" }, { "code": null, "e": 3365, "s": 3360, "text": "ng g" }, { "code": null, "e": 3409, "s": 3365, "text": "It will list out the available schematics −" }, { "code": null, "e": 3494, "s": 3409, "text": "Let’s understand some of the repeatedly used ng generate schematics in next section." }, { "code": null, "e": 3592, "s": 3494, "text": "Components are building block of Angular. To create a component in angular use the below syntax −" }, { "code": null, "e": 3616, "s": 3592, "text": "ng g c <component-name>" }, { "code": null, "e": 3699, "s": 3616, "text": "For example, if user wants to create a Details component then use the below code −" }, { "code": null, "e": 3714, "s": 3699, "text": "ng g c Details" }, { "code": null, "e": 3775, "s": 3714, "text": "After using this command, you could see the below response −" }, { "code": null, "e": 4047, "s": 3775, "text": "CREATE src/app/details/details.component.scss (0 bytes)\nCREATE src/app/details/details.component.html (22 bytes)\nCREATE src/app/details/details.component.spec.ts (635 bytes)\nCREATE src/app/details/details.component.ts (274 bytes)\nUPDATE src/app/app.module.ts (1201 bytes)" }, { "code": null, "e": 4113, "s": 4047, "text": "It is used to create a new class in Angular. It is defined below−" }, { "code": null, "e": 4137, "s": 4113, "text": "ng g class <class-name>" }, { "code": null, "e": 4207, "s": 4137, "text": "If you want to create a customer class, then type the below command −" }, { "code": null, "e": 4227, "s": 4207, "text": "ng g class Customer" }, { "code": null, "e": 4288, "s": 4227, "text": "After using this command, you could see the below response −" }, { "code": null, "e": 4370, "s": 4288, "text": "CREATE src/app/customer.spec.ts (162 bytes)\nCREATE src/app/customer.ts (26 bytes)" }, { "code": null, "e": 4478, "s": 4370, "text": "Pipes are used for filtering the data. It is used to create a custom pipe in Angular. It is defined below −" }, { "code": null, "e": 4500, "s": 4478, "text": "ng g pipe <pipe-name>" }, { "code": null, "e": 4585, "s": 4500, "text": "If you want to create a custom digit counts in a pipe, then type the below command −" }, { "code": null, "e": 4606, "s": 4585, "text": "ng g pipe DigitCount" }, { "code": null, "e": 4667, "s": 4606, "text": "After using this command, you could see the below response −" }, { "code": null, "e": 4808, "s": 4667, "text": "CREATE src/app/digit-count.pipe.spec.ts (204 bytes)\nCREATE src/app/digit-count.pipe.ts (213 bytes)\nUPDATE src/app/app.module.ts (1274 bytes)" }, { "code": null, "e": 4879, "s": 4808, "text": "It is used to create a new directive in Angular. It is defined below −" }, { "code": null, "e": 4911, "s": 4879, "text": "ng g directive <directive-name>" }, { "code": null, "e": 4990, "s": 4911, "text": "If you want to create a UnderlineText directive, then type the below command −" }, { "code": null, "e": 5019, "s": 4990, "text": "ng g directive UnderlineText" }, { "code": null, "e": 5080, "s": 5019, "text": "After using this command, you could see the below response −" }, { "code": null, "e": 5237, "s": 5080, "text": "CREATE src/app/underline-text.directive.spec.ts (253 bytes)\nCREATE src/app/underline-text.directive.ts (155 bytes)\nUPDATE src/app/app.module.ts (1371 bytes)" }, { "code": null, "e": 5305, "s": 5237, "text": "It is used to create a new module in Angular. It is defined below −" }, { "code": null, "e": 5331, "s": 5305, "text": "ng g module <module-name>" }, { "code": null, "e": 5410, "s": 5331, "text": "If you want to create a user information module, then type the below command −" }, { "code": null, "e": 5431, "s": 5410, "text": "ng g module Userinfo" }, { "code": null, "e": 5492, "s": 5431, "text": "After using this command, you could see the below response −" }, { "code": null, "e": 5547, "s": 5492, "text": "CREATE src/app/userinfo/userinfo.module.ts (194 bytes)" }, { "code": null, "e": 5613, "s": 5547, "text": "It is used to create an interface in Angular. It is given below −" }, { "code": null, "e": 5645, "s": 5613, "text": "ng g interface <interface-name>" }, { "code": null, "e": 5715, "s": 5645, "text": "If you want to create a customer class, then type the below command −" }, { "code": null, "e": 5743, "s": 5715, "text": "ng g interface CustomerData" }, { "code": null, "e": 5804, "s": 5743, "text": "After using this command, you could see the below response −" }, { "code": null, "e": 5847, "s": 5804, "text": "CREATE src/app/customer-data.ts (34 bytes)" }, { "code": null, "e": 5918, "s": 5847, "text": "It is used to create a new web worker in Angular. It is stated below −" }, { "code": null, "e": 5950, "s": 5918, "text": "ng g webWorker <webWorker-name>" }, { "code": null, "e": 6020, "s": 5950, "text": "If you want to create a customer class, then type the below command −" }, { "code": null, "e": 6053, "s": 6020, "text": "ng g webWorker CustomerWebWorker" }, { "code": null, "e": 6114, "s": 6053, "text": "After using this command, you could see the below response −" }, { "code": null, "e": 6281, "s": 6114, "text": "CREATE tsconfig.worker.json (212 bytes)\nCREATE src/app/customer-web-worker.worker.ts (157 bytes)\nUPDATE tsconfig.app.json (296 bytes)\nUPDATE angular.json (3863 bytes)" }, { "code": null, "e": 6344, "s": 6281, "text": "It is used to create a service in Angular. It is given below −" }, { "code": null, "e": 6372, "s": 6344, "text": "ng g service <service-name>" }, { "code": null, "e": 6442, "s": 6372, "text": "If you want to create a customer class, then type the below command −" }, { "code": null, "e": 6471, "s": 6442, "text": "ng g service CustomerService" }, { "code": null, "e": 6532, "s": 6471, "text": "After using this command, you could see the below response −" }, { "code": null, "e": 6647, "s": 6532, "text": "CREATE src/app/customer-service.service.spec.ts (379 bytes)\nCREATE src/app/customer-service.service.ts (144 bytes)" }, { "code": null, "e": 6708, "s": 6647, "text": "It is used to create an enum in Angular. It is given below −" }, { "code": null, "e": 6730, "s": 6708, "text": "ng g enum <enum-name>" }, { "code": null, "e": 6800, "s": 6730, "text": "If you want to create a customer class, then type the below command −" }, { "code": null, "e": 6826, "s": 6800, "text": "ng g enum CustomerRecords" }, { "code": null, "e": 6887, "s": 6826, "text": "After using this command, you could see the below response −" }, { "code": null, "e": 6938, "s": 6887, "text": "CREATE src/app/customer-records.enum.ts (32 bytes)" }, { "code": null, "e": 7044, "s": 6938, "text": "It is used to add support for an external library to your project. It is specified by the below command −" }, { "code": null, "e": 7058, "s": 7044, "text": "ng add [name]" }, { "code": null, "e": 7129, "s": 7058, "text": "It is used to compile or build your angular app. It is defined below −" }, { "code": null, "e": 7138, "s": 7129, "text": "ng build" }, { "code": null, "e": 7199, "s": 7138, "text": "After using this command, you could see the below response −" }, { "code": null, "e": 7282, "s": 7199, "text": "Generating ES5 bundles for differential loading...\nES5 bundle generation complete." }, { "code": null, "e": 7407, "s": 7282, "text": "It is used to retrieve or set Angular configuration values in the angular.json file for the workspace. It is defined below −" }, { "code": null, "e": 7417, "s": 7407, "text": "ng config" }, { "code": null, "e": 7478, "s": 7417, "text": "After using this command, you could see the below response −" }, { "code": null, "e": 7862, "s": 7478, "text": "{\n \"$schema\": \"./node_modules/@angular/cli/lib/config/schema.json\",\n \"version\": 1,\n \"newProjectRoot\": \"projects\",\n \"projects\": {\n \"MyApp\": {\n \"projectType\": \"application\",\n \"schematics\": {\n \"@schematics/angular:component\": {\n \"style\": \"scss\"\n }\n },\n .............................\n ............................." }, { "code": null, "e": 7977, "s": 7862, "text": "It is used to open the official Angular documentation (angular.io) in a browser, and searches for a given keyword." }, { "code": null, "e": 7994, "s": 7977, "text": "ng doc <keyword>" }, { "code": null, "e": 8092, "s": 7994, "text": "For example, if you search with component as ng g component then, it will open the documentation." }, { "code": null, "e": 8205, "s": 8092, "text": "It is used to build and serves an Angular app, then runs end-to-end tests using Protractor. It is stated below −" }, { "code": null, "e": 8232, "s": 8205, "text": "ng e2e <project> [options]" }, { "code": null, "e": 8315, "s": 8232, "text": "It lists out available commands and their short descriptions. It is stated below −" }, { "code": null, "e": 8323, "s": 8315, "text": "ng help" }, { "code": null, "e": 8413, "s": 8323, "text": "It is used to build and serves your app, rebuilding on file changes. It is given below: −" }, { "code": null, "e": 8422, "s": 8413, "text": "ng serve" }, { "code": null, "e": 8476, "s": 8422, "text": "Runs unit tests in a project. It is mentioned below −" }, { "code": null, "e": 8484, "s": 8476, "text": "ng test" }, { "code": null, "e": 8551, "s": 8484, "text": "Updates your application and its dependencies. It is given below −" }, { "code": null, "e": 8561, "s": 8551, "text": "ng update" }, { "code": null, "e": 8609, "s": 8561, "text": "Shows Angular CLI version. It is stated below −" }, { "code": null, "e": 8620, "s": 8609, "text": "ng version" }, { "code": null, "e": 8655, "s": 8620, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8669, "s": 8655, "text": " Anadi Sharma" }, { "code": null, "e": 8704, "s": 8669, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8718, "s": 8704, "text": " Anadi Sharma" }, { "code": null, "e": 8753, "s": 8718, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 8773, "s": 8753, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 8808, "s": 8773, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8825, "s": 8808, "text": " Frahaan Hussain" }, { "code": null, "e": 8858, "s": 8825, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 8870, "s": 8858, "text": " Senol Atac" }, { "code": null, "e": 8905, "s": 8870, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8917, "s": 8905, "text": " Senol Atac" }, { "code": null, "e": 8924, "s": 8917, "text": " Print" }, { "code": null, "e": 8935, "s": 8924, "text": " Add Notes" } ]
A Guide to Pandas and Matplotlib for Data Exploration | by Hugo Dolan | Towards Data Science
After recently using Pandas and Matplotlib to produce the graphs / analysis for this article on China’s property bubble , and creating a random forrest regression model to find undervalued used cars (more on this soon). I decided to put together this practical guide, which should hopefully be enough to get you up and running with your own data exploration using Pandas and MPL! This article is broken up into the following Sections: The Basic Requirements Reading Data From CSV Formatting, cleaning and filtering Data Frames Group-by and Merge Visualising Your Data The Plot Function Basics Seaborn violin and lm-plots Pair plots and Heat maps Figure Aesthetics Plotting with multiple axis Making your charts look less scientific import matplotlib.pyplot as pltimport pandas as pdimport numpy as np%matplotlib inlinecar_data = pd.read_csv('inbox/CarData-E-class-Tue Jul 03 2018.csv') Inline indicates to present graphs as cell output, read_csv returns a DataFrame, the file path is relative to that of your notebook. Often when dealing with a large number of features it is nice to see the first row, or the names of all the columns, using the columns property and head(nRows) function. However if we are interested in the types of values for a categorical such as the modelLine, we can access the column using the square bracket syntax and use .unique() to inspect the options. print(car_data.columns)car_data.head(2) car_data['modelLine'].unique() There are clearly multiple versions of the same model line entered under different variations of ‘Special Equipment’ so we will use a regex to replace anything containing SE with Special equipment. Similarly there are some columns with Nans (Not a Number) so we will just drop these with dropna(subset=[‘modelLine’]). car_data = car_data.dropna(subset=['modelLine'])car_data['modelLine'] = car_data['modelLine'].replace(to_replace={'.*SE.*': 'Standard equipment'}, regex=True) We can also filter out unwanted values such as ‘undefined’ by comparing the rows of modelLine against some boolean question, this returns a boolean array of the same dimensions as the DataFrame rows which can be used to filter with the square bracket syntax again. car_data = car_data[(car_data['modelLine'] != 'undefined')]car_data['modelLine'].unique() Note above how pandas never mutates any existing data, hence we have to overwrite our old data manually when we perform any mutations / filters. Whilst this may seem redundant, its extremely effective method of reducing unwanted side effects and bugs in your code. Moving on, we also need to change the firstRegistration field typically this should be treated as a python date format, but instead we will treat it as a numeric field for convenience in performing regressions on the data in a future article. Considering this data is associated with car registration, the year is really the important component we need to keep. Thus treating this as a numeric field means we can apply numerical rounding, multiplication / division to create a Registration Year feature column as below. car_data['firstRegistration'].head(5)car_data[‘firstRegistrationYear’] = round((car_data[‘firstRegistration’] / 10000),0)car_data[‘firstRegistrationYear’] .head(5) Group-by’s can be used to build groups of rows based off a specific feature in your dataset eg. the ‘modelLine’ categorical column. We can then perform an operation such as mean, min, max, std on the individual groups to help describe the sample data. group_by_modelLine = car_data.groupby(by=['modelLine'])car_data_avg = group_by_modelLine.mean()car_data_count = group_by_modelLine.count() As you can see the mean value for each numeric feature has been calculated for each model Line. Group by’s are highly versatile and also accept lambda functions for more complex row / group labelling.Next we will assemble a DataFrame of only the relevant features to plot a graph of availability (or car count) and average equipment per car. This DataFrame can be created by passing in a dictionary of keys which represent the columns and values which are single columns or Series from our existing data. This works here because both Data Frames have the same number of rows. Alternatively we can merge the two Data Frames by their indexes (modelLine) and rename the suffixes of repeated columns appropriately. We will then plot these two variables sorting by equipment then availability as a horizontal bar graph. # Since all the columns in car_data_count are the same, we will use just the first column as the rest yield the same result. iloc allows us to take all the rows and the zeroth column.car_data_count_series = car_data_count.iloc[:,0]features_of_interest = pd.DataFrame({'equipment': car_data_avg['equipment'], 'availability': car_data_count_series})alternative_method = car_data_avg.merge(car_data_count, left_index=True, right_index=True, suffixes=['_avg','_count'])alternative_method[['equipment_avg', 'firstRegistration_count']].sort_values(by=['equipment_avg', 'firstRegistration_count'], ascending=True).plot(kind='barh') Pandas has a built in .plot() function as part of the DataFrame class. It has several key parameters: kind — ‘bar’,’barh’,’pie’,’scatter’,’kde’ etc which can be found in the docs.color — Which accepts and array of hex codes corresponding sequential to each data series / column.linestyle — ‘solid’, ‘dotted’, ‘dashed’ (applies to line graphs only)xlim, ylim — specify a tuple (lower limit, upper limit) for which the plot will be drawnlegend— a boolean value to display or hide the legendlabels — a list corresponding to the number of columns in the dataframe, a descriptive name can be provided here for the legendtitle — The string title of the plot These are fairly straightforward to use and we’ll do some examples using .plot() later in the post. Seaborn builds on top of matplotlib to provide a richer out of the box environment. It includes a neat lmplot plot function for rapid exploration of multiple variables. Using our car data example, we would like to understand the association between the equipment kit-out of a car and the sale price. Obviously we would also like this data segmented by model line to compare like with like. import seaborn as sns Passing in our column labels for equipment and price (x and y axis) followed by the actual DataFrame source. Use the col keyword to generate a separate plot for each model line and set the col_wrap 2 to make a nice grid. filtered_class = car_data[car_data['modelLine'] != 'AVANTGARDE']sns.lmplot("equipment", "price", data=filtered_class, hue="gears", fit_reg=False, col='modelLine', col_wrap=2) As you can see putting a hue onto the chart for the number of gears was particularly informative, as these types of car tend to be no better equipped but more expensive. As you can see we could perform significant exploration of our dataset in 3 lines of code. These plots are excellent for dealing with large continuous datasets, and can similarly be segmented by an index. Using our car dataset we can gain a greater understanding about the price distribution of used cars. Since the age of a car dramatically affects the price we will plot the first regsitration year as our x axis variable and price as our y. We can then set our hue to sepearate out the various model variants. from matplotlib.ticker import AutoMinorLocatorfig = plt.figure(figsize=(18,6))LOOKBACK_YEARS = 3REGISTRATION_YEAR = 2017filtered_years = car_data[car_data['firstRegistrationYear'] > REGISTRATION_YEAR - LOOKBACK_YEARS]ax1 = sns.violinplot('firstRegistrationYear', "price", data=filtered_years, hue='modelLine')ax1.minorticks_on()ax1.xaxis.set_minor_locator(AutoMinorLocator(2))ax1.grid(which='minor', axis='x', linewidth=1) Notice that the violin plot function returns the axis on which the plot is displayed. This allows us to edit property of the axis. In this case we have set minor ticks on and used the AutoMinorLocator to place 1 minor tick between each major interval. I then made the minor grid visible with line width of 1. This was neat hack to put a box around each registration year. In datasets with a small number of features (10–15) Seaborn Pairplots can quickly enable a visual inspection of any relationships between variables. Graphs along the left diagonal represent the distribution of each feature, whilst graphs on off diagonals show the relationship between variables. sns.pairplot(car_data.loc[:,car_data.dtypes == 'float64']) Similarly we can utilise the pandas Corr() to find the correlation between each variable in the matrix and plot this using Seaborn’s Heatmap function, specifying the labels and the Heatmap colour range. corr = car_data.loc[:,car_data.dtypes == 'float64'].corr()sns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns, cmap=sns.diverging_palette(220, 10, as_cmap=True)) These two tools combined can be quite useful for identifying important features to a model quickly. Using the Heatmap for example we can see from the top row, that the number of gears and the first registration are positively correlated with price, where as milage is likely to be negatively correlated. Its by far a perfect tool for analysis, but useful at a basic level. Below is some data from my previous post on China’s Property Bubble. I wanted to show construction data for all cities and then provide a subsequent breakdown by city tier in a single figure. Lets breakdown how we might create such a figure: First we define the size of the figure to provide adequate graphing space. When plotting with multiple axis we define a grid on which axis may be place on. We then use the subplot2grid function to return an axis at the desired location (specified from top left corner) with the correct span of rows / columns. fig = plt.figure(figsize = (15,12))grid_size = (3,2)hosts_to_fmt = []# Place A Title On The Figurefig.text(x=0.8, y=0.95, s='Sources: China National Bureau of Statistics',fontproperties=subtitle_font, horizontalalignment='left',color='#524939')# Overlay multiple plots onto the same axis, which spans 1 entire column of the figurelarge_left_ax = plt.subplot2grid(grid_size, (0,0), colspan=1, rowspan=3) We can then subsequently plot onto this axis by specifying the ax property of the plot function. Note that the despite plotting onto a specific axis, the use of the secondary_y parameter means a new axis instance will be created. This will be important to store for formatting later. # Aggregating to series into single data frame for ease of plottingconstruction_statistics = pd.DataFrame({ 'Constructed Floorspace (sq.m, City Avg)': china_constructed_units_total, 'Purchased Units (sq.m, City Avg)': china_under_construction_units_total,})construction_statistics.plot(ax=large_left_ax, legend=True, color=['b', 'r'], title='All Tiers')# Second graph overlayed on the secondary y axislarge_left_ax_secondary = china_years_to_construct_existing_pipeline.plot( ax=large_left_ax, label='Years of Backlog', linestyle='dotted', legend=True, secondary_y=True, color='g')# Adds the axis for formatting laterhosts_to_fmt.extend([large_left_ax, large_left_ax_secondary]) To produce the breakdowns by city tier, we again utilise the subplot2grid but this time change the index on every loop, such that the 3 tier charts plot one below the other. # For each City Tier overlay a series of graphs on an axis on the right hand column# Its row position determined by its indexfor index, tier in enumerate(draw_tiers[0:3]): tier_axis = plt.subplot2grid(grid_size, (index,1)) china_constructed_units_tiered[tier].plot(ax=tier_axis, title=tier, color='b', legend=False) ax1 = china_under_construction_units_tiered[tier].plot( ax=tier_axis,linestyle='dashed', label='Purchased Units (sq.m,City Avg)', title=tier, legend=True, color='r') ax2 =china_property_price_sqmetre_cities_tiered[tier].plot( ax=tier_axis, linestyle='dotted', label='Yuan / sq.m', secondary_y=True, legend=True, color='black') ax2.set_ylim(0,30000)hosts_to_fmt.extend([ax1,ax2]) Ok so now we have generated the correct layout and plotted data: In the case of the above chart, I went for a styling similar to the ft.com. First up we need to import our fonts via Matplotlib font manager, and create a font properties objects for each respective category. import matplotlib.font_manager as fm# Font Importsheading_font = fm.FontProperties(fname='/Users/hugo/Desktop/Playfair_Display/PlayfairDisplay-Regular.ttf', size=22)subtitle_font = fm.FontProperties(fname='/Users/hugo/Library/Fonts/Roboto-Regular.ttf', size=12)# Color Themescolor_bg = '#FEF1E5'lighter_highlight = '#FAE6E1'darker_highlight = '#FBEADC' Next we will define a function which will: Set the figure background (using set_facecolor) Apply a title to the figure using the specified title font. Call the tight layout function which utilises the plot space more compactly. Next we will iterate over each axes within the figure and call a function to: Disable all except the bottom spines (axes borders) Set the background colour of the axis to be slightly darker. Disable the white box around the legend if a legend exists. Set the title of each axis to use the subtitle font. Finally we just need to call the formatter function we created and pass in our figure and the axes we collected earlier. Thanks for reading this tutorial, hopefully this helps get you up and running with Pandas and Matplotlib.
[ { "code": null, "e": 552, "s": 172, "text": "After recently using Pandas and Matplotlib to produce the graphs / analysis for this article on China’s property bubble , and creating a random forrest regression model to find undervalued used cars (more on this soon). I decided to put together this practical guide, which should hopefully be enough to get you up and running with your own data exploration using Pandas and MPL!" }, { "code": null, "e": 607, "s": 552, "text": "This article is broken up into the following Sections:" }, { "code": null, "e": 630, "s": 607, "text": "The Basic Requirements" }, { "code": null, "e": 652, "s": 630, "text": "Reading Data From CSV" }, { "code": null, "e": 699, "s": 652, "text": "Formatting, cleaning and filtering Data Frames" }, { "code": null, "e": 718, "s": 699, "text": "Group-by and Merge" }, { "code": null, "e": 740, "s": 718, "text": "Visualising Your Data" }, { "code": null, "e": 765, "s": 740, "text": "The Plot Function Basics" }, { "code": null, "e": 793, "s": 765, "text": "Seaborn violin and lm-plots" }, { "code": null, "e": 818, "s": 793, "text": "Pair plots and Heat maps" }, { "code": null, "e": 836, "s": 818, "text": "Figure Aesthetics" }, { "code": null, "e": 864, "s": 836, "text": "Plotting with multiple axis" }, { "code": null, "e": 904, "s": 864, "text": "Making your charts look less scientific" }, { "code": null, "e": 1058, "s": 904, "text": "import matplotlib.pyplot as pltimport pandas as pdimport numpy as np%matplotlib inlinecar_data = pd.read_csv('inbox/CarData-E-class-Tue Jul 03 2018.csv')" }, { "code": null, "e": 1191, "s": 1058, "text": "Inline indicates to present graphs as cell output, read_csv returns a DataFrame, the file path is relative to that of your notebook." }, { "code": null, "e": 1553, "s": 1191, "text": "Often when dealing with a large number of features it is nice to see the first row, or the names of all the columns, using the columns property and head(nRows) function. However if we are interested in the types of values for a categorical such as the modelLine, we can access the column using the square bracket syntax and use .unique() to inspect the options." }, { "code": null, "e": 1593, "s": 1553, "text": "print(car_data.columns)car_data.head(2)" }, { "code": null, "e": 1624, "s": 1593, "text": "car_data['modelLine'].unique()" }, { "code": null, "e": 1942, "s": 1624, "text": "There are clearly multiple versions of the same model line entered under different variations of ‘Special Equipment’ so we will use a regex to replace anything containing SE with Special equipment. Similarly there are some columns with Nans (Not a Number) so we will just drop these with dropna(subset=[‘modelLine’])." }, { "code": null, "e": 2101, "s": 1942, "text": "car_data = car_data.dropna(subset=['modelLine'])car_data['modelLine'] = car_data['modelLine'].replace(to_replace={'.*SE.*': 'Standard equipment'}, regex=True)" }, { "code": null, "e": 2366, "s": 2101, "text": "We can also filter out unwanted values such as ‘undefined’ by comparing the rows of modelLine against some boolean question, this returns a boolean array of the same dimensions as the DataFrame rows which can be used to filter with the square bracket syntax again." }, { "code": null, "e": 2456, "s": 2366, "text": "car_data = car_data[(car_data['modelLine'] != 'undefined')]car_data['modelLine'].unique()" }, { "code": null, "e": 2721, "s": 2456, "text": "Note above how pandas never mutates any existing data, hence we have to overwrite our old data manually when we perform any mutations / filters. Whilst this may seem redundant, its extremely effective method of reducing unwanted side effects and bugs in your code." }, { "code": null, "e": 2964, "s": 2721, "text": "Moving on, we also need to change the firstRegistration field typically this should be treated as a python date format, but instead we will treat it as a numeric field for convenience in performing regressions on the data in a future article." }, { "code": null, "e": 3241, "s": 2964, "text": "Considering this data is associated with car registration, the year is really the important component we need to keep. Thus treating this as a numeric field means we can apply numerical rounding, multiplication / division to create a Registration Year feature column as below." }, { "code": null, "e": 3405, "s": 3241, "text": "car_data['firstRegistration'].head(5)car_data[‘firstRegistrationYear’] = round((car_data[‘firstRegistration’] / 10000),0)car_data[‘firstRegistrationYear’] .head(5)" }, { "code": null, "e": 3657, "s": 3405, "text": "Group-by’s can be used to build groups of rows based off a specific feature in your dataset eg. the ‘modelLine’ categorical column. We can then perform an operation such as mean, min, max, std on the individual groups to help describe the sample data." }, { "code": null, "e": 3796, "s": 3657, "text": "group_by_modelLine = car_data.groupby(by=['modelLine'])car_data_avg = group_by_modelLine.mean()car_data_count = group_by_modelLine.count()" }, { "code": null, "e": 4507, "s": 3796, "text": "As you can see the mean value for each numeric feature has been calculated for each model Line. Group by’s are highly versatile and also accept lambda functions for more complex row / group labelling.Next we will assemble a DataFrame of only the relevant features to plot a graph of availability (or car count) and average equipment per car. This DataFrame can be created by passing in a dictionary of keys which represent the columns and values which are single columns or Series from our existing data. This works here because both Data Frames have the same number of rows. Alternatively we can merge the two Data Frames by their indexes (modelLine) and rename the suffixes of repeated columns appropriately." }, { "code": null, "e": 4611, "s": 4507, "text": "We will then plot these two variables sorting by equipment then availability as a horizontal bar graph." }, { "code": null, "e": 5236, "s": 4611, "text": "# Since all the columns in car_data_count are the same, we will use just the first column as the rest yield the same result. iloc allows us to take all the rows and the zeroth column.car_data_count_series = car_data_count.iloc[:,0]features_of_interest = pd.DataFrame({'equipment': car_data_avg['equipment'], 'availability': car_data_count_series})alternative_method = car_data_avg.merge(car_data_count, left_index=True, right_index=True, suffixes=['_avg','_count'])alternative_method[['equipment_avg', 'firstRegistration_count']].sort_values(by=['equipment_avg', 'firstRegistration_count'], ascending=True).plot(kind='barh')" }, { "code": null, "e": 5338, "s": 5236, "text": "Pandas has a built in .plot() function as part of the DataFrame class. It has several key parameters:" }, { "code": null, "e": 5888, "s": 5338, "text": "kind — ‘bar’,’barh’,’pie’,’scatter’,’kde’ etc which can be found in the docs.color — Which accepts and array of hex codes corresponding sequential to each data series / column.linestyle — ‘solid’, ‘dotted’, ‘dashed’ (applies to line graphs only)xlim, ylim — specify a tuple (lower limit, upper limit) for which the plot will be drawnlegend— a boolean value to display or hide the legendlabels — a list corresponding to the number of columns in the dataframe, a descriptive name can be provided here for the legendtitle — The string title of the plot" }, { "code": null, "e": 5988, "s": 5888, "text": "These are fairly straightforward to use and we’ll do some examples using .plot() later in the post." }, { "code": null, "e": 6378, "s": 5988, "text": "Seaborn builds on top of matplotlib to provide a richer out of the box environment. It includes a neat lmplot plot function for rapid exploration of multiple variables. Using our car data example, we would like to understand the association between the equipment kit-out of a car and the sale price. Obviously we would also like this data segmented by model line to compare like with like." }, { "code": null, "e": 6400, "s": 6378, "text": "import seaborn as sns" }, { "code": null, "e": 6621, "s": 6400, "text": "Passing in our column labels for equipment and price (x and y axis) followed by the actual DataFrame source. Use the col keyword to generate a separate plot for each model line and set the col_wrap 2 to make a nice grid." }, { "code": null, "e": 6796, "s": 6621, "text": "filtered_class = car_data[car_data['modelLine'] != 'AVANTGARDE']sns.lmplot(\"equipment\", \"price\", data=filtered_class, hue=\"gears\", fit_reg=False, col='modelLine', col_wrap=2)" }, { "code": null, "e": 7057, "s": 6796, "text": "As you can see putting a hue onto the chart for the number of gears was particularly informative, as these types of car tend to be no better equipped but more expensive. As you can see we could perform significant exploration of our dataset in 3 lines of code." }, { "code": null, "e": 7479, "s": 7057, "text": "These plots are excellent for dealing with large continuous datasets, and can similarly be segmented by an index. Using our car dataset we can gain a greater understanding about the price distribution of used cars. Since the age of a car dramatically affects the price we will plot the first regsitration year as our x axis variable and price as our y. We can then set our hue to sepearate out the various model variants." }, { "code": null, "e": 7902, "s": 7479, "text": "from matplotlib.ticker import AutoMinorLocatorfig = plt.figure(figsize=(18,6))LOOKBACK_YEARS = 3REGISTRATION_YEAR = 2017filtered_years = car_data[car_data['firstRegistrationYear'] > REGISTRATION_YEAR - LOOKBACK_YEARS]ax1 = sns.violinplot('firstRegistrationYear', \"price\", data=filtered_years, hue='modelLine')ax1.minorticks_on()ax1.xaxis.set_minor_locator(AutoMinorLocator(2))ax1.grid(which='minor', axis='x', linewidth=1)" }, { "code": null, "e": 8274, "s": 7902, "text": "Notice that the violin plot function returns the axis on which the plot is displayed. This allows us to edit property of the axis. In this case we have set minor ticks on and used the AutoMinorLocator to place 1 minor tick between each major interval. I then made the minor grid visible with line width of 1. This was neat hack to put a box around each registration year." }, { "code": null, "e": 8570, "s": 8274, "text": "In datasets with a small number of features (10–15) Seaborn Pairplots can quickly enable a visual inspection of any relationships between variables. Graphs along the left diagonal represent the distribution of each feature, whilst graphs on off diagonals show the relationship between variables." }, { "code": null, "e": 8629, "s": 8570, "text": "sns.pairplot(car_data.loc[:,car_data.dtypes == 'float64'])" }, { "code": null, "e": 8832, "s": 8629, "text": "Similarly we can utilise the pandas Corr() to find the correlation between each variable in the matrix and plot this using Seaborn’s Heatmap function, specifying the labels and the Heatmap colour range." }, { "code": null, "e": 9011, "s": 8832, "text": "corr = car_data.loc[:,car_data.dtypes == 'float64'].corr()sns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns, cmap=sns.diverging_palette(220, 10, as_cmap=True))" }, { "code": null, "e": 9384, "s": 9011, "text": "These two tools combined can be quite useful for identifying important features to a model quickly. Using the Heatmap for example we can see from the top row, that the number of gears and the first registration are positively correlated with price, where as milage is likely to be negatively correlated. Its by far a perfect tool for analysis, but useful at a basic level." }, { "code": null, "e": 9576, "s": 9384, "text": "Below is some data from my previous post on China’s Property Bubble. I wanted to show construction data for all cities and then provide a subsequent breakdown by city tier in a single figure." }, { "code": null, "e": 9626, "s": 9576, "text": "Lets breakdown how we might create such a figure:" }, { "code": null, "e": 9936, "s": 9626, "text": "First we define the size of the figure to provide adequate graphing space. When plotting with multiple axis we define a grid on which axis may be place on. We then use the subplot2grid function to return an axis at the desired location (specified from top left corner) with the correct span of rows / columns." }, { "code": null, "e": 10339, "s": 9936, "text": "fig = plt.figure(figsize = (15,12))grid_size = (3,2)hosts_to_fmt = []# Place A Title On The Figurefig.text(x=0.8, y=0.95, s='Sources: China National Bureau of Statistics',fontproperties=subtitle_font, horizontalalignment='left',color='#524939')# Overlay multiple plots onto the same axis, which spans 1 entire column of the figurelarge_left_ax = plt.subplot2grid(grid_size, (0,0), colspan=1, rowspan=3)" }, { "code": null, "e": 10623, "s": 10339, "text": "We can then subsequently plot onto this axis by specifying the ax property of the plot function. Note that the despite plotting onto a specific axis, the use of the secondary_y parameter means a new axis instance will be created. This will be important to store for formatting later." }, { "code": null, "e": 11330, "s": 10623, "text": "# Aggregating to series into single data frame for ease of plottingconstruction_statistics = pd.DataFrame({ 'Constructed Floorspace (sq.m, City Avg)': china_constructed_units_total, 'Purchased Units (sq.m, City Avg)': china_under_construction_units_total,})construction_statistics.plot(ax=large_left_ax, legend=True, color=['b', 'r'], title='All Tiers')# Second graph overlayed on the secondary y axislarge_left_ax_secondary = china_years_to_construct_existing_pipeline.plot( ax=large_left_ax, label='Years of Backlog', linestyle='dotted', legend=True, secondary_y=True, color='g')# Adds the axis for formatting laterhosts_to_fmt.extend([large_left_ax, large_left_ax_secondary])" }, { "code": null, "e": 11504, "s": 11330, "text": "To produce the breakdowns by city tier, we again utilise the subplot2grid but this time change the index on every loop, such that the 3 tier charts plot one below the other." }, { "code": null, "e": 12259, "s": 11504, "text": "# For each City Tier overlay a series of graphs on an axis on the right hand column# Its row position determined by its indexfor index, tier in enumerate(draw_tiers[0:3]): tier_axis = plt.subplot2grid(grid_size, (index,1)) china_constructed_units_tiered[tier].plot(ax=tier_axis, title=tier, color='b', legend=False) ax1 = china_under_construction_units_tiered[tier].plot( ax=tier_axis,linestyle='dashed', label='Purchased Units (sq.m,City Avg)', title=tier, legend=True, color='r') ax2 =china_property_price_sqmetre_cities_tiered[tier].plot( ax=tier_axis, linestyle='dotted', label='Yuan / sq.m', secondary_y=True, legend=True, color='black') ax2.set_ylim(0,30000)hosts_to_fmt.extend([ax1,ax2])" }, { "code": null, "e": 12324, "s": 12259, "text": "Ok so now we have generated the correct layout and plotted data:" }, { "code": null, "e": 12533, "s": 12324, "text": "In the case of the above chart, I went for a styling similar to the ft.com. First up we need to import our fonts via Matplotlib font manager, and create a font properties objects for each respective category." }, { "code": null, "e": 12886, "s": 12533, "text": "import matplotlib.font_manager as fm# Font Importsheading_font = fm.FontProperties(fname='/Users/hugo/Desktop/Playfair_Display/PlayfairDisplay-Regular.ttf', size=22)subtitle_font = fm.FontProperties(fname='/Users/hugo/Library/Fonts/Roboto-Regular.ttf', size=12)# Color Themescolor_bg = '#FEF1E5'lighter_highlight = '#FAE6E1'darker_highlight = '#FBEADC'" }, { "code": null, "e": 12929, "s": 12886, "text": "Next we will define a function which will:" }, { "code": null, "e": 12977, "s": 12929, "text": "Set the figure background (using set_facecolor)" }, { "code": null, "e": 13037, "s": 12977, "text": "Apply a title to the figure using the specified title font." }, { "code": null, "e": 13114, "s": 13037, "text": "Call the tight layout function which utilises the plot space more compactly." }, { "code": null, "e": 13192, "s": 13114, "text": "Next we will iterate over each axes within the figure and call a function to:" }, { "code": null, "e": 13244, "s": 13192, "text": "Disable all except the bottom spines (axes borders)" }, { "code": null, "e": 13305, "s": 13244, "text": "Set the background colour of the axis to be slightly darker." }, { "code": null, "e": 13365, "s": 13305, "text": "Disable the white box around the legend if a legend exists." }, { "code": null, "e": 13418, "s": 13365, "text": "Set the title of each axis to use the subtitle font." }, { "code": null, "e": 13539, "s": 13418, "text": "Finally we just need to call the formatter function we created and pass in our figure and the axes we collected earlier." } ]
How to get the value of radio button using AngularJS ? - GeeksforGeeks
27 Jan, 2022 In this article, we will see how to get the radio button’s value with the help of AngularJS. In this article, we will use the ng-model to get the value of the checked radio button. Example 1: In this example, the selected value is shown with an alert. HTML <!DOCTYPE HTML><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.selectedGender = ''; $scope.getVal = function (gender) { alert(gender); }; }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to get the radio button value in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> <form action="javascript:void(0)"> Male: <input type="radio" name="userGender" ng-model='gender' value="Male" /> <br> Female : <input type="radio" name="userGender" ng-model='gender' value="Female" /> <br> <br> <button ng-click="getVal(gender)"> Click here </button> </form> </div> </div></body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: In this example, the selected value is shown in a <p> tag. HTML <!DOCTYPE HTML><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.selGender = ''; $scope.getVal = function (gender) { $scope.selGender = angular.copy(gender); }; }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to get the radio button value in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> <form action="javascript:void(0)"> Male: <input type="radio" name="userGender" ng-model='gender' value="Male" /> <br> Female : <input type="radio" name="userGender" ng-model='gender' value="Female" /> <br> <br> <button ng-click="getVal(gender)"> Click here </button> </form> <p>Chosen Gender = {{selGender}}</p> </div> </div></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. sweetyty AngularJS-Misc HTML-Misc AngularJS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Angular Libraries For Web Developers How to use <mat-chip-list> and <mat-chip> in Angular Material ? Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular PrimeNG Dropdown Component Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 25029, "s": 25001, "text": "\n27 Jan, 2022" }, { "code": null, "e": 25211, "s": 25029, "text": "In this article, we will see how to get the radio button’s value with the help of AngularJS. In this article, we will use the ng-model to get the value of the checked radio button. " }, { "code": null, "e": 25282, "s": 25211, "text": "Example 1: In this example, the selected value is shown with an alert." }, { "code": null, "e": 25287, "s": 25282, "text": "HTML" }, { "code": "<!DOCTYPE HTML><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.selectedGender = ''; $scope.getVal = function (gender) { alert(gender); }; }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to get the radio button value in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> <form action=\"javascript:void(0)\"> Male: <input type=\"radio\" name=\"userGender\" ng-model='gender' value=\"Male\" /> <br> Female : <input type=\"radio\" name=\"userGender\" ng-model='gender' value=\"Female\" /> <br> <br> <button ng-click=\"getVal(gender)\"> Click here </button> </form> </div> </div></body> </html>", "e": 26511, "s": 25287, "text": null }, { "code": null, "e": 26519, "s": 26511, "text": "Output:" }, { "code": null, "e": 26550, "s": 26519, "text": "Before clicking on the button:" }, { "code": null, "e": 26580, "s": 26550, "text": "After clicking on the button:" }, { "code": null, "e": 26650, "s": 26580, "text": "Example 2: In this example, the selected value is shown in a <p> tag." }, { "code": null, "e": 26655, "s": 26650, "text": "HTML" }, { "code": "<!DOCTYPE HTML><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.selGender = ''; $scope.getVal = function (gender) { $scope.selGender = angular.copy(gender); }; }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to get the radio button value in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> <form action=\"javascript:void(0)\"> Male: <input type=\"radio\" name=\"userGender\" ng-model='gender' value=\"Male\" /> <br> Female : <input type=\"radio\" name=\"userGender\" ng-model='gender' value=\"Female\" /> <br> <br> <button ng-click=\"getVal(gender)\"> Click here </button> </form> <p>Chosen Gender = {{selGender}}</p> </div> </div></body> </html>", "e": 27947, "s": 26655, "text": null }, { "code": null, "e": 27955, "s": 27947, "text": "Output:" }, { "code": null, "e": 28092, "s": 27955, "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": 28101, "s": 28092, "text": "sweetyty" }, { "code": null, "e": 28116, "s": 28101, "text": "AngularJS-Misc" }, { "code": null, "e": 28126, "s": 28116, "text": "HTML-Misc" }, { "code": null, "e": 28136, "s": 28126, "text": "AngularJS" }, { "code": null, "e": 28141, "s": 28136, "text": "HTML" }, { "code": null, "e": 28158, "s": 28141, "text": "Web Technologies" }, { "code": null, "e": 28163, "s": 28158, "text": "HTML" }, { "code": null, "e": 28261, "s": 28163, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28270, "s": 28261, "text": "Comments" }, { "code": null, "e": 28283, "s": 28270, "text": "Old Comments" }, { "code": null, "e": 28327, "s": 28283, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 28391, "s": 28327, "text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?" }, { "code": null, "e": 28415, "s": 28391, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 28468, "s": 28415, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 28503, "s": 28468, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 28565, "s": 28503, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28615, "s": 28565, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 28675, "s": 28615, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28723, "s": 28675, "text": "How to update Node.js and NPM to next version ?" } ]
How to create a Password Entry Field in Tkinter?
Suppose you are creating a Login Form for a Tkinter application. In many cases, an ideal login requires a standard format of username, password, and other details of the user. Users can enter the password in the Entry field with any combination of alphanumeric characters. Generally, to establish a secure bridge between the user and the application, the password fields store the input in the form of "*" characters. In order to create a field that accepts the input in the form of "*," we have to use show="*" attribute in the Entry widget. The following example will have an Entry widget that accepts the password in hidden form. If we click "Show Password", it will show the password on the screen. # Import the required libraries from tkinter import * from tkinter import ttk # Create an instance of tkinter frame or window win = Tk() # Set the size of the window win.geometry("700x350") # Define a function to show the entered password def show(): p = password.get() ttk.Label(win, text="Your Password is: " + str(p)).pack() password = StringVar() # Add an Entry widget for accepting User Password entry = Entry(win, width=25, textvariable=password, show="*") entry.pack(pady=10) # Add a Button to reveal the password ttk.Button(win, text="Show Password", command=show).pack() win.mainloop() Running the above code will display a password field and a button to reveal the password on the screen. Now, click the "Show Password" button to reveal the password on the screen.
[ { "code": null, "e": 1605, "s": 1062, "text": "Suppose you are creating a Login Form for a Tkinter application. In many cases, an ideal login requires a standard format of username, password, and other details of the user. Users can enter the password in the Entry field with any combination of alphanumeric characters. Generally, to establish a secure bridge between the user and the application, the password fields store the input in the form of \"*\" characters. In order to create a field that accepts the input in the form of \"*,\" we have to use show=\"*\" attribute in the Entry widget." }, { "code": null, "e": 1765, "s": 1605, "text": "The following example will have an Entry widget that accepts the password in hidden form. If we click \"Show Password\", it will show the password on the screen." }, { "code": null, "e": 2373, "s": 1765, "text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame or window\nwin = Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\n# Define a function to show the entered password\ndef show():\n p = password.get()\n ttk.Label(win, text=\"Your Password is: \" + str(p)).pack()\n\npassword = StringVar()\n\n# Add an Entry widget for accepting User Password\nentry = Entry(win, width=25, textvariable=password, show=\"*\")\nentry.pack(pady=10)\n\n# Add a Button to reveal the password\nttk.Button(win, text=\"Show Password\", command=show).pack()\n\nwin.mainloop()" }, { "code": null, "e": 2477, "s": 2373, "text": "Running the above code will display a password field and a button to reveal the password on the screen." }, { "code": null, "e": 2553, "s": 2477, "text": "Now, click the \"Show Password\" button to reveal the password on the screen." } ]
Segmentation in OCR !!. A basic explanation of different levels... | by Susmith Reddy | Towards Data Science
Welcome to part III about the working of the OCR system. In the previous post, we have seen the basic and widely used Preprocessing techniques in the OCR system. In this part, we will cover the techniques of another most important phase of the OCR system, Segmentation. Segmentation is nothing but breaking the whole image into subparts to process them further. Segmentation of image is done in the following sequence : → Line level Segmentation → Word level Segmentation → Character level Segmentation For all the above-mentioned levels of Segmentation, we are going to use the Histogram Projection technique. Let me give you a brief introduction to the Histogram Projection method. Once the colored image is converted to the binary image, only black and white pixels are present in the image. In a binary image, pixels representing useful information are called Foreground pixels, and the pixels that are not foreground pixels are called Background pixels. We choose whether a foreground pixel should be white or black while binarizing the image. Horizontal Histogram Projection: In this method, we count the No.of foreground pixels along the rows of the image, and the resultant array is of the size equal to No.of rows in the image (Height of the image). # img be binarized image of size height x width and foregound pixel is white i.e pixel value = 255horizontal_hist = np.sum(img,axis=1,keepdims=True)/255# axis = 1 is used to take sum along the row# horizontal_hist is an array of size height x 1# If the img has foreground pixel as black i.e pixel value = 0horizontal_hist = img.shape[1] - np.sum(img,axis=1,keepdims=True)/255# Logic :- No.of columns - No.of white pixels Plotting horizontal_hist as a histogram looks like this In the above image, Higher peaks imply No.of foreground pixels in the corresponding row is high. Lower peaks imply No.of foreground pixels in the corresponding row are low Vertical Histogram Projection: In this method, we count the No.of foreground pixels along the image columns. The resultant array is of the size equal to No.of columns in the image (Width of the image). # img be binarized image of size height x width and foregound pixel is white i.e pixel value = 255vertical_hist = np.sum(img,axis=0,keepdims=True)/255# axis = 0is used to take sum along the column# vertical_hist is an array of size 1 x width# If the img has foreground pixel as black i.e pixel value = 0vertical_hist = img.shape[0] - np.sum(img,axis=0,keepdims=True)/255# Logic :- No.of rows - No.of white pixels Plotting vertical_hist as a histogram looks like this Note: In the above image, foreground pixels are black, and background pixels are white. In the above image, Higher peaks imply No.of foreground pixels in the corresponding column are high. Lower peaks imply No.of foreground pixels in the corresponding column are low. Now that we have understood Horizontal and Vertical histogram projections, we are ready to know how different levels of Segmentation is performed. Line Level Segmentation: In this level of segmentation, we are provided with a skew corrected image containing text written in the form of lines. The objective of Line Level Segmentation is to segment the image into lines. Line Level Segmentation: In this level of segmentation, we are provided with a skew corrected image containing text written in the form of lines. The objective of Line Level Segmentation is to segment the image into lines. General Rules of writing: We should leave enough space in between the lines. The idea is, If we Horizontally project the binary image, Rows that represent the text in a line have high No.of foreground pixels, which correspond to higher peaks in the histogram. Rows that represent the gaps in-between the lines have high No.of background pixels, which correspond to lower peaks in the histogram. Rows that correspond to lower peaks in the histogram can be selected as the segmenting lines to separate the lines. 2. Word Level Segmentation: At this level of segmentation, we are provided with an image containing a single line (segmented in the previous step) which consists of a sequence of words. The objective of Word Level Segmentation is to segment the image into words. General Rules of writing: We should leave enough space in between the words. The idea is similar to the previous step, but the only change is, here we have to project the image vertically (Sum is taken along columns) because we have to segment words vertically. If we Vertically project the binary image, Columns that represent the text have high No.of foreground pixels, which correspond to higher peaks in the histogram. Columns that represent the gaps in-between the words have high No.of background pixels, which correspond to lower peaks in the histogram. Note: In the above pic, Foreground pixels are black pixels, and background pixels are white. I think you have figured out how the word segmentation is done in the above picture. Columns that correspond to lower peaks in the histogram can be selected as the segmenting lines to separate the words. For segmenting words, lower peaks should be selected in such a way that they should span through a certain width (threshold). This is because we’ll find lower peaks which correspond to the gaps between disconnected characters within a word, which we are not interested in. As we know, the gaps between the words are greater than the gaps between the characters within a word, the threshold should be chosen in such a way that neglects the thin gaps between the characters within the words. 3. Character Level Segmentation: At this level of segmentation, we are provided with an image containing a single word (segmented in the previous step) which consists of a sequence of characters. The objective of Character Level Segmentation is to segment the image into individual characters. This level of segmentation is optional, which depends upon the context where the OCR is being used. If the OCR system is being applied to the text, where characters within a word are separate, Character Level Segmentation is not required. Since a uniform gap is maintained (even though it is small) between the characters within a word, we can segment the characters in the previous step itself (by setting a very low threshold). If the OCR system is being applied to the text, where characters within a word are joined (Cursive handwriting), Character Level Segmentation has to be performed to segment the characters. We can use the same idea which we have used for Word Level Segmentation by leveraging the small gap between the characters, i.e., by projecting the image vertically, we can segment the characters. In Character Level Segmentation, segmenting of characters is not straightforward because of the concept of ligatures in Cursive handwriting. What is Ligature ?? A Ligature is the link which joins the two successive characters in cursive handwriting. Now you might be thinking, What problem does this ligature create .....right?In English script, we have two types of characters Closed Characters: These characters have a loop, and when projected vertically, all the columns spanned across these characters have at least 2 foreground pixels. E.g., a, b, c,d Open Characters: These characters don’t have a loop, and when projected vertically, Of all the columns spanned across these characters, there is at least one column that has only 1 foreground pixel. E.g., u, v, w Thus the OCR system cannot differentiate the ligature with the curve from open characters and considers both valid candidates for segmenting. This problem is known as the Over Segmentation Problem. Note: In the above image, for segmenting, valid candidates are the ligatures (connections between u,m & m,n), and invalid candidates are those, which are a part of the open characters u, m, n (we cant segment in between the character) Till date, we have no perfect solution for this problem, but here is the basic and widely used method to overcome this problem. We assume Thinning is done to 1-pixel width. So possible sum in vertical histogram array is → sum=0, if no foreground pixel is present in the column → sum=1, if either ligature or part of an open character is present in the column → sum>1, if part of a closed character is present in the column. E.g., o,p (has more than one foreground pixel in each column) In the above image, Columns marked in red have either vertical histogram sum=0 or sum=1. These columns are known as PSC (Potential Segmentation Columns). Following rules are followed to select the Valid Segment lines (doesn’t always select a valid segment line, but a majority of times selects a valid one):- Clear vertical space between two consecutive characters, i.e., sum=0, along that column, indicates no foreground pixel is present. So we can select the center column among such consecutive columns. When there is a column with sum=1, which indicates the presence of ligature or part of open character, in this case, Over Segmentation problem is eliminated to a great extent by taking the average of all those PSC which are at a distance less than a particular value (threshold) and by merging them into a single SC(Segmentation Column). The threshold value is the minimum distance along the width of the word image between consecutive PSCs and is so chosen that its value must be less than the width of the thinnest character possible(e.g., i,l) in a word image. Now all these SC’s are validated by a machine learning model trained with a huge amount of data. If the probability of an SC being a valid segmenting line is high, it is considered a valid segmenting line; otherwise, it is ignored. By following the above rules, we can segment characters correctly 90% of the time. In this 3-part series, we got a high-level overview of the working of an OCR System and covered the two most important phases of the OCR system Preprocessing and Segmentation. I hope you understood and enjoyed reading this !!! Any doubts, Suggestions, Corrections are Welcome. Happy Learning ......Signing Off 😀😀 [1] Choudhary, Amit & Rishi, Rahul & Savita, Ahlawat. (2013). A New Character Segmentation Approach for Off-Line Cursive Handwritten Words. Procedia Computer Science. 17. 88–95. 10.1016/j.procs.2013.05.013. [2] Sanchez, A. & Suarez, P.D. & Mello, Carlos & Oliveira, Adriano & Alves, V.M.O.. (2008). Text Line Segmentation in Images of Handwritten Historical Documents. 1–6. 10.1109/IPTA.2008.4743758. [3] Kurniawan, Fajri & Shafry, Mohd & Rahim, Mohd & Matus, Ni & Rakhmadi, Akmal & Mohamad, Dzulkifli. (2011). Characters Segmentation of Cursive Handwritten Words based on Contour Analysis and Neural Network Validation. ITB Journal of Information and Communication Technology. 5. 10.5614/itbj.ict.2011.5.1.1. Image Source: Google
[ { "code": null, "e": 334, "s": 172, "text": "Welcome to part III about the working of the OCR system. In the previous post, we have seen the basic and widely used Preprocessing techniques in the OCR system." }, { "code": null, "e": 442, "s": 334, "text": "In this part, we will cover the techniques of another most important phase of the OCR system, Segmentation." }, { "code": null, "e": 534, "s": 442, "text": "Segmentation is nothing but breaking the whole image into subparts to process them further." }, { "code": null, "e": 675, "s": 534, "text": "Segmentation of image is done in the following sequence : → Line level Segmentation → Word level Segmentation → Character level Segmentation" }, { "code": null, "e": 783, "s": 675, "text": "For all the above-mentioned levels of Segmentation, we are going to use the Histogram Projection technique." }, { "code": null, "e": 967, "s": 783, "text": "Let me give you a brief introduction to the Histogram Projection method. Once the colored image is converted to the binary image, only black and white pixels are present in the image." }, { "code": null, "e": 1221, "s": 967, "text": "In a binary image, pixels representing useful information are called Foreground pixels, and the pixels that are not foreground pixels are called Background pixels. We choose whether a foreground pixel should be white or black while binarizing the image." }, { "code": null, "e": 1431, "s": 1221, "text": "Horizontal Histogram Projection: In this method, we count the No.of foreground pixels along the rows of the image, and the resultant array is of the size equal to No.of rows in the image (Height of the image)." }, { "code": null, "e": 1852, "s": 1431, "text": "# img be binarized image of size height x width and foregound pixel is white i.e pixel value = 255horizontal_hist = np.sum(img,axis=1,keepdims=True)/255# axis = 1 is used to take sum along the row# horizontal_hist is an array of size height x 1# If the img has foreground pixel as black i.e pixel value = 0horizontal_hist = img.shape[1] - np.sum(img,axis=1,keepdims=True)/255# Logic :- No.of columns - No.of white pixels" }, { "code": null, "e": 1908, "s": 1852, "text": "Plotting horizontal_hist as a histogram looks like this" }, { "code": null, "e": 1928, "s": 1908, "text": "In the above image," }, { "code": null, "e": 2005, "s": 1928, "text": "Higher peaks imply No.of foreground pixels in the corresponding row is high." }, { "code": null, "e": 2080, "s": 2005, "text": "Lower peaks imply No.of foreground pixels in the corresponding row are low" }, { "code": null, "e": 2282, "s": 2080, "text": "Vertical Histogram Projection: In this method, we count the No.of foreground pixels along the image columns. The resultant array is of the size equal to No.of columns in the image (Width of the image)." }, { "code": null, "e": 2695, "s": 2282, "text": "# img be binarized image of size height x width and foregound pixel is white i.e pixel value = 255vertical_hist = np.sum(img,axis=0,keepdims=True)/255# axis = 0is used to take sum along the column# vertical_hist is an array of size 1 x width# If the img has foreground pixel as black i.e pixel value = 0vertical_hist = img.shape[0] - np.sum(img,axis=0,keepdims=True)/255# Logic :- No.of rows - No.of white pixels" }, { "code": null, "e": 2749, "s": 2695, "text": "Plotting vertical_hist as a histogram looks like this" }, { "code": null, "e": 2837, "s": 2749, "text": "Note: In the above image, foreground pixels are black, and background pixels are white." }, { "code": null, "e": 2857, "s": 2837, "text": "In the above image," }, { "code": null, "e": 2938, "s": 2857, "text": "Higher peaks imply No.of foreground pixels in the corresponding column are high." }, { "code": null, "e": 3017, "s": 2938, "text": "Lower peaks imply No.of foreground pixels in the corresponding column are low." }, { "code": null, "e": 3164, "s": 3017, "text": "Now that we have understood Horizontal and Vertical histogram projections, we are ready to know how different levels of Segmentation is performed." }, { "code": null, "e": 3387, "s": 3164, "text": "Line Level Segmentation: In this level of segmentation, we are provided with a skew corrected image containing text written in the form of lines. The objective of Line Level Segmentation is to segment the image into lines." }, { "code": null, "e": 3610, "s": 3387, "text": "Line Level Segmentation: In this level of segmentation, we are provided with a skew corrected image containing text written in the form of lines. The objective of Line Level Segmentation is to segment the image into lines." }, { "code": null, "e": 3687, "s": 3610, "text": "General Rules of writing: We should leave enough space in between the lines." }, { "code": null, "e": 3745, "s": 3687, "text": "The idea is, If we Horizontally project the binary image," }, { "code": null, "e": 3870, "s": 3745, "text": "Rows that represent the text in a line have high No.of foreground pixels, which correspond to higher peaks in the histogram." }, { "code": null, "e": 4005, "s": 3870, "text": "Rows that represent the gaps in-between the lines have high No.of background pixels, which correspond to lower peaks in the histogram." }, { "code": null, "e": 4121, "s": 4005, "text": "Rows that correspond to lower peaks in the histogram can be selected as the segmenting lines to separate the lines." }, { "code": null, "e": 4384, "s": 4121, "text": "2. Word Level Segmentation: At this level of segmentation, we are provided with an image containing a single line (segmented in the previous step) which consists of a sequence of words. The objective of Word Level Segmentation is to segment the image into words." }, { "code": null, "e": 4461, "s": 4384, "text": "General Rules of writing: We should leave enough space in between the words." }, { "code": null, "e": 4646, "s": 4461, "text": "The idea is similar to the previous step, but the only change is, here we have to project the image vertically (Sum is taken along columns) because we have to segment words vertically." }, { "code": null, "e": 4689, "s": 4646, "text": "If we Vertically project the binary image," }, { "code": null, "e": 4807, "s": 4689, "text": "Columns that represent the text have high No.of foreground pixels, which correspond to higher peaks in the histogram." }, { "code": null, "e": 4945, "s": 4807, "text": "Columns that represent the gaps in-between the words have high No.of background pixels, which correspond to lower peaks in the histogram." }, { "code": null, "e": 5038, "s": 4945, "text": "Note: In the above pic, Foreground pixels are black pixels, and background pixels are white." }, { "code": null, "e": 5242, "s": 5038, "text": "I think you have figured out how the word segmentation is done in the above picture. Columns that correspond to lower peaks in the histogram can be selected as the segmenting lines to separate the words." }, { "code": null, "e": 5732, "s": 5242, "text": "For segmenting words, lower peaks should be selected in such a way that they should span through a certain width (threshold). This is because we’ll find lower peaks which correspond to the gaps between disconnected characters within a word, which we are not interested in. As we know, the gaps between the words are greater than the gaps between the characters within a word, the threshold should be chosen in such a way that neglects the thin gaps between the characters within the words." }, { "code": null, "e": 6026, "s": 5732, "text": "3. Character Level Segmentation: At this level of segmentation, we are provided with an image containing a single word (segmented in the previous step) which consists of a sequence of characters. The objective of Character Level Segmentation is to segment the image into individual characters." }, { "code": null, "e": 6126, "s": 6026, "text": "This level of segmentation is optional, which depends upon the context where the OCR is being used." }, { "code": null, "e": 6456, "s": 6126, "text": "If the OCR system is being applied to the text, where characters within a word are separate, Character Level Segmentation is not required. Since a uniform gap is maintained (even though it is small) between the characters within a word, we can segment the characters in the previous step itself (by setting a very low threshold)." }, { "code": null, "e": 6645, "s": 6456, "text": "If the OCR system is being applied to the text, where characters within a word are joined (Cursive handwriting), Character Level Segmentation has to be performed to segment the characters." }, { "code": null, "e": 6842, "s": 6645, "text": "We can use the same idea which we have used for Word Level Segmentation by leveraging the small gap between the characters, i.e., by projecting the image vertically, we can segment the characters." }, { "code": null, "e": 6983, "s": 6842, "text": "In Character Level Segmentation, segmenting of characters is not straightforward because of the concept of ligatures in Cursive handwriting." }, { "code": null, "e": 7092, "s": 6983, "text": "What is Ligature ?? A Ligature is the link which joins the two successive characters in cursive handwriting." }, { "code": null, "e": 7220, "s": 7092, "text": "Now you might be thinking, What problem does this ligature create .....right?In English script, we have two types of characters" }, { "code": null, "e": 7399, "s": 7220, "text": "Closed Characters: These characters have a loop, and when projected vertically, all the columns spanned across these characters have at least 2 foreground pixels. E.g., a, b, c,d" }, { "code": null, "e": 7612, "s": 7399, "text": "Open Characters: These characters don’t have a loop, and when projected vertically, Of all the columns spanned across these characters, there is at least one column that has only 1 foreground pixel. E.g., u, v, w" }, { "code": null, "e": 7810, "s": 7612, "text": "Thus the OCR system cannot differentiate the ligature with the curve from open characters and considers both valid candidates for segmenting. This problem is known as the Over Segmentation Problem." }, { "code": null, "e": 8045, "s": 7810, "text": "Note: In the above image, for segmenting, valid candidates are the ligatures (connections between u,m & m,n), and invalid candidates are those, which are a part of the open characters u, m, n (we cant segment in between the character)" }, { "code": null, "e": 8532, "s": 8045, "text": "Till date, we have no perfect solution for this problem, but here is the basic and widely used method to overcome this problem. We assume Thinning is done to 1-pixel width. So possible sum in vertical histogram array is → sum=0, if no foreground pixel is present in the column → sum=1, if either ligature or part of an open character is present in the column → sum>1, if part of a closed character is present in the column. E.g., o,p (has more than one foreground pixel in each column)" }, { "code": null, "e": 8686, "s": 8532, "text": "In the above image, Columns marked in red have either vertical histogram sum=0 or sum=1. These columns are known as PSC (Potential Segmentation Columns)." }, { "code": null, "e": 8841, "s": 8686, "text": "Following rules are followed to select the Valid Segment lines (doesn’t always select a valid segment line, but a majority of times selects a valid one):-" }, { "code": null, "e": 9039, "s": 8841, "text": "Clear vertical space between two consecutive characters, i.e., sum=0, along that column, indicates no foreground pixel is present. So we can select the center column among such consecutive columns." }, { "code": null, "e": 9835, "s": 9039, "text": "When there is a column with sum=1, which indicates the presence of ligature or part of open character, in this case, Over Segmentation problem is eliminated to a great extent by taking the average of all those PSC which are at a distance less than a particular value (threshold) and by merging them into a single SC(Segmentation Column). The threshold value is the minimum distance along the width of the word image between consecutive PSCs and is so chosen that its value must be less than the width of the thinnest character possible(e.g., i,l) in a word image. Now all these SC’s are validated by a machine learning model trained with a huge amount of data. If the probability of an SC being a valid segmenting line is high, it is considered a valid segmenting line; otherwise, it is ignored." }, { "code": null, "e": 9918, "s": 9835, "text": "By following the above rules, we can segment characters correctly 90% of the time." }, { "code": null, "e": 10094, "s": 9918, "text": "In this 3-part series, we got a high-level overview of the working of an OCR System and covered the two most important phases of the OCR system Preprocessing and Segmentation." }, { "code": null, "e": 10145, "s": 10094, "text": "I hope you understood and enjoyed reading this !!!" }, { "code": null, "e": 10195, "s": 10145, "text": "Any doubts, Suggestions, Corrections are Welcome." }, { "code": null, "e": 10231, "s": 10195, "text": "Happy Learning ......Signing Off 😀😀" }, { "code": null, "e": 10438, "s": 10231, "text": "[1] Choudhary, Amit & Rishi, Rahul & Savita, Ahlawat. (2013). A New Character Segmentation Approach for Off-Line Cursive Handwritten Words. Procedia Computer Science. 17. 88–95. 10.1016/j.procs.2013.05.013." }, { "code": null, "e": 10632, "s": 10438, "text": "[2] Sanchez, A. & Suarez, P.D. & Mello, Carlos & Oliveira, Adriano & Alves, V.M.O.. (2008). Text Line Segmentation in Images of Handwritten Historical Documents. 1–6. 10.1109/IPTA.2008.4743758." }, { "code": null, "e": 10941, "s": 10632, "text": "[3] Kurniawan, Fajri & Shafry, Mohd & Rahim, Mohd & Matus, Ni & Rakhmadi, Akmal & Mohamad, Dzulkifli. (2011). Characters Segmentation of Cursive Handwritten Words based on Contour Analysis and Neural Network Validation. ITB Journal of Information and Communication Technology. 5. 10.5614/itbj.ict.2011.5.1.1." } ]
Create a contiguous flattened NumPy array - GeeksforGeeks
19 Aug, 2020 Let us see how to create a contiguous array in NumPy.The contiguous flattened array is a two-dimensional and multi-dimensional array that is stored as a one-dimensional array. We will be using the ravel() method to perform this task. Syntax : numpy.ravel(array, order = ‘C’)Parameters : array : Input array. order : C-contiguous, F-contiguous, A-contiguous; optional Returns : Flattened array having same type as the Input array and and order as per choice. Example 1 : Flattening a 2D array. Python3 # Importing librariesimport numpy as np # Creating 2D arrayarr = np.array([[5, 6, 7], [8, 9, 10]])print("Original array:\n", arr) # Flattening the arrayflattened_array = np.ravel(arr)print("New flattened array:\n", flattened_array) Output : Original array: [[ 5 6 7] [ 8 9 10]] New flattened array: [ 5 6 7 8 9 10] Example 2 : Flattening a 3D array. Python3 # Importing librariesimport numpy as np # Creating 3D arrayarr = np.array([[[3, 4], [5, 6]], [[7, 8], [9, 0]]])print("Original array:\n", arr) # Flattening the arrayflattened_array = np.ravel(arr)print("New flattened array:\n", flattened_array) Output : Original array: [[[3 4] [5 6]] [[7 8] [9 0]]] New flattened array: [3 4 5 6 7 8 9 0] Python numpy-arrayManipulation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Python | os.path.join() method Defaultdict in Python Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n19 Aug, 2020" }, { "code": null, "e": 24526, "s": 24292, "text": "Let us see how to create a contiguous array in NumPy.The contiguous flattened array is a two-dimensional and multi-dimensional array that is stored as a one-dimensional array. We will be using the ravel() method to perform this task." }, { "code": null, "e": 24579, "s": 24526, "text": "Syntax : numpy.ravel(array, order = ‘C’)Parameters :" }, { "code": null, "e": 24600, "s": 24579, "text": "array : Input array." }, { "code": null, "e": 24659, "s": 24600, "text": "order : C-contiguous, F-contiguous, A-contiguous; optional" }, { "code": null, "e": 24750, "s": 24659, "text": "Returns : Flattened array having same type as the Input array and and order as per choice." }, { "code": null, "e": 24785, "s": 24750, "text": "Example 1 : Flattening a 2D array." }, { "code": null, "e": 24793, "s": 24785, "text": "Python3" }, { "code": "# Importing librariesimport numpy as np # Creating 2D arrayarr = np.array([[5, 6, 7], [8, 9, 10]])print(\"Original array:\\n\", arr) # Flattening the arrayflattened_array = np.ravel(arr)print(\"New flattened array:\\n\", flattened_array)", "e": 25027, "s": 24793, "text": null }, { "code": null, "e": 25036, "s": 25027, "text": "Output :" }, { "code": null, "e": 25121, "s": 25036, "text": "Original array:\n [[ 5 6 7]\n [ 8 9 10]]\nNew flattened array:\n [ 5 6 7 8 9 10]\n" }, { "code": null, "e": 25156, "s": 25121, "text": "Example 2 : Flattening a 3D array." }, { "code": null, "e": 25164, "s": 25156, "text": "Python3" }, { "code": "# Importing librariesimport numpy as np # Creating 3D arrayarr = np.array([[[3, 4], [5, 6]], [[7, 8], [9, 0]]])print(\"Original array:\\n\", arr) # Flattening the arrayflattened_array = np.ravel(arr)print(\"New flattened array:\\n\", flattened_array)", "e": 25411, "s": 25164, "text": null }, { "code": null, "e": 25420, "s": 25411, "text": "Output :" }, { "code": null, "e": 25514, "s": 25420, "text": "Original array:\n [[[3 4]\n [5 6]]\n\n [[7 8]\n [9 0]]]\nNew flattened array:\n [3 4 5 6 7 8 9 0]\n" }, { "code": null, "e": 25545, "s": 25514, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 25558, "s": 25545, "text": "Python-numpy" }, { "code": null, "e": 25565, "s": 25558, "text": "Python" }, { "code": null, "e": 25663, "s": 25565, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25695, "s": 25663, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25737, "s": 25695, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25793, "s": 25737, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25835, "s": 25793, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25890, "s": 25835, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 25921, "s": 25890, "text": "Python | os.path.join() method" }, { "code": null, "e": 25943, "s": 25921, "text": "Defaultdict in Python" }, { "code": null, "e": 25982, "s": 25943, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26011, "s": 25982, "text": "Create a directory in Python" } ]
How to convert an integer to a character in Python?
Python's built-in function chr() returns a sunicode character equivalent of an integer between 0 to 0x10ffff. >>> chr(a) 'd' >>> chr(300) 'Ĭ' >>> chr(65) 'A'
[ { "code": null, "e": 1172, "s": 1062, "text": "Python's built-in function chr() returns a sunicode character equivalent of an integer between 0 to 0x10ffff." }, { "code": null, "e": 1221, "s": 1172, "text": ">>> chr(a)\n'd'\n>>> chr(300)\n'Ĭ'\n>>> chr(65)\n'A'" } ]
Underscore.js _.difference() Function - GeeksforGeeks
24 Nov, 2021 The Underscore.js is a JavaScript library that provides a lot of useful functions like the map, filter, invoke etc even without using any built-in objects.The _.difference() function returns the values of array that are not present in the other arrays. If element is present in array then this element will not be included in the resultant array. This is because it takes difference of the second array and first array. Syntax: _.difference( array, *others ) Parameters: This function accepts two parameters as mentioned above and described below: array: This parameter is used to hold the array elements. others: It is an array whose elements need to be deleted. Return value: This function returns an array which contains elements of the first array which are not in the second array. Passing a list of numbers to _.difference() function: The ._difference() function takes the element from the list one by one and checks if that element is present in the second array or not. If it is present then it simply ignores the element otherwise add the elements in the resultant array. Example: <!DOCTYPE html><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> console.log(_.difference([1, 2, 3, 4, 5], [1, 2, 3, 4, 6, 7])); </script> </body></html> Output: Passing false values to the _.difference() function: Passing the false values like null, undefined, false, “” (empty string) then the _.difference() function will work in the same way. If any of the false values are present in the first array but not present in the second array then it will be included in the resultant array. Example: <!DOCTYPE html><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> console.log(_.difference([undefined, '', " ", null], [undefined, 4, null])); </script> </body></html> Output: Passing a set of strings to the _.difference() function: Passing the set of strings which contains words inside “” then the _.difference() function will work in the same way. If any of the these string values are present in the first array but not present in the second array then it will be included in the resultant array. Example: <!DOCTYPE html><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> console.log(_.difference( ["This", "is", "geeks", "for", "geeks2"], ["This", "for", "is"]) ); </script> </body></html> Output: Passing two arrays which have the same elements to the _.difference() function: Passing the first and the second array having the same elements then all the elements during the check operation will be ignored. And hence the resultant array will be empty. Example: <!DOCTYPE html><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> console.log(_.difference([1, 2, 3, 4], [1, 2, 3, 4])); </script> </body></html> Output: Note: These commands will not work in Google console or in Firefox as for these additional files need to be added which they didn’t have added. So, add the given links to your HTML file and then run them. <script type="text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script> JavaScript - Underscore.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript? Hide or show elements in HTML using display property Differences between Functional Components and Class Components in React Set the value of an input field in JavaScript Express.js express.Router() Function Installation of Node.js on Linux Convert a string to an integer in JavaScript How to create footer to stay at the bottom of a Web page? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 33211, "s": 33183, "text": "\n24 Nov, 2021" }, { "code": null, "e": 33631, "s": 33211, "text": "The Underscore.js is a JavaScript library that provides a lot of useful functions like the map, filter, invoke etc even without using any built-in objects.The _.difference() function returns the values of array that are not present in the other arrays. If element is present in array then this element will not be included in the resultant array. This is because it takes difference of the second array and first array." }, { "code": null, "e": 33639, "s": 33631, "text": "Syntax:" }, { "code": null, "e": 33670, "s": 33639, "text": "_.difference( array, *others )" }, { "code": null, "e": 33759, "s": 33670, "text": "Parameters: This function accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 33817, "s": 33759, "text": "array: This parameter is used to hold the array elements." }, { "code": null, "e": 33875, "s": 33817, "text": "others: It is an array whose elements need to be deleted." }, { "code": null, "e": 33998, "s": 33875, "text": "Return value: This function returns an array which contains elements of the first array which are not in the second array." }, { "code": null, "e": 34292, "s": 33998, "text": "Passing a list of numbers to _.difference() function: The ._difference() function takes the element from the list one by one and checks if that element is present in the second array or not. If it is present then it simply ignores the element otherwise add the elements in the resultant array." }, { "code": null, "e": 34301, "s": 34292, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> </head> <body> <script type=\"text/javascript\"> console.log(_.difference([1, 2, 3, 4, 5], [1, 2, 3, 4, 6, 7])); </script> </body></html> ", "e": 34679, "s": 34301, "text": null }, { "code": null, "e": 34687, "s": 34679, "text": "Output:" }, { "code": null, "e": 35015, "s": 34687, "text": "Passing false values to the _.difference() function: Passing the false values like null, undefined, false, “” (empty string) then the _.difference() function will work in the same way. If any of the false values are present in the first array but not present in the second array then it will be included in the resultant array." }, { "code": null, "e": 35024, "s": 35015, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> </head> <body> <script type=\"text/javascript\"> console.log(_.difference([undefined, '', \" \", null], [undefined, 4, null])); </script> </body></html> ", "e": 35415, "s": 35024, "text": null }, { "code": null, "e": 35423, "s": 35415, "text": "Output:" }, { "code": null, "e": 35748, "s": 35423, "text": "Passing a set of strings to the _.difference() function: Passing the set of strings which contains words inside “” then the _.difference() function will work in the same way. If any of the these string values are present in the first array but not present in the second array then it will be included in the resultant array." }, { "code": null, "e": 35757, "s": 35748, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> </head> <body> <script type=\"text/javascript\"> console.log(_.difference( [\"This\", \"is\", \"geeks\", \"for\", \"geeks2\"], [\"This\", \"for\", \"is\"]) ); </script> </body></html> ", "e": 36170, "s": 35757, "text": null }, { "code": null, "e": 36178, "s": 36170, "text": "Output:" }, { "code": null, "e": 36433, "s": 36178, "text": "Passing two arrays which have the same elements to the _.difference() function: Passing the first and the second array having the same elements then all the elements during the check operation will be ignored. And hence the resultant array will be empty." }, { "code": null, "e": 36442, "s": 36433, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> </head> <body> <script type=\"text/javascript\"> console.log(_.difference([1, 2, 3, 4], [1, 2, 3, 4])); </script> </body></html> ", "e": 36774, "s": 36442, "text": null }, { "code": null, "e": 36782, "s": 36774, "text": "Output:" }, { "code": null, "e": 36987, "s": 36782, "text": "Note: These commands will not work in Google console or in Firefox as for these additional files need to be added which they didn’t have added. So, add the given links to your HTML file and then run them." }, { "code": "<script type=\"text/javascript\" src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script> ", "e": 37115, "s": 36987, "text": null }, { "code": null, "e": 37142, "s": 37115, "text": "JavaScript - Underscore.js" }, { "code": null, "e": 37153, "s": 37142, "text": "JavaScript" }, { "code": null, "e": 37170, "s": 37153, "text": "Web Technologies" }, { "code": null, "e": 37268, "s": 37170, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37277, "s": 37268, "text": "Comments" }, { "code": null, "e": 37290, "s": 37277, "text": "Old Comments" }, { "code": null, "e": 37335, "s": 37290, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 37404, "s": 37335, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 37457, "s": 37404, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 37529, "s": 37457, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 37575, "s": 37529, "text": "Set the value of an input field in JavaScript" }, { "code": null, "e": 37612, "s": 37575, "text": "Express.js express.Router() Function" }, { "code": null, "e": 37645, "s": 37612, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 37690, "s": 37645, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 37748, "s": 37690, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Dynamic Programming on Trees | Set 2 - GeeksforGeeks
26 Jan, 2022 Given a tree with N nodes and N-1 edges, find out the maximum height of the tree when any node in the tree is considered as the root of the tree. The above diagram represents a tree with 11 nodes and 10 edges and the path that gives us the maximum height when node 1 is considered as a root. The maximum height is 3. In the above diagram, when 2 is considered as a root, then the longest path found is in RED color. A naive approach would be to traverse the tree using DFS traversal for every node and calculate the maximum height when the node is treated as the root of the tree. The time complexity for the DFS traversal of a tree is O(N). The overall time complexity of DFS for all N nodes will be O(N)*N i.e., O(N2). The above problem can be solved by using Dynamic Programming on Trees. To solve this problem, pre-calculate two things for every node. One will be the maximum height while traveling downwards via its branches to the leaves. While the other will be the maximum height when traveling upwards via its parent to any of the leaves. Optimal Substructure: When node i is considered as a root, in[i] be the maximum height of the tree when we travel downwards via its sub-trees and leaves.Also, out[i] be the maximum height of the tree while traveling upwards via its parent. The maximum height of a tree when node i is considered as a root will be max(in[i], out[i]). Calculation of in[i]: In the image above, values in[i] have been calculated for every node i. The maximum of every subtree is taken and added with 1 to the parent of that subtree. Add 1 for the edge between parent and subtree. Traverse the tree using DFS and calculate in[i] as max(in[i], 1+in[child]) for every node. Calculation of out[i]: The above diagram shows all the out[i] values and the path. For calculation of out[i], move upwards to the parent of node i. From the parent of node i, there are two ways to move in, one will be in all the branches of the parent. The other direction is to move to the parent(call it parent2 to avoid confusion) of the parent(call it parent1) of node i. The maximum height upwards via parent2 is out[parent1] itself. Generally, out[node i] as 1+max(out[i], 1+max of all branches). Add 1 for the edges between node and parent. The above diagram explains the calculation of out[i] when 2 is considered as the root of the tree. The branches of node 2 are not taken into count since the maximum height via that path has already been calculated and stored in i[2]. Moving up, in this case, the parent of 2, i.e., 1, has no parent. So, the branches except for the one which has the node are considered while calculating the maximum. The above diagram explains the calculation of out[10]. The parent of node 10, i.e., 7 has a parent and a branch(precisely a child in this case). So the maximum height of both has been taken to count in such cases when parent and branches exist. In case of multiple branches of a parent, take the longest of them to count(excluding the branch in which the node lies) Calculating the maximum height of all the branches connected to parent : in[i] stores the maximum height while moving downwards. No need to store all the lengths of branches. Only the first and second maximum length among all the branches will give the answer. Since the algorithm used is based on DFS, all the branches connected to the parent will be considered, including the branch which has the node. If the first maximum path thus obtained is the same as in[i], then maximum1 is the length of the branch in which node i lies. In this case, our longest path will be maximum2.Recurrence relation of in[i] and out[i]: in[i] = max(in[i], 1 + in[child]) out[i] = 1 + max(out[parent of i], 1 + longest path of all branches of parent of i) Below is the implementation of the above idea: C++ Java Python3 C# Javascript // C++ code to find the maximum path length// considering any node as root#include <bits/stdc++.h>using namespace std; vector<int> in,out; // function to pre-calculate the array in[]// which stores the maximum height when travelled// via branchesvoid dfs1(vector<int> v[], int u, int parent){ // initially every node has 0 height in[u] = 0; // traverse in the subtree of u for (int child : v[u]) { // if child is same as parent if (child == parent) continue; // dfs called dfs1(v, child, u); // recursively calculate the max height in[u] = max(in[u], 1 + in[child]); }} // function to pre-calculate the array ouut[]// which stores the maximum height when traveled// via parentvoid dfs2(vector<int> v[], int u, int parent){ // stores the longest and second // longest branches int mx1 = -1, mx2 = -1; // traverse in the subtress of u for (int child : v[u]) { if (child == parent) continue; // compare and store the longest // and second longest if (in[child] >= mx1) { mx2 = mx1; mx1 = in[child]; } else if (in[child] > mx2) mx2 = in[child]; } // traverse in the subtree of u for (int child : v[u]) { if (child == parent) continue; int longest = mx1; // if longest branch has the node, then // consider the second longest branch if (mx1 == in[child]) longest = mx2; // recursively calculate out[i] out[child] = 1 + max(out[u], 1 + longest); // dfs function call dfs2(v, child, u); }} // function to print all the maximum heights// from every nodevoid printHeights(vector<int> v[], int n){ // traversal to calculate in[] array dfs1(v, 1, 0); // traversal to calculate out[] array dfs2(v, 1, 0); // print all maximum heights for (int i = 1; i <= n; i++) cout << "The maximum height when node " << i << " is considered as root" << " is " << max(in[i], out[i]) << "\n";} // Driver Codeint main(){ int n = 11; vector<int> v[n + 1]; // initialize the tree given in the diagram v[1].push_back(2), v[2].push_back(1); v[1].push_back(3), v[3].push_back(1); v[1].push_back(4), v[4].push_back(1); v[2].push_back(5), v[5].push_back(2); v[2].push_back(6), v[6].push_back(2); v[3].push_back(7), v[7].push_back(3); v[7].push_back(10), v[10].push_back(7); v[7].push_back(11), v[11].push_back(7); v[4].push_back(8), v[8].push_back(4); v[4].push_back(9), v[9].push_back(4); // initialise in and out vectors in.resize(n+1,0); out.resize(n+1,0); // function to print the maximum height from every node printHeights(v, n); return 0;} // Java code to find the maximum path length// considering any node as rootimport java.io.*;import java.util.*; class GFG{ static final int MAX_NODES = 100;static int in[] = new int[MAX_NODES];static int out[] = new int[MAX_NODES]; // Function to pre-calculate the array in[]// which stores the maximum height when travelled// via branchesstatic void dfs1(ArrayList<ArrayList<Integer>> v, int u, int parent){ // Initially every node has 0 height in[u] = 0; // Traverse in the subtree of u for(int j = 0; j < v.get(u).size(); j++) { int child = v.get(u).get(j); // If child is same as parent if (child == parent) continue; // dfs called dfs1(v, child, u); // Recursively calculate the max height in[u] = Math.max(in[u], 1 + in[child]); }} // Function to pre-calculate the array ouut[]// which stores the maximum height when traveled// via parentstatic void dfs2(ArrayList<ArrayList<Integer>> v, int u, int parent){ // Stores the longest and second // longest branches int mx1 = -1, mx2 = -1; // Traverse in the subtress of u for(int j = 0; j < v.get(u).size(); j++) { int child = v.get(u).get(j); if (child == parent) continue; // Compare and store the longest // and second longest if (in[child] >= mx1) { mx2 = mx1; mx1 = in[child]; } else if (in[child] > mx2) mx2 = in[child]; } // Traverse in the subtree of u for(int j = 0; j < v.get(u).size(); j++) { int child = v.get(u).get(j); if (child == parent) continue; int longest = mx1; // If longest branch has the node, then // consider the second longest branch if (mx1 == in[child]) longest = mx2; // Recursively calculate out[i] out[child] = 1 + Math.max(out[u], 1 + longest); // dfs function call dfs2(v, child, u); }} static void addEdge(ArrayList<ArrayList<Integer>> adj, int u, int v){ adj.get(u).add(v); adj.get(v).add(u);} // Function to print all the maximum heights// from every nodestatic void printHeights(ArrayList<ArrayList<Integer>> v, int n){ // Traversal to calculate in[] array dfs1(v, 1, 0); // Traversal to calculate out[] array dfs2(v, 1, 0); // Print all maximum heights for(int i = 1; i < n; i++) System.out.println( "The maximum height when node " + i + " is considered as root is " + Math.max(in[i], out[i]));} // Driver Codepublic static void main(String[] args){ // Creating a graph with 11 vertices int V = 12; ArrayList<ArrayList< Integer>> adj = new ArrayList<ArrayList< Integer>>(V + 1); for(int i = 0; i < V; i++) adj.add(new ArrayList<Integer>()); // Initialize the tree given in the diagram addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 1, 4); addEdge(adj, 2, 5); addEdge(adj, 2, 6); addEdge(adj, 3, 7); addEdge(adj, 7, 10); addEdge(adj, 7, 11); addEdge(adj, 4, 8); addEdge(adj, 4, 9); // Function to print the maximum height // from every node printHeights(adj, V);}} // This code is contributed by decoding # Python3 code to find the maximum path length# considering any node as rootinn = [0] * 100out = [0] * 100 # function to pre-calculate the array inn[]# which stores the maximum height when travelled# via branchesdef dfs1(v, u, parent): global inn, out # initially every node has 0 height inn[u] = 0 # traverse in the subtree of u for child in v[u]: # if child is same as parent if (child == parent): continue # dfs called dfs1(v, child, u) # recursively calculate the max height inn[u] = max(inn[u], 1 + inn[child]) # function to pre-calculate the array ouut[]# which stores the maximum height when traveled# via parentdef dfs2(v, u, parent): global inn, out # stores the longest and second # longest branches mx1, mx2 = -1, -1 # traverse in the subtress of u for child in v[u]: if (child == parent): continue # compare and store the longest # and second longest if (inn[child] >= mx1): mx2 = mx1 mx1 = inn[child] elif (inn[child] > mx2): mx2 = inn[child] # traverse in the subtree of u for child in v[u]: if (child == parent): continue longest = mx1 # if longest branch has the node, then # consider the second longest branch if (mx1 == inn[child]): longest = mx2 # recursively calculate out[i] out[child] = 1 + max(out[u], 1 + longest) # dfs function call dfs2(v, child, u) # function to print all the maximum heights# from every nodedef printHeights(v, n): global inn, out # traversal to calculate inn[] array dfs1(v, 1, 0) # traversal to calculate out[] array dfs2(v, 1, 0) # print all maximum heights for i in range(1, n + 1): print("The maximum height when node", i, "is considered as root is", max(inn[i], out[i])) # Driver Codeif __name__ == '__main__': n = 11 v = [[] for i in range(n + 1)] # initialize the tree given in the diagram v[1].append(2) v[2].append(1) v[1].append(3) v[3].append(1) v[1].append(4) v[4].append(1) v[2].append(5) v[5].append(2) v[2].append(6) v[6].append(2) v[3].append(7) v[7].append(3) v[7].append(10) v[10].append(7) v[7].append(11) v[11].append(7) v[4].append(8) v[8].append(4) v[4].append(9) v[9].append(4) # function to print the maximum height from every node printHeights(v, n) # This code is contributed by mohit kumar 29. using System;using System.Collections.Generic; public class GFG{ static int MAX_NODES = 100;static int[] In = new int[MAX_NODES];static int[] Out = new int[MAX_NODES]; // Function to pre-calculate the array in[]// which stores the maximum height when travelled// via branchesstatic void dfs1(List<List<int>> v, int u, int parent){ // Initially every node has 0 height In[u] = 0; // Traverse in the subtree of u for(int j = 0; j < v[u].Count; j++) { int child = v[u][j]; // If child is same as parent if (child == parent) continue; // dfs called dfs1(v, child, u); // Recursively calculate the max height In[u] = Math.Max(In[u], 1 + In[child]); }} // Function to pre-calculate the array ouut[]// which stores the maximum height when traveled// via parentstatic void dfs2(List<List<int>> v, int u, int parent){ // Stores the longest and second // longest branches int mx1 = -1, mx2 = -1; // Traverse in the subtress of u for(int j = 0; j < v[u].Count; j++) { int child = v[u][j]; if (child == parent) continue; // Compare and store the longest // and second longest if (In[child] >= mx1) { mx2 = mx1; mx1 = In[child]; } else if (In[child] > mx2) mx2 = In[child]; } // Traverse in the subtree of u for(int j = 0; j < v[u].Count; j++) { int child = v[u][j]; if (child == parent) continue; int longest = mx1; // If longest branch has the node, then // consider the second longest branch if (mx1 == In[child]) longest = mx2; // Recursively calculate out[i] Out[child] = 1 + Math.Max(Out[u], 1 + longest); // dfs function call dfs2(v, child, u); }} static void addEdge(List<List<int>> adj, int u, int v){ adj[u].Add(v); adj[v].Add(u);} // Function to print all the maximum heights// from every nodestatic void printHeights(List<List<int>> v, int n){ // Traversal to calculate in[] array dfs1(v, 1, 0); // Traversal to calculate out[] array dfs2(v, 1, 0); // Print all maximum heights for(int i = 1; i < n; i++) Console.WriteLine( "The maximum height when node " + i + " is considered as root is " + Math.Max(In[i], Out[i]));} // Driver Code static public void Main (){ // Creating a graph with 11 vertices int V = 12; List<List<int>> adj = new List<List< int>>(); for(int i = 0; i < V; i++) adj.Add(new List<int>()); // Initialize the tree given in the diagram addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 1, 4); addEdge(adj, 2, 5); addEdge(adj, 2, 6); addEdge(adj, 3, 7); addEdge(adj, 7, 10); addEdge(adj, 7, 11); addEdge(adj, 4, 8); addEdge(adj, 4, 9); // Function to print the maximum height // from every node printHeights(adj, V); }} // This code is contributed by avanitrachhadiya2155 <script>// Javascript code to find the maximum path length// considering any node as root let MAX_NODES = 100; let In = new Array(MAX_NODES);let out=new Array(MAX_NODES);for(let i=0;i<MAX_NODES;i++){ In[i]=0; out[i]=0;}// Function to pre-calculate the array in[]// which stores the maximum height when travelled// via branchesfunction dfs1(v,u,parent){ // Initially every node has 0 height In[u] = 0; // Traverse in the subtree of u for(let j = 0; j < v[u].length; j++) { let child = v[u][j]; // If child is same as parent if (child == parent) continue; // dfs called dfs1(v, child, u); // Recursively calculate the max height In[u] = Math.max(In[u], 1 + In[child]); }} // Function to pre-calculate the array ouut[]// which stores the maximum height when traveled// via parentfunction dfs2(v,u,parent){ // Stores the longest and second // longest branches let mx1 = -1, mx2 = -1; // Traverse in the subtress of u for(let j = 0; j < v[u].length; j++) { let child = v[u][j]; if (child == parent) continue; // Compare and store the longest // and second longest if (In[child] >= mx1) { mx2 = mx1; mx1 = In[child]; } else if (In[child] > mx2) mx2 = In[child]; } // Traverse in the subtree of u for(let j = 0; j < v[u].length; j++) { let child = v[u][j]; if (child == parent) continue; let longest = mx1; // If longest branch has the node, then // consider the second longest branch if (mx1 == In[child]) longest = mx2; // Recursively calculate out[i] out[child] = 1 + Math.max(out[u], 1 + longest); // dfs function call dfs2(v, child, u); }} function addEdge(adj,u,v){ adj[u].push(v); adj[v].push(u);} // Function to print all the maximum heights// from every nodefunction printHeights(v,n){ // Traversal to calculate in[] array dfs1(v, 1, 0); // Traversal to calculate out[] array dfs2(v, 1, 0); // Print all maximum heights for(let i = 1; i < n; i++) document.write( "The maximum height when node " + i + " is considered as root is " + Math.max(In[i], out[i])+"<br>");} // Driver Code let V = 12;let adj = new Array(V+1);for(let i = 0; i <= V; i++) adj[i]=[]; // Initialize the tree given in the diagramaddEdge(adj, 1, 2);addEdge(adj, 1, 3);addEdge(adj, 1, 4);addEdge(adj, 2, 5);addEdge(adj, 2, 6);addEdge(adj, 3, 7);addEdge(adj, 7, 10);addEdge(adj, 7, 11);addEdge(adj, 4, 8);addEdge(adj, 4, 9); // Function to print the maximum height// from every nodeprintHeights(adj, V); // This code is contributed by patel2127</script> The maximum height when node 1 is considered as root is 3 The maximum height when node 2 is considered as root is 4 The maximum height when node 3 is considered as root is 3 The maximum height when node 4 is considered as root is 4 The maximum height when node 5 is considered as root is 5 The maximum height when node 6 is considered as root is 5 The maximum height when node 7 is considered as root is 4 The maximum height when node 8 is considered as root is 5 The maximum height when node 9 is considered as root is 5 The maximum height when node 10 is considered as root is 5 The maximum height when node 11 is considered as root is 5 Time Complexity : O(N) Auxiliary Space : O(N) deepaksati Akanksha_Rai pgmreddy mohit kumar 29 patel2127 nidhi_biet avanitrachhadiya2155 ashutoshsinghgeeksforgeeks adnanirshad158 Advanced Data Structure Algorithms Dynamic Programming Tree Dynamic Programming Tree Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Red-Black Tree | Set 2 (Insert) Disjoint Set Data Structures Ordered Set and GNU C++ PBDS Insert Operation in B-Tree Binary Indexed Tree or Fenwick Tree SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews DSA Sheet by Love Babbar Difference between BFS and DFS A* Search Algorithm
[ { "code": null, "e": 26249, "s": 26221, "text": "\n26 Jan, 2022" }, { "code": null, "e": 26396, "s": 26249, "text": "Given a tree with N nodes and N-1 edges, find out the maximum height of the tree when any node in the tree is considered as the root of the tree. " }, { "code": null, "e": 26569, "s": 26396, "text": "The above diagram represents a tree with 11 nodes and 10 edges and the path that gives us the maximum height when node 1 is considered as a root. The maximum height is 3. " }, { "code": null, "e": 26973, "s": 26569, "text": "In the above diagram, when 2 is considered as a root, then the longest path found is in RED color. A naive approach would be to traverse the tree using DFS traversal for every node and calculate the maximum height when the node is treated as the root of the tree. The time complexity for the DFS traversal of a tree is O(N). The overall time complexity of DFS for all N nodes will be O(N)*N i.e., O(N2)." }, { "code": null, "e": 27541, "s": 26973, "text": "The above problem can be solved by using Dynamic Programming on Trees. To solve this problem, pre-calculate two things for every node. One will be the maximum height while traveling downwards via its branches to the leaves. While the other will be the maximum height when traveling upwards via its parent to any of the leaves. Optimal Substructure: When node i is considered as a root, in[i] be the maximum height of the tree when we travel downwards via its sub-trees and leaves.Also, out[i] be the maximum height of the tree while traveling upwards via its parent. " }, { "code": null, "e": 27634, "s": 27541, "text": "The maximum height of a tree when node i is considered as a root will be max(in[i], out[i])." }, { "code": null, "e": 27658, "s": 27634, "text": "Calculation of in[i]: " }, { "code": null, "e": 27978, "s": 27658, "text": "In the image above, values in[i] have been calculated for every node i. The maximum of every subtree is taken and added with 1 to the parent of that subtree. Add 1 for the edge between parent and subtree. Traverse the tree using DFS and calculate in[i] as max(in[i], 1+in[child]) for every node. Calculation of out[i]: " }, { "code": null, "e": 28504, "s": 27978, "text": "The above diagram shows all the out[i] values and the path. For calculation of out[i], move upwards to the parent of node i. From the parent of node i, there are two ways to move in, one will be in all the branches of the parent. The other direction is to move to the parent(call it parent2 to avoid confusion) of the parent(call it parent1) of node i. The maximum height upwards via parent2 is out[parent1] itself. Generally, out[node i] as 1+max(out[i], 1+max of all branches). Add 1 for the edges between node and parent. " }, { "code": null, "e": 28905, "s": 28504, "text": "The above diagram explains the calculation of out[i] when 2 is considered as the root of the tree. The branches of node 2 are not taken into count since the maximum height via that path has already been calculated and stored in i[2]. Moving up, in this case, the parent of 2, i.e., 1, has no parent. So, the branches except for the one which has the node are considered while calculating the maximum." }, { "code": null, "e": 29893, "s": 28905, "text": "The above diagram explains the calculation of out[10]. The parent of node 10, i.e., 7 has a parent and a branch(precisely a child in this case). So the maximum height of both has been taken to count in such cases when parent and branches exist. In case of multiple branches of a parent, take the longest of them to count(excluding the branch in which the node lies) Calculating the maximum height of all the branches connected to parent : in[i] stores the maximum height while moving downwards. No need to store all the lengths of branches. Only the first and second maximum length among all the branches will give the answer. Since the algorithm used is based on DFS, all the branches connected to the parent will be considered, including the branch which has the node. If the first maximum path thus obtained is the same as in[i], then maximum1 is the length of the branch in which node i lies. In this case, our longest path will be maximum2.Recurrence relation of in[i] and out[i]: " }, { "code": null, "e": 30012, "s": 29893, "text": "in[i] = max(in[i], 1 + in[child]) out[i] = 1 + max(out[parent of i], 1 + longest path of all branches of parent of i) " }, { "code": null, "e": 30060, "s": 30012, "text": "Below is the implementation of the above idea: " }, { "code": null, "e": 30064, "s": 30060, "text": "C++" }, { "code": null, "e": 30069, "s": 30064, "text": "Java" }, { "code": null, "e": 30077, "s": 30069, "text": "Python3" }, { "code": null, "e": 30080, "s": 30077, "text": "C#" }, { "code": null, "e": 30091, "s": 30080, "text": "Javascript" }, { "code": "// C++ code to find the maximum path length// considering any node as root#include <bits/stdc++.h>using namespace std; vector<int> in,out; // function to pre-calculate the array in[]// which stores the maximum height when travelled// via branchesvoid dfs1(vector<int> v[], int u, int parent){ // initially every node has 0 height in[u] = 0; // traverse in the subtree of u for (int child : v[u]) { // if child is same as parent if (child == parent) continue; // dfs called dfs1(v, child, u); // recursively calculate the max height in[u] = max(in[u], 1 + in[child]); }} // function to pre-calculate the array ouut[]// which stores the maximum height when traveled// via parentvoid dfs2(vector<int> v[], int u, int parent){ // stores the longest and second // longest branches int mx1 = -1, mx2 = -1; // traverse in the subtress of u for (int child : v[u]) { if (child == parent) continue; // compare and store the longest // and second longest if (in[child] >= mx1) { mx2 = mx1; mx1 = in[child]; } else if (in[child] > mx2) mx2 = in[child]; } // traverse in the subtree of u for (int child : v[u]) { if (child == parent) continue; int longest = mx1; // if longest branch has the node, then // consider the second longest branch if (mx1 == in[child]) longest = mx2; // recursively calculate out[i] out[child] = 1 + max(out[u], 1 + longest); // dfs function call dfs2(v, child, u); }} // function to print all the maximum heights// from every nodevoid printHeights(vector<int> v[], int n){ // traversal to calculate in[] array dfs1(v, 1, 0); // traversal to calculate out[] array dfs2(v, 1, 0); // print all maximum heights for (int i = 1; i <= n; i++) cout << \"The maximum height when node \" << i << \" is considered as root\" << \" is \" << max(in[i], out[i]) << \"\\n\";} // Driver Codeint main(){ int n = 11; vector<int> v[n + 1]; // initialize the tree given in the diagram v[1].push_back(2), v[2].push_back(1); v[1].push_back(3), v[3].push_back(1); v[1].push_back(4), v[4].push_back(1); v[2].push_back(5), v[5].push_back(2); v[2].push_back(6), v[6].push_back(2); v[3].push_back(7), v[7].push_back(3); v[7].push_back(10), v[10].push_back(7); v[7].push_back(11), v[11].push_back(7); v[4].push_back(8), v[8].push_back(4); v[4].push_back(9), v[9].push_back(4); // initialise in and out vectors in.resize(n+1,0); out.resize(n+1,0); // function to print the maximum height from every node printHeights(v, n); return 0;}", "e": 32909, "s": 30091, "text": null }, { "code": "// Java code to find the maximum path length// considering any node as rootimport java.io.*;import java.util.*; class GFG{ static final int MAX_NODES = 100;static int in[] = new int[MAX_NODES];static int out[] = new int[MAX_NODES]; // Function to pre-calculate the array in[]// which stores the maximum height when travelled// via branchesstatic void dfs1(ArrayList<ArrayList<Integer>> v, int u, int parent){ // Initially every node has 0 height in[u] = 0; // Traverse in the subtree of u for(int j = 0; j < v.get(u).size(); j++) { int child = v.get(u).get(j); // If child is same as parent if (child == parent) continue; // dfs called dfs1(v, child, u); // Recursively calculate the max height in[u] = Math.max(in[u], 1 + in[child]); }} // Function to pre-calculate the array ouut[]// which stores the maximum height when traveled// via parentstatic void dfs2(ArrayList<ArrayList<Integer>> v, int u, int parent){ // Stores the longest and second // longest branches int mx1 = -1, mx2 = -1; // Traverse in the subtress of u for(int j = 0; j < v.get(u).size(); j++) { int child = v.get(u).get(j); if (child == parent) continue; // Compare and store the longest // and second longest if (in[child] >= mx1) { mx2 = mx1; mx1 = in[child]; } else if (in[child] > mx2) mx2 = in[child]; } // Traverse in the subtree of u for(int j = 0; j < v.get(u).size(); j++) { int child = v.get(u).get(j); if (child == parent) continue; int longest = mx1; // If longest branch has the node, then // consider the second longest branch if (mx1 == in[child]) longest = mx2; // Recursively calculate out[i] out[child] = 1 + Math.max(out[u], 1 + longest); // dfs function call dfs2(v, child, u); }} static void addEdge(ArrayList<ArrayList<Integer>> adj, int u, int v){ adj.get(u).add(v); adj.get(v).add(u);} // Function to print all the maximum heights// from every nodestatic void printHeights(ArrayList<ArrayList<Integer>> v, int n){ // Traversal to calculate in[] array dfs1(v, 1, 0); // Traversal to calculate out[] array dfs2(v, 1, 0); // Print all maximum heights for(int i = 1; i < n; i++) System.out.println( \"The maximum height when node \" + i + \" is considered as root is \" + Math.max(in[i], out[i]));} // Driver Codepublic static void main(String[] args){ // Creating a graph with 11 vertices int V = 12; ArrayList<ArrayList< Integer>> adj = new ArrayList<ArrayList< Integer>>(V + 1); for(int i = 0; i < V; i++) adj.add(new ArrayList<Integer>()); // Initialize the tree given in the diagram addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 1, 4); addEdge(adj, 2, 5); addEdge(adj, 2, 6); addEdge(adj, 3, 7); addEdge(adj, 7, 10); addEdge(adj, 7, 11); addEdge(adj, 4, 8); addEdge(adj, 4, 9); // Function to print the maximum height // from every node printHeights(adj, V);}} // This code is contributed by decoding", "e": 36299, "s": 32909, "text": null }, { "code": "# Python3 code to find the maximum path length# considering any node as rootinn = [0] * 100out = [0] * 100 # function to pre-calculate the array inn[]# which stores the maximum height when travelled# via branchesdef dfs1(v, u, parent): global inn, out # initially every node has 0 height inn[u] = 0 # traverse in the subtree of u for child in v[u]: # if child is same as parent if (child == parent): continue # dfs called dfs1(v, child, u) # recursively calculate the max height inn[u] = max(inn[u], 1 + inn[child]) # function to pre-calculate the array ouut[]# which stores the maximum height when traveled# via parentdef dfs2(v, u, parent): global inn, out # stores the longest and second # longest branches mx1, mx2 = -1, -1 # traverse in the subtress of u for child in v[u]: if (child == parent): continue # compare and store the longest # and second longest if (inn[child] >= mx1): mx2 = mx1 mx1 = inn[child] elif (inn[child] > mx2): mx2 = inn[child] # traverse in the subtree of u for child in v[u]: if (child == parent): continue longest = mx1 # if longest branch has the node, then # consider the second longest branch if (mx1 == inn[child]): longest = mx2 # recursively calculate out[i] out[child] = 1 + max(out[u], 1 + longest) # dfs function call dfs2(v, child, u) # function to print all the maximum heights# from every nodedef printHeights(v, n): global inn, out # traversal to calculate inn[] array dfs1(v, 1, 0) # traversal to calculate out[] array dfs2(v, 1, 0) # print all maximum heights for i in range(1, n + 1): print(\"The maximum height when node\", i, \"is considered as root is\", max(inn[i], out[i])) # Driver Codeif __name__ == '__main__': n = 11 v = [[] for i in range(n + 1)] # initialize the tree given in the diagram v[1].append(2) v[2].append(1) v[1].append(3) v[3].append(1) v[1].append(4) v[4].append(1) v[2].append(5) v[5].append(2) v[2].append(6) v[6].append(2) v[3].append(7) v[7].append(3) v[7].append(10) v[10].append(7) v[7].append(11) v[11].append(7) v[4].append(8) v[8].append(4) v[4].append(9) v[9].append(4) # function to print the maximum height from every node printHeights(v, n) # This code is contributed by mohit kumar 29.", "e": 38856, "s": 36299, "text": null }, { "code": "using System;using System.Collections.Generic; public class GFG{ static int MAX_NODES = 100;static int[] In = new int[MAX_NODES];static int[] Out = new int[MAX_NODES]; // Function to pre-calculate the array in[]// which stores the maximum height when travelled// via branchesstatic void dfs1(List<List<int>> v, int u, int parent){ // Initially every node has 0 height In[u] = 0; // Traverse in the subtree of u for(int j = 0; j < v[u].Count; j++) { int child = v[u][j]; // If child is same as parent if (child == parent) continue; // dfs called dfs1(v, child, u); // Recursively calculate the max height In[u] = Math.Max(In[u], 1 + In[child]); }} // Function to pre-calculate the array ouut[]// which stores the maximum height when traveled// via parentstatic void dfs2(List<List<int>> v, int u, int parent){ // Stores the longest and second // longest branches int mx1 = -1, mx2 = -1; // Traverse in the subtress of u for(int j = 0; j < v[u].Count; j++) { int child = v[u][j]; if (child == parent) continue; // Compare and store the longest // and second longest if (In[child] >= mx1) { mx2 = mx1; mx1 = In[child]; } else if (In[child] > mx2) mx2 = In[child]; } // Traverse in the subtree of u for(int j = 0; j < v[u].Count; j++) { int child = v[u][j]; if (child == parent) continue; int longest = mx1; // If longest branch has the node, then // consider the second longest branch if (mx1 == In[child]) longest = mx2; // Recursively calculate out[i] Out[child] = 1 + Math.Max(Out[u], 1 + longest); // dfs function call dfs2(v, child, u); }} static void addEdge(List<List<int>> adj, int u, int v){ adj[u].Add(v); adj[v].Add(u);} // Function to print all the maximum heights// from every nodestatic void printHeights(List<List<int>> v, int n){ // Traversal to calculate in[] array dfs1(v, 1, 0); // Traversal to calculate out[] array dfs2(v, 1, 0); // Print all maximum heights for(int i = 1; i < n; i++) Console.WriteLine( \"The maximum height when node \" + i + \" is considered as root is \" + Math.Max(In[i], Out[i]));} // Driver Code static public void Main (){ // Creating a graph with 11 vertices int V = 12; List<List<int>> adj = new List<List< int>>(); for(int i = 0; i < V; i++) adj.Add(new List<int>()); // Initialize the tree given in the diagram addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 1, 4); addEdge(adj, 2, 5); addEdge(adj, 2, 6); addEdge(adj, 3, 7); addEdge(adj, 7, 10); addEdge(adj, 7, 11); addEdge(adj, 4, 8); addEdge(adj, 4, 9); // Function to print the maximum height // from every node printHeights(adj, V); }} // This code is contributed by avanitrachhadiya2155", "e": 42084, "s": 38856, "text": null }, { "code": "<script>// Javascript code to find the maximum path length// considering any node as root let MAX_NODES = 100; let In = new Array(MAX_NODES);let out=new Array(MAX_NODES);for(let i=0;i<MAX_NODES;i++){ In[i]=0; out[i]=0;}// Function to pre-calculate the array in[]// which stores the maximum height when travelled// via branchesfunction dfs1(v,u,parent){ // Initially every node has 0 height In[u] = 0; // Traverse in the subtree of u for(let j = 0; j < v[u].length; j++) { let child = v[u][j]; // If child is same as parent if (child == parent) continue; // dfs called dfs1(v, child, u); // Recursively calculate the max height In[u] = Math.max(In[u], 1 + In[child]); }} // Function to pre-calculate the array ouut[]// which stores the maximum height when traveled// via parentfunction dfs2(v,u,parent){ // Stores the longest and second // longest branches let mx1 = -1, mx2 = -1; // Traverse in the subtress of u for(let j = 0; j < v[u].length; j++) { let child = v[u][j]; if (child == parent) continue; // Compare and store the longest // and second longest if (In[child] >= mx1) { mx2 = mx1; mx1 = In[child]; } else if (In[child] > mx2) mx2 = In[child]; } // Traverse in the subtree of u for(let j = 0; j < v[u].length; j++) { let child = v[u][j]; if (child == parent) continue; let longest = mx1; // If longest branch has the node, then // consider the second longest branch if (mx1 == In[child]) longest = mx2; // Recursively calculate out[i] out[child] = 1 + Math.max(out[u], 1 + longest); // dfs function call dfs2(v, child, u); }} function addEdge(adj,u,v){ adj[u].push(v); adj[v].push(u);} // Function to print all the maximum heights// from every nodefunction printHeights(v,n){ // Traversal to calculate in[] array dfs1(v, 1, 0); // Traversal to calculate out[] array dfs2(v, 1, 0); // Print all maximum heights for(let i = 1; i < n; i++) document.write( \"The maximum height when node \" + i + \" is considered as root is \" + Math.max(In[i], out[i])+\"<br>\");} // Driver Code let V = 12;let adj = new Array(V+1);for(let i = 0; i <= V; i++) adj[i]=[]; // Initialize the tree given in the diagramaddEdge(adj, 1, 2);addEdge(adj, 1, 3);addEdge(adj, 1, 4);addEdge(adj, 2, 5);addEdge(adj, 2, 6);addEdge(adj, 3, 7);addEdge(adj, 7, 10);addEdge(adj, 7, 11);addEdge(adj, 4, 8);addEdge(adj, 4, 9); // Function to print the maximum height// from every nodeprintHeights(adj, V); // This code is contributed by patel2127</script>", "e": 44943, "s": 42084, "text": null }, { "code": null, "e": 45586, "s": 44946, "text": "The maximum height when node 1 is considered as root is 3\nThe maximum height when node 2 is considered as root is 4\nThe maximum height when node 3 is considered as root is 3\nThe maximum height when node 4 is considered as root is 4\nThe maximum height when node 5 is considered as root is 5\nThe maximum height when node 6 is considered as root is 5\nThe maximum height when node 7 is considered as root is 4\nThe maximum height when node 8 is considered as root is 5\nThe maximum height when node 9 is considered as root is 5\nThe maximum height when node 10 is considered as root is 5\nThe maximum height when node 11 is considered as root is 5" }, { "code": null, "e": 45636, "s": 45590, "text": "Time Complexity : O(N) Auxiliary Space : O(N)" }, { "code": null, "e": 45649, "s": 45638, "text": "deepaksati" }, { "code": null, "e": 45662, "s": 45649, "text": "Akanksha_Rai" }, { "code": null, "e": 45671, "s": 45662, "text": "pgmreddy" }, { "code": null, "e": 45686, "s": 45671, "text": "mohit kumar 29" }, { "code": null, "e": 45696, "s": 45686, "text": "patel2127" }, { "code": null, "e": 45707, "s": 45696, "text": "nidhi_biet" }, { "code": null, "e": 45728, "s": 45707, "text": "avanitrachhadiya2155" }, { "code": null, "e": 45755, "s": 45728, "text": "ashutoshsinghgeeksforgeeks" }, { "code": null, "e": 45770, "s": 45755, "text": "adnanirshad158" }, { "code": null, "e": 45794, "s": 45770, "text": "Advanced Data Structure" }, { "code": null, "e": 45805, "s": 45794, "text": "Algorithms" }, { "code": null, "e": 45825, "s": 45805, "text": "Dynamic Programming" }, { "code": null, "e": 45830, "s": 45825, "text": "Tree" }, { "code": null, "e": 45850, "s": 45830, "text": "Dynamic Programming" }, { "code": null, "e": 45855, "s": 45850, "text": "Tree" }, { "code": null, "e": 45866, "s": 45855, "text": "Algorithms" }, { "code": null, "e": 45964, "s": 45866, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45996, "s": 45964, "text": "Red-Black Tree | Set 2 (Insert)" }, { "code": null, "e": 46025, "s": 45996, "text": "Disjoint Set Data Structures" }, { "code": null, "e": 46054, "s": 46025, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 46081, "s": 46054, "text": "Insert Operation in B-Tree" }, { "code": null, "e": 46117, "s": 46081, "text": "Binary Indexed Tree or Fenwick Tree" }, { "code": null, "e": 46166, "s": 46117, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 46210, "s": 46166, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 46235, "s": 46210, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 46266, "s": 46235, "text": "Difference between BFS and DFS" } ]
Basics of Image Classification in Machine Learning Using Open Source Frameworks in IBM PowerAI (Part 2) | by Upendra Rajan | Towards Data Science
Image classification has become one of the key pilot use cases for demonstrating machine learning. In the previous article, I introduced machine learning, IBM PowerAI, compared GPU and CPU performances while running image classification programs on the IBM Power platform. In this article, let’s take a look at how to check the output at any inner layer of a neural network and train your own model by working with Nvidia DIGITS. It wasn’t till the 1980s that researchers discovered adding more layers to a neural network vastly improved its performance. Such neural networks with several hidden layers are common today in several use cases including image classification. Contrary to what the name indicates, it is possible to observe relevant parameters in the hidden layers. As you probably know by now, convolutional neural networks (CNNs) are a type of deep neural networks and produce fairly accurate results when used for image classification. When studying Digital Signal Processing in engineering school, you are bound to come across the term convolution. Simply put, the convolution of two signals is the integration of the product of the two signal functions, after one of the functions is reversed and shifted. In our case, every input image is a matrix of pixel values. To see a visual representation of how convolution is performed in the hidden layers, consider this example. In this example, the orange matrix (3x3) is called the Filter and is used to compute a convoluted output of the original image (5X5 matrix of pixels). The result is called the Activation Map or Feature Map. It is to be understood that depending on the Filter applied, the output Feature Map can be modified and trained to get the desired output. In modern CNNs, the Filter is learned automatically during the training process, but we do specify certain parameters (shown below) depending on the architecture being used. Please head to this blog if you need a more detailed analysis. In our case, a version of AlexNet is used and that’s the standard architecture we rely on. In the code below, we read the structure of the net. The CNN contains two ordered dictionaries; a) Net.blobs for input data; a. This has the following parameters – batch size, channel dimension, height and width b) Net.params is a vector of blobs for having weight and bias parameters; a. Weight indicates the strength of a connection. Weights near zero indicate a good correlation between the input and the ouput. b. Bias indicates how far off the predictions may be from the real values and is very important in moving the predictions along to the next step. c. This has the following parameters – output channels, input channels, filter height and filter width for the weights and a one-dimentional output channel for the biases. Let’s attempt to print these. # for each layer, show the output shapefor layer_name, blob in net.blobs.iteritems():print layer_name + ‘\t’ + str(blob.data.shape) Here is the output. data (50, 3, 227, 227)conv1 (50, 96, 55, 55)pool1 (50, 96, 27, 27)norm1 (50, 96, 27, 27)conv2 (50, 256, 27, 27)pool2 (50, 256, 13, 13)norm2 (50, 256, 13, 13)conv3 (50, 384, 13, 13)conv4 (50, 384, 13, 13)conv5 (50, 256, 13, 13)pool5 (50, 256, 6, 6)fc6 (50, 4096)fc7 (50, 4096)fc8 (50, 1000)prob (50, 1000) And; for layer_name, param in net.params.iteritems():print layer_name + ‘\t’ + str(param[0].data.shape), str(param[1].data.shape) Here is the output. conv1 (96, 3, 11, 11) (96,)conv2 (256, 48, 5, 5) (256,)conv3 (384, 256, 3, 3) (384,)conv4 (384, 192, 3, 3) (384,)conv5 (256, 192, 3, 3) (256,)fc6 (4096, 9216) (4096,)fc7 (4096, 4096) (4096,)fc8 (1000, 4096) (1000,) As you see, we have four dimensional data here. Here is a function to visualize this data; def vis_square(data):“””Take an array of shape (n, height, width) or (n, height, width, 3) and visualize each (height, width) thing in a grid of size approx. sqrt(n) by sqrt(n)””” # normalize data for display data = (data — data.min()) / (data.max() — data.min()) # force the number of filters to be square n = int(np.ceil(np.sqrt(data.shape[0]))) padding = (((0, n ** 2 — data.shape[0]), (0, 1), (0, 1)) # add some space between filters + ((0, 0),) * (data.ndim — 3)) # don’t pad the last dimension (if there is one) data = np.pad(data, padding, mode=’constant’, constant_values=1) # pad with ones (white) # tile the filters into an image data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1))) data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:]) plt.imshow(data); plt.axis(‘off’) Here, you can see the filters in the layer conv1; # the parameters are a list of [weights, biases]filters = net.params[‘conv1’][0].datavis_square(filters.transpose(0, 2, 3, 1)) Here, we see rectified responses of the filters above for the first 36; feat = net.blobs[‘conv1’].data[0, :36]vis_square(feat) Here, we see the output of the fifth layer, after pooling has been done; feat = net.blobs[‘pool5’].data[0]vis_square(feat) The first fully connected layer was ‘fc6’ which is a rectified output. The histogram of all non-negative values is displayed using this code; feat = net.blobs[‘fc6’].data[0]plt.subplot(2, 1, 1)plt.plot(feat.flat)plt.subplot(2, 1, 2)_ = plt.hist(feat.flat[feat.flat > 0], bins=100) Here, we see the histogram of the final probability values of all predicted classes. The top peak here shows the top predicted class, in our case, orangutan. Other minor cluster peaks are also shown. feat = net.blobs[‘prob’].data[0]plt.figure(figsize=(15, 3))plt.plot(feat.flat)[<matplotlib.lines.Line2D at 0x7f09587dfb50>] What is Nvidia DIGITS? Nvidia Deep Learning GPU Training System (DIGITS) is an application that is used to classify images, perform segmentation and object detection tasks. It is a GUI based application that interfaces with Caffe. The download and installation procedure can be found on their website. Stable and other beta versions are also available on Github. DIGITS server is installed in the container that I am using for this demo. Once installed, the GUI can be accessed from port 5000. The next step is to download a sample dataset from the web to a directory I created (/DIGITS) in my VM. This dataset is called CIFAR-100. It contains 100 classes of images and each class contains 600 images. There are 500 training images and 100 testing images per class. The 100 classes in the CIFAR-100 are grouped into 20 super-classes. Each image comes with a “fine” label (the class to which it belongs) and a “coarse” label (the super-class to which it belongs). Here’s a brief explanation of what it contains; 1) Labels.txt: This file contains a list of classes in the training data set. 2) Train: This directory contains the images used for training. 3) Train.txt: This file contains a list of mappings between training files to the classes. The labels are positional, i.e. the first label from the labels.txt file is represented by the number 0, the second by number 1 etc. 4) Test: This directory contains the images used for testing the training quality. 5) Test.txt: This file contains a list of mappings between the test files and the classes. The labels are positional, i.e. the first label from the labels.txt file is represented by the number 0, the second by number 1 etc. root@JARVICENAE-0A0A1841:~/DIGITS# python -m digits.download_data cifar100 . The output; Downloading url=http://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz ...Uncompressing file=cifar-100-python.tar.gz ...Extracting images file=./cifar-100-python/train ...Extracting images file=./cifar-100-python/test ...Dataset directory is created successfully at ‘.’Done after 65.3251469135 seconds. Let’s take a look at the downloaded data set. Although I am not showing the other directories I listed above, assume that they are downloaded and present. root@JARVICENAE-0A0A1841:~/DIGITS# ls fine/train | headappleaquarium_fishbabybearbeaverbedbeebeetlebicyclebottle Let’s create a new classification dataset with the pre-trained dataset (CIFAR-100) that we downloaded. Here, the path /root/DIGITS/fine/train is the path to our dataset. Also notice the ‘Separate test images folder’ option and specify the /root/DIGITS/fine/test directory. You can also specify a name for this dataset, like ‘Cifar100’ for example (not shown in the screenshot above). When you click on Create, a new job to create the training database is started as shown below. The status of the jobs involved are shown on the right hand side pane in the image above. Once done, your DIGITS home screen should now show this dataset as being available to use. Let’s create a new image classification model with the name ‘Classify Images’ with the CIFAR-100 dataset we created. We’ll use a pre-built AlexNet neural network architecture for this model. Once you click on Create, a new job is started as before. The status of the job called ‘Train Caffe Model’ is shown in the screenshot below. As the training proceeds, the job status will be updated in a graph as shown below. Over time, I was able to see an increase in accuracy. After a while, when the job completes, you will be able to upload a test image and classify it based on your model. An example image (of a green apple) is being uploaded and the results are seen instantly. This is fairly good accuracy with a small dataset like CIFAR-100, and you can expect better accuracy values when larger datasets are used. I wish to write a shorter part 3 to show the benefits of Torch. Time will tell. If you’ve enjoyed this piece, go ahead, give it a clap 👏🏻 (you can clap more than once)! You can also share it somewhere online so others can read it too. The postings on this site are my own and don’t necessarily represent IBM’s positions, strategies or opinions. Author: Upendra Rajan
[ { "code": null, "e": 602, "s": 172, "text": "Image classification has become one of the key pilot use cases for demonstrating machine learning. In the previous article, I introduced machine learning, IBM PowerAI, compared GPU and CPU performances while running image classification programs on the IBM Power platform. In this article, let’s take a look at how to check the output at any inner layer of a neural network and train your own model by working with Nvidia DIGITS." }, { "code": null, "e": 950, "s": 602, "text": "It wasn’t till the 1980s that researchers discovered adding more layers to a neural network vastly improved its performance. Such neural networks with several hidden layers are common today in several use cases including image classification. Contrary to what the name indicates, it is possible to observe relevant parameters in the hidden layers." }, { "code": null, "e": 1563, "s": 950, "text": "As you probably know by now, convolutional neural networks (CNNs) are a type of deep neural networks and produce fairly accurate results when used for image classification. When studying Digital Signal Processing in engineering school, you are bound to come across the term convolution. Simply put, the convolution of two signals is the integration of the product of the two signal functions, after one of the functions is reversed and shifted. In our case, every input image is a matrix of pixel values. To see a visual representation of how convolution is performed in the hidden layers, consider this example." }, { "code": null, "e": 1909, "s": 1563, "text": "In this example, the orange matrix (3x3) is called the Filter and is used to compute a convoluted output of the original image (5X5 matrix of pixels). The result is called the Activation Map or Feature Map. It is to be understood that depending on the Filter applied, the output Feature Map can be modified and trained to get the desired output." }, { "code": null, "e": 2146, "s": 1909, "text": "In modern CNNs, the Filter is learned automatically during the training process, but we do specify certain parameters (shown below) depending on the architecture being used. Please head to this blog if you need a more detailed analysis." }, { "code": null, "e": 2333, "s": 2146, "text": "In our case, a version of AlexNet is used and that’s the standard architecture we rely on. In the code below, we read the structure of the net. The CNN contains two ordered dictionaries;" }, { "code": null, "e": 2362, "s": 2333, "text": "a) Net.blobs for input data;" }, { "code": null, "e": 2449, "s": 2362, "text": "a. This has the following parameters – batch size, channel dimension, height and width" }, { "code": null, "e": 2523, "s": 2449, "text": "b) Net.params is a vector of blobs for having weight and bias parameters;" }, { "code": null, "e": 2652, "s": 2523, "text": "a. Weight indicates the strength of a connection. Weights near zero indicate a good correlation between the input and the ouput." }, { "code": null, "e": 2798, "s": 2652, "text": "b. Bias indicates how far off the predictions may be from the real values and is very important in moving the predictions along to the next step." }, { "code": null, "e": 2970, "s": 2798, "text": "c. This has the following parameters – output channels, input channels, filter height and filter width for the weights and a one-dimentional output channel for the biases." }, { "code": null, "e": 3000, "s": 2970, "text": "Let’s attempt to print these." }, { "code": null, "e": 3132, "s": 3000, "text": "# for each layer, show the output shapefor layer_name, blob in net.blobs.iteritems():print layer_name + ‘\\t’ + str(blob.data.shape)" }, { "code": null, "e": 3152, "s": 3132, "text": "Here is the output." }, { "code": null, "e": 3457, "s": 3152, "text": "data (50, 3, 227, 227)conv1 (50, 96, 55, 55)pool1 (50, 96, 27, 27)norm1 (50, 96, 27, 27)conv2 (50, 256, 27, 27)pool2 (50, 256, 13, 13)norm2 (50, 256, 13, 13)conv3 (50, 384, 13, 13)conv4 (50, 384, 13, 13)conv5 (50, 256, 13, 13)pool5 (50, 256, 6, 6)fc6 (50, 4096)fc7 (50, 4096)fc8 (50, 1000)prob (50, 1000)" }, { "code": null, "e": 3462, "s": 3457, "text": "And;" }, { "code": null, "e": 3587, "s": 3462, "text": "for layer_name, param in net.params.iteritems():print layer_name + ‘\\t’ + str(param[0].data.shape), str(param[1].data.shape)" }, { "code": null, "e": 3607, "s": 3587, "text": "Here is the output." }, { "code": null, "e": 3822, "s": 3607, "text": "conv1 (96, 3, 11, 11) (96,)conv2 (256, 48, 5, 5) (256,)conv3 (384, 256, 3, 3) (384,)conv4 (384, 192, 3, 3) (384,)conv5 (256, 192, 3, 3) (256,)fc6 (4096, 9216) (4096,)fc7 (4096, 4096) (4096,)fc8 (1000, 4096) (1000,)" }, { "code": null, "e": 3913, "s": 3822, "text": "As you see, we have four dimensional data here. Here is a function to visualize this data;" }, { "code": null, "e": 4771, "s": 3913, "text": "def vis_square(data):“””Take an array of shape (n, height, width) or (n, height, width, 3) and visualize each (height, width) thing in a grid of size approx. sqrt(n) by sqrt(n)””” # normalize data for display data = (data — data.min()) / (data.max() — data.min()) # force the number of filters to be square n = int(np.ceil(np.sqrt(data.shape[0]))) padding = (((0, n ** 2 — data.shape[0]), (0, 1), (0, 1)) # add some space between filters + ((0, 0),) * (data.ndim — 3)) # don’t pad the last dimension (if there is one) data = np.pad(data, padding, mode=’constant’, constant_values=1) # pad with ones (white) # tile the filters into an image data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1))) data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:]) plt.imshow(data); plt.axis(‘off’)" }, { "code": null, "e": 4821, "s": 4771, "text": "Here, you can see the filters in the layer conv1;" }, { "code": null, "e": 4948, "s": 4821, "text": "# the parameters are a list of [weights, biases]filters = net.params[‘conv1’][0].datavis_square(filters.transpose(0, 2, 3, 1))" }, { "code": null, "e": 5020, "s": 4948, "text": "Here, we see rectified responses of the filters above for the first 36;" }, { "code": null, "e": 5075, "s": 5020, "text": "feat = net.blobs[‘conv1’].data[0, :36]vis_square(feat)" }, { "code": null, "e": 5148, "s": 5075, "text": "Here, we see the output of the fifth layer, after pooling has been done;" }, { "code": null, "e": 5198, "s": 5148, "text": "feat = net.blobs[‘pool5’].data[0]vis_square(feat)" }, { "code": null, "e": 5340, "s": 5198, "text": "The first fully connected layer was ‘fc6’ which is a rectified output. The histogram of all non-negative values is displayed using this code;" }, { "code": null, "e": 5479, "s": 5340, "text": "feat = net.blobs[‘fc6’].data[0]plt.subplot(2, 1, 1)plt.plot(feat.flat)plt.subplot(2, 1, 2)_ = plt.hist(feat.flat[feat.flat > 0], bins=100)" }, { "code": null, "e": 5679, "s": 5479, "text": "Here, we see the histogram of the final probability values of all predicted classes. The top peak here shows the top predicted class, in our case, orangutan. Other minor cluster peaks are also shown." }, { "code": null, "e": 5803, "s": 5679, "text": "feat = net.blobs[‘prob’].data[0]plt.figure(figsize=(15, 3))plt.plot(feat.flat)[<matplotlib.lines.Line2D at 0x7f09587dfb50>]" }, { "code": null, "e": 5826, "s": 5803, "text": "What is Nvidia DIGITS?" }, { "code": null, "e": 6297, "s": 5826, "text": "Nvidia Deep Learning GPU Training System (DIGITS) is an application that is used to classify images, perform segmentation and object detection tasks. It is a GUI based application that interfaces with Caffe. The download and installation procedure can be found on their website. Stable and other beta versions are also available on Github. DIGITS server is installed in the container that I am using for this demo. Once installed, the GUI can be accessed from port 5000." }, { "code": null, "e": 6766, "s": 6297, "text": "The next step is to download a sample dataset from the web to a directory I created (/DIGITS) in my VM. This dataset is called CIFAR-100. It contains 100 classes of images and each class contains 600 images. There are 500 training images and 100 testing images per class. The 100 classes in the CIFAR-100 are grouped into 20 super-classes. Each image comes with a “fine” label (the class to which it belongs) and a “coarse” label (the super-class to which it belongs)." }, { "code": null, "e": 6814, "s": 6766, "text": "Here’s a brief explanation of what it contains;" }, { "code": null, "e": 6892, "s": 6814, "text": "1) Labels.txt: This file contains a list of classes in the training data set." }, { "code": null, "e": 6956, "s": 6892, "text": "2) Train: This directory contains the images used for training." }, { "code": null, "e": 7180, "s": 6956, "text": "3) Train.txt: This file contains a list of mappings between training files to the classes. The labels are positional, i.e. the first label from the labels.txt file is represented by the number 0, the second by number 1 etc." }, { "code": null, "e": 7263, "s": 7180, "text": "4) Test: This directory contains the images used for testing the training quality." }, { "code": null, "e": 7487, "s": 7263, "text": "5) Test.txt: This file contains a list of mappings between the test files and the classes. The labels are positional, i.e. the first label from the labels.txt file is represented by the number 0, the second by number 1 etc." }, { "code": null, "e": 7564, "s": 7487, "text": "root@JARVICENAE-0A0A1841:~/DIGITS# python -m digits.download_data cifar100 ." }, { "code": null, "e": 7576, "s": 7564, "text": "The output;" }, { "code": null, "e": 7880, "s": 7576, "text": "Downloading url=http://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz ...Uncompressing file=cifar-100-python.tar.gz ...Extracting images file=./cifar-100-python/train ...Extracting images file=./cifar-100-python/test ...Dataset directory is created successfully at ‘.’Done after 65.3251469135 seconds." }, { "code": null, "e": 8035, "s": 7880, "text": "Let’s take a look at the downloaded data set. Although I am not showing the other directories I listed above, assume that they are downloaded and present." }, { "code": null, "e": 8148, "s": 8035, "text": "root@JARVICENAE-0A0A1841:~/DIGITS# ls fine/train | headappleaquarium_fishbabybearbeaverbedbeebeetlebicyclebottle" }, { "code": null, "e": 8251, "s": 8148, "text": "Let’s create a new classification dataset with the pre-trained dataset (CIFAR-100) that we downloaded." }, { "code": null, "e": 8532, "s": 8251, "text": "Here, the path /root/DIGITS/fine/train is the path to our dataset. Also notice the ‘Separate test images folder’ option and specify the /root/DIGITS/fine/test directory. You can also specify a name for this dataset, like ‘Cifar100’ for example (not shown in the screenshot above)." }, { "code": null, "e": 8627, "s": 8532, "text": "When you click on Create, a new job to create the training database is started as shown below." }, { "code": null, "e": 8808, "s": 8627, "text": "The status of the jobs involved are shown on the right hand side pane in the image above. Once done, your DIGITS home screen should now show this dataset as being available to use." }, { "code": null, "e": 8999, "s": 8808, "text": "Let’s create a new image classification model with the name ‘Classify Images’ with the CIFAR-100 dataset we created. We’ll use a pre-built AlexNet neural network architecture for this model." }, { "code": null, "e": 9140, "s": 8999, "text": "Once you click on Create, a new job is started as before. The status of the job called ‘Train Caffe Model’ is shown in the screenshot below." }, { "code": null, "e": 9278, "s": 9140, "text": "As the training proceeds, the job status will be updated in a graph as shown below. Over time, I was able to see an increase in accuracy." }, { "code": null, "e": 9484, "s": 9278, "text": "After a while, when the job completes, you will be able to upload a test image and classify it based on your model. An example image (of a green apple) is being uploaded and the results are seen instantly." }, { "code": null, "e": 9623, "s": 9484, "text": "This is fairly good accuracy with a small dataset like CIFAR-100, and you can expect better accuracy values when larger datasets are used." }, { "code": null, "e": 9703, "s": 9623, "text": "I wish to write a shorter part 3 to show the benefits of Torch. Time will tell." }, { "code": null, "e": 9858, "s": 9703, "text": "If you’ve enjoyed this piece, go ahead, give it a clap 👏🏻 (you can clap more than once)! You can also share it somewhere online so others can read it too." }, { "code": null, "e": 9968, "s": 9858, "text": "The postings on this site are my own and don’t necessarily represent IBM’s positions, strategies or opinions." } ]
DAX Filter - ADDMISSINGITEMS function
Adds combinations of items from multiple columns to a table if they do not already exist. The determination of which item combinations to add is based on referencing source columns which contain all the possible values for the columns. DAX ADDMISSINGITEMS function is new in Excel 2016. ADDMISSINGITEMS (<showAllColumn>, [<showAllColumn>] ..., <table>, <groupingColumn>, [<groupingColumn>] ..., [<filterTable>] ...) ADDMISSINGITEMS (<showAllColumn>, [<showAllColumn>] ..., <table>, [ROLLUPISSUBTOTAL (<groupingColumn>, <isSubtotal_columnName>, [<groupingColumn>, [<isSubtotal_columnName>]] ...)], [<filterTable>] ...) showAllColumn A column for which to return items with no data for the calculated fields used. table A table containing all items with data (NON EMPTY) for the calculated fields used. groupingColumn A column which is used to group by in the supplied table argument. isSubtotal_columnName A Boolean column in the supplied table argument which contains ISSUBTOTAL values for the corresponding groupingColumn column. filterTable A table representing filters to include in the logic for determining whether to add specific combinations of items with no data. Used to avoid having ADDMISSINGITEMS add in item combinations which are not present because they were removed by a filter. To determine the combinations of items from different columns to evaluate − AutoExist is applied for columns within the same table. CrossJoin is applied across different tables. ROLLUPGROUP is used inside the ROLLUPISSUBTOTAL function to reflect ROLLUPGROUPs present in the supplied table argument. If ROLLUPISSUBTOTAL is used to define the supplied table argument or the equivalent rows and ISSUBTOTAL columns are added by some other means, ROLLUPISSUBTOTAL must be used with the same arguments within ADDMISSINGITEMS. This is also true for ROLLUPGROUP, if it is used with ROLLUPISSUBTOTAL to define the supplied table argument. If ROLLUPISSUBTOTAL is used to define the supplied table argument or the equivalent rows and ISSUBTOTAL columns are added by some other means, ROLLUPISSUBTOTAL must be used with the same arguments within ADDMISSINGITEMS. This is also true for ROLLUPGROUP, if it is used with ROLLUPISSUBTOTAL to define the supplied table argument. The ADDMISSINGITEMS function requires that, if ROLLUPISSUBTOTAL is used to define the supplied table argument, ISSUBTOTAL columns corresponding to each group by column, or ROLLUPGROUP are present in the supplied table argument. Also, the names of the ISSUBTOTAL columns must be supplied in the ROLLUPISSUBTOTAL function inside ADDMISSINGITEMS and they must match the names of Boolean columns in the supplied table argument. This enables the ADDMISSINGITEMS function to identify BLANK values stemming from the fact that a row is a subtotal row from other BLANK values. The ADDMISSINGITEMS function requires that, if ROLLUPISSUBTOTAL is used to define the supplied table argument, ISSUBTOTAL columns corresponding to each group by column, or ROLLUPGROUP are present in the supplied table argument. Also, the names of the ISSUBTOTAL columns must be supplied in the ROLLUPISSUBTOTAL function inside ADDMISSINGITEMS and they must match the names of Boolean columns in the supplied table argument. This enables the ADDMISSINGITEMS function to identify BLANK values stemming from the fact that a row is a subtotal row from other BLANK values. If ROLLUPGROUP is used with ROLLUPISSUBTOTAL to define the supplied table argument, exactly one ISSUBTOTAL column name must be supplied per ROLLUPGROUP and it must match the corresponding ISSUBTOTAL column name in the supplied table argument. If ROLLUPGROUP is used with ROLLUPISSUBTOTAL to define the supplied table argument, exactly one ISSUBTOTAL column name must be supplied per ROLLUPGROUP and it must match the corresponding ISSUBTOTAL column name in the supplied table argument. The ADDMISSINGITEMS function will return BLANK values for the IsSubtotal columns of blank rows it adds. = ADDMISSINGITEMS (Products, FILTER (Products,Products[Product]="Air Purifier")) 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2237, "s": 2001, "text": "Adds combinations of items from multiple columns to a table if they do not already exist. The determination of which item combinations to add is based on referencing source columns which contain all the possible values for the columns." }, { "code": null, "e": 2288, "s": 2237, "text": "DAX ADDMISSINGITEMS function is new in Excel 2016." }, { "code": null, "e": 2635, "s": 2288, "text": "ADDMISSINGITEMS (<showAllColumn>, [<showAllColumn>] ..., \n <table>, <groupingColumn>, [<groupingColumn>] ..., [<filterTable>] ...) \n\nADDMISSINGITEMS (<showAllColumn>, [<showAllColumn>] ..., \n <table>, [ROLLUPISSUBTOTAL (<groupingColumn>, <isSubtotal_columnName>, \n [<groupingColumn>, [<isSubtotal_columnName>]] ...)], [<filterTable>] ...) \n" }, { "code": null, "e": 2649, "s": 2635, "text": "showAllColumn" }, { "code": null, "e": 2729, "s": 2649, "text": "A column for which to return items with no data for the calculated fields used." }, { "code": null, "e": 2735, "s": 2729, "text": "table" }, { "code": null, "e": 2818, "s": 2735, "text": "A table containing all items with data (NON EMPTY) for the calculated fields used." }, { "code": null, "e": 2833, "s": 2818, "text": "groupingColumn" }, { "code": null, "e": 2900, "s": 2833, "text": "A column which is used to group by in the supplied table argument." }, { "code": null, "e": 2922, "s": 2900, "text": "isSubtotal_columnName" }, { "code": null, "e": 3048, "s": 2922, "text": "A Boolean column in the supplied table argument which contains ISSUBTOTAL values for the corresponding groupingColumn column." }, { "code": null, "e": 3060, "s": 3048, "text": "filterTable" }, { "code": null, "e": 3312, "s": 3060, "text": "A table representing filters to include in the logic for determining whether to add specific combinations of items with no data. Used to avoid having ADDMISSINGITEMS add in item combinations which are not present because they were removed by a filter." }, { "code": null, "e": 3388, "s": 3312, "text": "To determine the combinations of items from different columns to evaluate −" }, { "code": null, "e": 3444, "s": 3388, "text": "AutoExist is applied for columns within the same table." }, { "code": null, "e": 3490, "s": 3444, "text": "CrossJoin is applied across different tables." }, { "code": null, "e": 3611, "s": 3490, "text": "ROLLUPGROUP is used inside the ROLLUPISSUBTOTAL function to reflect ROLLUPGROUPs present in the supplied table argument." }, { "code": null, "e": 3942, "s": 3611, "text": "If ROLLUPISSUBTOTAL is used to define the supplied table argument or the equivalent rows and ISSUBTOTAL columns are added by some other means, ROLLUPISSUBTOTAL must be used with the same arguments within ADDMISSINGITEMS. This is also true for ROLLUPGROUP, if it is used with ROLLUPISSUBTOTAL to define the supplied table argument." }, { "code": null, "e": 4273, "s": 3942, "text": "If ROLLUPISSUBTOTAL is used to define the supplied table argument or the equivalent rows and ISSUBTOTAL columns are added by some other means, ROLLUPISSUBTOTAL must be used with the same arguments within ADDMISSINGITEMS. This is also true for ROLLUPGROUP, if it is used with ROLLUPISSUBTOTAL to define the supplied table argument." }, { "code": null, "e": 4841, "s": 4273, "text": "The ADDMISSINGITEMS function requires that, if ROLLUPISSUBTOTAL is used to define the supplied table argument, ISSUBTOTAL columns corresponding to each group by column, or ROLLUPGROUP are present in the supplied table argument. Also, the names of the ISSUBTOTAL columns must be supplied in the ROLLUPISSUBTOTAL function inside ADDMISSINGITEMS and they must match the names of Boolean columns in the supplied table argument. This enables the ADDMISSINGITEMS function to identify BLANK values stemming from the fact that a row is a subtotal row from other BLANK values." }, { "code": null, "e": 5409, "s": 4841, "text": "The ADDMISSINGITEMS function requires that, if ROLLUPISSUBTOTAL is used to define the supplied table argument, ISSUBTOTAL columns corresponding to each group by column, or ROLLUPGROUP are present in the supplied table argument. Also, the names of the ISSUBTOTAL columns must be supplied in the ROLLUPISSUBTOTAL function inside ADDMISSINGITEMS and they must match the names of Boolean columns in the supplied table argument. This enables the ADDMISSINGITEMS function to identify BLANK values stemming from the fact that a row is a subtotal row from other BLANK values." }, { "code": null, "e": 5652, "s": 5409, "text": "If ROLLUPGROUP is used with ROLLUPISSUBTOTAL to define the supplied table argument, exactly one ISSUBTOTAL column name must be supplied per ROLLUPGROUP and it must match the corresponding ISSUBTOTAL column name in the supplied table argument." }, { "code": null, "e": 5895, "s": 5652, "text": "If ROLLUPGROUP is used with ROLLUPISSUBTOTAL to define the supplied table argument, exactly one ISSUBTOTAL column name must be supplied per ROLLUPGROUP and it must match the corresponding ISSUBTOTAL column name in the supplied table argument." }, { "code": null, "e": 5999, "s": 5895, "text": "The ADDMISSINGITEMS function will return BLANK values for the IsSubtotal columns of blank rows it adds." }, { "code": null, "e": 6081, "s": 5999, "text": "= ADDMISSINGITEMS (Products, FILTER (Products,Products[Product]=\"Air Purifier\")) " }, { "code": null, "e": 6116, "s": 6081, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6130, "s": 6116, "text": " Abhay Gadiya" }, { "code": null, "e": 6163, "s": 6130, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 6177, "s": 6163, "text": " Randy Minder" }, { "code": null, "e": 6212, "s": 6177, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6226, "s": 6212, "text": " Randy Minder" }, { "code": null, "e": 6233, "s": 6226, "text": " Print" }, { "code": null, "e": 6244, "s": 6233, "text": " Add Notes" } ]
SQL - SELECT Database, USE Statement
When you have multiple databases in your SQL Schema, then before starting your operation, you would need to select a database where all the operations would be performed. The SQL USE statement is used to select any existing database in the SQL schema. The basic syntax of the USE statement is as shown below − USE DatabaseName; Always the database name should be unique within the RDBMS. You can check the available databases as shown below − SQL> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | AMROOD | | TUTORIALSPOINT | | mysql | | orig | | test | +--------------------+ 6 rows in set (0.00 sec) Now, if you want to work with the AMROOD database, then you can execute the following SQL command and start working with the AMROOD database. SQL> USE AMROOD; 42 Lectures 5 hours Anadi Sharma 14 Lectures 2 hours Anadi Sharma 44 Lectures 4.5 hours Anadi Sharma 94 Lectures 7 hours Abhishek And Pukhraj 80 Lectures 6.5 hours Oracle Master Training | 150,000+ Students Worldwide 31 Lectures 6 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2624, "s": 2453, "text": "When you have multiple databases in your SQL Schema, then before starting your operation, you would need to select a database where all the operations would be performed." }, { "code": null, "e": 2705, "s": 2624, "text": "The SQL USE statement is used to select any existing database in the SQL schema." }, { "code": null, "e": 2763, "s": 2705, "text": "The basic syntax of the USE statement is as shown below −" }, { "code": null, "e": 2782, "s": 2763, "text": "USE DatabaseName;\n" }, { "code": null, "e": 2842, "s": 2782, "text": "Always the database name should be unique within the RDBMS." }, { "code": null, "e": 2897, "s": 2842, "text": "You can check the available databases as shown below −" }, { "code": null, "e": 3173, "s": 2897, "text": "SQL> SHOW DATABASES;\n+--------------------+\n| Database |\n+--------------------+\n| information_schema |\n| AMROOD |\n| TUTORIALSPOINT |\n| mysql |\n| orig |\n| test |\n+--------------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 3315, "s": 3173, "text": "Now, if you want to work with the AMROOD database, then you can execute the following SQL command and start working with the AMROOD database." }, { "code": null, "e": 3332, "s": 3315, "text": "SQL> USE AMROOD;" }, { "code": null, "e": 3365, "s": 3332, "text": "\n 42 Lectures \n 5 hours \n" }, { "code": null, "e": 3379, "s": 3365, "text": " Anadi Sharma" }, { "code": null, "e": 3412, "s": 3379, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 3426, "s": 3412, "text": " Anadi Sharma" }, { "code": null, "e": 3461, "s": 3426, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3475, "s": 3461, "text": " Anadi Sharma" }, { "code": null, "e": 3508, "s": 3475, "text": "\n 94 Lectures \n 7 hours \n" }, { "code": null, "e": 3530, "s": 3508, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 3565, "s": 3530, "text": "\n 80 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3619, "s": 3565, "text": " Oracle Master Training | 150,000+ Students Worldwide" }, { "code": null, "e": 3652, "s": 3619, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 3680, "s": 3652, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3687, "s": 3680, "text": " Print" }, { "code": null, "e": 3698, "s": 3687, "text": " Add Notes" } ]
SQL Tryit Editor v1.6
SELECT 'Customer' AS Type, ContactName, City, Country FROM Customers UNION SELECT 'Supplier', ContactName, City, Country FROM Suppliers ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, Opera, and Edge(79). If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 54, "s": 0, "text": "SELECT 'Customer' AS Type, ContactName, City, Country" }, { "code": null, "e": 69, "s": 54, "text": "FROM Customers" }, { "code": null, "e": 75, "s": 69, "text": "UNION" }, { "code": null, "e": 121, "s": 75, "text": "SELECT 'Supplier', ContactName, City, Country" }, { "code": null, "e": 136, "s": 121, "text": "FROM Suppliers" }, { "code": null, "e": 138, "s": 136, "text": "​" }, { "code": null, "e": 201, "s": 138, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 261, "s": 201, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 329, "s": 261, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 367, "s": 329, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 452, "s": 367, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 626, "s": 452, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 677, "s": 626, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 745, "s": 677, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 916, "s": 745, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 1016, "s": 916, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 1076, "s": 1016, "text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)." } ]
Python program to find Maximum and minimum element’s position in a list?
In python is very easy to find out maximum, minimum element and their position also. Python provides different inbuilt function. min() is used for find out minimum value in an array, max() is used for find out maximum value in an array. index() is used for finding the index of the element. maxminposition(A, n) /* A is a user input list and n is the size of the list.*/ Step 1: use inbuilt function for finding the position of minimum element. A.index(min(A)) Step 2: use inbuilt function for finding the position of a maximum element. A.index(max(A)) # Function to find minimum and maximum position in list def maxminposition(A, n): # inbuilt function to find the position of minimum minposition = A.index(min(A)) # inbuilt function to find the position of maximum maxposition = A.index(max(A)) print ("The maximum is at position::", maxposition + 1) print ("The minimum is at position::", minposition + 1) # Driver code A=list() n=int(input("Enter the size of the List ::")) print("Enter the Element ::") for i in range(int(n)): k=int(input("")) A.append(k) maxminposition(A,n) Enter the size of the List ::4 Enter the Element:: 12 34 1 66 The maximum is at position:: 4 The minimum is at position:: 3
[ { "code": null, "e": 1353, "s": 1062, "text": "In python is very easy to find out maximum, minimum element and their position also. Python provides different inbuilt function. min() is used for find out minimum value in an array, max() is used for find out maximum value in an array. index() is used for finding the index of the element." }, { "code": null, "e": 1640, "s": 1353, "text": "maxminposition(A, n)\n/* A is a user input list and n is the size of the list.*/\nStep 1: use inbuilt function for finding the position of minimum element.\n A.index(min(A))\nStep 2: use inbuilt function for finding the position of a maximum element.\n A.index(max(A))\n" }, { "code": null, "e": 2196, "s": 1640, "text": "# Function to find minimum and maximum position in list\ndef maxminposition(A, n):\n # inbuilt function to find the position of minimum \n minposition = A.index(min(A))\n # inbuilt function to find the position of maximum \n maxposition = A.index(max(A)) \n print (\"The maximum is at position::\", maxposition + 1) \n print (\"The minimum is at position::\", minposition + 1)\n# Driver code\nA=list()\nn=int(input(\"Enter the size of the List ::\"))\nprint(\"Enter the Element ::\")\nfor i in range(int(n)):\n k=int(input(\"\"))\n A.append(k)\nmaxminposition(A,n)" }, { "code": null, "e": 2321, "s": 2196, "text": "Enter the size of the List ::4\nEnter the Element::\n12\n34\n1\n66\nThe maximum is at position:: 4\nThe minimum is at position:: 3\n" } ]
Python program to check if a string has at least one letter and one number - GeeksforGeeks
07 Dec, 2021 Given a string in Python. The task is to check whether the string has at least one letter(character) and one number. Return “True” if the given string full fill above condition else return “False” (without quotes).Examples: Input: welcome2ourcountry34 Output: True Input: stringwithoutnum Output: False Approach: The approach is simple we will use loop and two flags for letter and number. These flags will check whether the string contains letter and number. In the end, we will take AND of both flags to check if both are true or not. Letters can be checked in Python String using the isalpha() method and numbers can be checked using the isdigit() method. Python3 def checkString(str): # initializing flag variable flag_l = False flag_n = False # checking for letter and numbers in # given string for i in str: # if string has letter if i.isalpha(): flag_l = True # if string has number if i.isdigit(): flag_n = True # returning and of flag # for checking required condition return flag_l and flag_n # driver codeprint(checkString('thishasboth29'))print(checkString('geeksforgeeks')) Output: True False simranarora5sos Python string-programs python-string Python-string-functions Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 23925, "s": 23897, "text": "\n07 Dec, 2021" }, { "code": null, "e": 24150, "s": 23925, "text": "Given a string in Python. The task is to check whether the string has at least one letter(character) and one number. Return “True” if the given string full fill above condition else return “False” (without quotes).Examples: " }, { "code": null, "e": 24230, "s": 24150, "text": "Input: welcome2ourcountry34\nOutput: True\n\nInput: stringwithoutnum\nOutput: False" }, { "code": null, "e": 24586, "s": 24230, "text": "Approach: The approach is simple we will use loop and two flags for letter and number. These flags will check whether the string contains letter and number. In the end, we will take AND of both flags to check if both are true or not. Letters can be checked in Python String using the isalpha() method and numbers can be checked using the isdigit() method." }, { "code": null, "e": 24594, "s": 24586, "text": "Python3" }, { "code": "def checkString(str): # initializing flag variable flag_l = False flag_n = False # checking for letter and numbers in # given string for i in str: # if string has letter if i.isalpha(): flag_l = True # if string has number if i.isdigit(): flag_n = True # returning and of flag # for checking required condition return flag_l and flag_n # driver codeprint(checkString('thishasboth29'))print(checkString('geeksforgeeks'))", "e": 25113, "s": 24594, "text": null }, { "code": null, "e": 25121, "s": 25113, "text": "Output:" }, { "code": null, "e": 25132, "s": 25121, "text": "True\nFalse" }, { "code": null, "e": 25148, "s": 25132, "text": "simranarora5sos" }, { "code": null, "e": 25171, "s": 25148, "text": "Python string-programs" }, { "code": null, "e": 25185, "s": 25171, "text": "python-string" }, { "code": null, "e": 25209, "s": 25185, "text": "Python-string-functions" }, { "code": null, "e": 25216, "s": 25209, "text": "Python" }, { "code": null, "e": 25232, "s": 25216, "text": "Python Programs" }, { "code": null, "e": 25330, "s": 25232, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25339, "s": 25330, "text": "Comments" }, { "code": null, "e": 25352, "s": 25339, "text": "Old Comments" }, { "code": null, "e": 25384, "s": 25352, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25440, "s": 25384, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25482, "s": 25440, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25524, "s": 25482, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25560, "s": 25524, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 25582, "s": 25560, "text": "Defaultdict in Python" }, { "code": null, "e": 25621, "s": 25582, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25667, "s": 25621, "text": "Python | Split string into list of characters" }, { "code": null, "e": 25705, "s": 25667, "text": "Python | Convert a list to dictionary" } ]
Python 3 - String isalpha() Method
The isalpha() method checks whether the string consists of alphabetic characters only. Following is the syntax for islpha() method − str.isalpha() NA This method returns true if all the characters in the string are alphabetic and there is at least one character, false otherwise. The following example shows the usage of isalpha() method. #!/usr/bin/python3 str = "this"; # No space & digit in this string print (str.isalpha()) str = "this is string example....wow!!!" print (str.isalpha()) When we run above program, it produces the following result − True False 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2427, "s": 2340, "text": "The isalpha() method checks whether the string consists of alphabetic characters only." }, { "code": null, "e": 2473, "s": 2427, "text": "Following is the syntax for islpha() method −" }, { "code": null, "e": 2488, "s": 2473, "text": "str.isalpha()\n" }, { "code": null, "e": 2491, "s": 2488, "text": "NA" }, { "code": null, "e": 2621, "s": 2491, "text": "This method returns true if all the characters in the string are alphabetic and there is at least one character, false otherwise." }, { "code": null, "e": 2680, "s": 2621, "text": "The following example shows the usage of isalpha() method." }, { "code": null, "e": 2835, "s": 2680, "text": "#!/usr/bin/python3\n\nstr = \"this\"; # No space & digit in this string\nprint (str.isalpha())\n\nstr = \"this is string example....wow!!!\"\nprint (str.isalpha())" }, { "code": null, "e": 2897, "s": 2835, "text": "When we run above program, it produces the following result −" }, { "code": null, "e": 2909, "s": 2897, "text": "True\nFalse\n" }, { "code": null, "e": 2946, "s": 2909, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 2962, "s": 2946, "text": " Malhar Lathkar" }, { "code": null, "e": 2995, "s": 2962, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3014, "s": 2995, "text": " Arnab Chakraborty" }, { "code": null, "e": 3049, "s": 3014, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3071, "s": 3049, "text": " In28Minutes Official" }, { "code": null, "e": 3105, "s": 3071, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3133, "s": 3105, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3168, "s": 3133, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3182, "s": 3168, "text": " Lets Kode It" }, { "code": null, "e": 3215, "s": 3182, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3232, "s": 3215, "text": " Abhilash Nelson" }, { "code": null, "e": 3239, "s": 3232, "text": " Print" }, { "code": null, "e": 3250, "s": 3239, "text": " Add Notes" } ]
Distributed Deep Learning with Horovod | by Jordi TORRES.AI | Towards Data Science
[This post will be used in the master course Supercomputers Architecture at UPC Barcelona Tech with the support of the BSC] In the previous post we explored how we can scale the training on Multiple GPUs in one Server with TensorFlow using tf.distributed.MirroredStrategy(). Now, in this post, we will use Horovod API to scale the training on multiple servers following data parallelism strategies. Uber Engineering introduced Michelangelo, an internal ML-as-a-service platform that makes it easy to build and deploy these systems at scale. Horovod, a component of Michelangelo, is an open-source distributed training framework for TensorFlow, PyTorch, and MXNet. Its goal is to make distributed Deep Learning fast and easy to use via ring-allreduce and requires only a few lines of modification to user code. Horovod is available under the Apache 2.0 license. Conceptually, the data-parallel distributed training paradigm under Horovod is straightforward: 1. Run multiple copies of the training script and each copy: reads a chunk of the data runs it through the model computes model updates (gradients) 2. Average gradients among those multiple copies 3. Update the model 4. Repeat (from Step 1) Horovod applies Baidu’s algorithm for averaging gradients and communicating those gradients to all nodes (steps 2 and 3 above) that follows the ring-allreduce decentralized scheme. The algorithm was based on the approach introduced in the 2009 paper by Patarasuk and Yuan. Horovod replaced the Baidu ring-allreduce implementation with NCCL-2, which is NVIDIA’s library for collective communication that provides a highly optimized version of ring-allreduce across multiple machines. The following figure from the paper by Sergeev and Balso shows the ring-allreduce algorithm that allows workers nodes to average gradients and disperses them to all nodes without the need for a centralized scheme with a parameter server. A more clear and visual explanation can be obtained in this post from Medium: “Visual intuition on ring-allreduce for distributed Deep Learning”. In this ring-allreduce algorithm, each of N nodes communicates with two of its peers 2∗(N−1) times. During this communication, a node sends and receives chunks of the data buffer. In the first N-1 iterations, received values are added to the values in the node’s buffer. In the second N-1 iterations, received values replace the values held in the node’s buffer. Patarasuk and Yuan suggest that this algorithm is bandwidth-optimal, meaning that if the buffer is large enough, it will optimally utilize the available network. Horovod is a python package installed using pip, and in general it assumes installation of MPI for worker discovery and reduction coordination and Nvidia’s NCCL-2 libraries to support inter-GPU communication. This is because MPI is used extensively in the supercomputing community for high-performance parallel computing. However, if MPI is not installed, Horovod includes Gloo, an open-source collective communications library developed by Facebook. You can choose to use Gloo at runtime by passing the --gloo argument to horovodrun: $ horovodrun --gloo -np 2 python train.py Horovod introduces an hvdobject that has to be initialized and has to wrap the optimizer (Horovod averages the gradients using allreduce or allgather). A GPU is bound to this process using its local rank, and we broadcast variables from rank 0 to all other processes during initialization. A Horovod Python program is launched using the mpiruncommand. It takes as parameters the hostname of each server as well as the number of GPUs to be used on each server. To use Horovod in Tensorflow, you must make the following additions to your program: Import Horovod: Import Horovod: import horovod.tensorflow as hvd 2. Horovod must be initialized before starting using: hvd.init() 3. Pin each GPU to a process.We will be employing local rank for that, such that, the first process in the server will be pinned to the first GPU; the second process to the second GPU, and so forth: gpus = tf.config.experimental.list_physical_devices('GPU')for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True)if gpus: tf.config.experimental.set_visible_devices( gpus[hvd.local_rank()], 'GPU') 4. Scale the learning rate by the number of workers. Effective batch size in synchronous distributed training is scaled by the number of workers. An increase in learning rate compensates for the increased batch size. You can know more about this in this Facebook’s paper. opt = tf.keras.optimizers.SGD(0.0005 * hvd.size()) 5. Wrap optimizer in hvd.DistributedOptimizer. The distributed optimizer delegates gradient computation to the original optimizer, averages gradients using allreduce or allgather, and then applies those averaged gradients. opt = hvd.DistributedOptimizer(opt) 6. Specify experimental_run_tf_function=False to ensure TensorFlow uses Horovod’s distributed optimizer to compute gradients. 7. Add hvd.callbacks.BroadcastGlobalVariablesCallback(0) to broadcast initial variable states from rank 0 to all other processes. This is necessary to ensure consistent initialization of all workers when training is started with random weights or restored from a checkpoint. callbacks = [ hvd.callbacks.BroadcastGlobalVariablesCallback(0)] 8. If you need to save checkpoints, do it only on worker 0 to prevent other workers from corrupting them. Or if you want to run evaluation or to print information to the standard output, it is recommended to do it on worker 0. This can be accomplished with hvd.rank() = 0. if hvd.rank() == 0: print(model.summary()) To show how to use Horovod, we will use the same example presented in the previous post, that trains a classifier of CIFAR10 dataset based in a ResNet50, and train it on the CTE-POWER machine. Following the steps presented in the above section on how to use Horovod API, below we present the resulting parallel code: import tensorflow as tffrom tensorflow.keras import layersfrom tensorflow.keras import modelsimport horovod.tensorflow.keras as hvdimport numpy as npimport argparseimport timeimport syssys.path.append(‘/gpfs/projects/nct00/nct00002/cifar-utils’)from cifar import load_cifarhvd.init()parser = argparse.ArgumentParser()parser.add_argument(‘ -- epochs’, type=int, default=5)parser.add_argument(‘ -- batch_size’, type=int, default=256)args = parser.parse_args()batch_size = args.batch_sizeepochs = args.epochsmodel_name = args.model_namegpus = tf.config.experimental.list_physical_devices(‘GPU’)for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True)if gpus: tf.config.experimental.set_visible_devices( gpus[hvd.local_rank()], ‘GPU’)train_ds, test_ds = load_cifar(batch_size)model = tf.keras.applications.resnet_v2.ResNet50V2( include_top=True, weights=None, input_shape=(128, 128, 3), classes=10)if hvd.rank() == 0: print(model.summary())opt = tf.keras.optimizers.SGD(0.0005 * hvd.size())opt = hvd.DistributedOptimizer(opt)model.compile( loss=’sparse_categorical_crossentropy’, optimizer=opt, metrics=[‘accuracy’], experimental_run_tf_function=False)callbacks = [ hvd.callbacks.BroadcastGlobalVariablesCallback(0)]if hvd.rank() == 0: verbose = 2else: verbose=0model.fit(train_ds, epochs=epochs, verbose=verbose, callbacks=callbacks) After modifying your sequential python script with the inclusion of Horovod API calls, you must write your job script (.sh file) to submit the job to the SLURM workload manager as we did in the previous section. For this concrete example, presented in the previous section, the SLURM script to send the jobs to run on a server with 4GPUs looks like this: #!/bin/bash#SBATCH --job-name horovod1#SBATCH -D .#SBATCH --output hvd_1_%j.output#SBATCH --error hvd_1_%j.err#SBATCH --nodes=1#SBATCH --gres='gpu:4'#SBATCH --ntasks-per-node=4#SBATCH --cpus-per-task 40#SBATCH --time 00:25:00module purge; module load gcc/8.3.0 cuda/10.2 cudnn/7.6.4 nccl/2.4.8 tensorrt/6.0.1 openmpi/4.0.1 atlas/3.10.3 scalapack/2.0.2 fftw/3.3.8 szip/2.1.1 ffmpeg/4.2.1 opencv/4.1.1 python/3.7.4_MLhorovodrun -np $SLURM_NTASKS -H localhost:$SLURM_NTASKS --gloo \python3.7 tf2_keras_cifar_hvd.py --epochs 10 --batch_size 512 If we take a look at this SLURM script, we can find the following variables that will determine how our model will be distributed: nodes: Amount of servers that will be employed to distribute the workload gres: Amount of GPUs’s per server that will be used. ntasks-per-node: Number of processes running in a server. In Horovod each GPU gets pinned to a process, therefore this should be equal to the number of GPUs employed in each server (it must be added to create SLURM_NTASKS variable that will be required for the -np flag in horovodrunthat especifies the number of processes). cpu-per-task: In CTE-POWER each server holds 160 cores, therefore this parameter must be 160/ntasks-per-node to employ the maximum amount of cores per process. Detailed information about the possible flags for horovodrun command can be obtained executing the command horovodrun --help. In the example from above we are using one server with 4 GPUs. If we would like to employ 8 GPUs to do our computation we would need 2 servers, as each server in the CTE-POWER has 4GPUs. To run on more than one server (for example, on two), we need to use the following SLURM script: #!/bin/bash#SBATCH --job-name horovod-multinode#SBATCH --D .#SBATCH --output hvd_multinode_%j.output#SBATCH --error hvd_multinode_%j.error#SBATCH --nodes=2#SBATCH --gres=’gpu:4'#SBATCH --ntasks-per-node=4#SBATCH --cpus-per-task 40#SBATCH --time 00:50:00module purge; module load gcc/8.3.0 cuda/10.2 cudnn/7.6.4 nccl/2.4.8 tensorrt/6.0.1 openmpi/4.0.1 atlas/3.10.3 scalapack/2.0.2 fftw/3.3.8 szip/2.1.1 ffmpeg/4.2.1 opencv/4.1.1 python/3.7.4_MLHOSTS_FLAG="-H "for node in $(scontrol show hostnames "$SLURM_JOB_NODELIST"); do HOSTS_FLAG="$HOSTS_FLAG$node-ib0:$SLURM_NTASKS_PER_NODE,"doneHOSTS_FLAG=${HOSTS_FLAG%?}horovodrun --start-timeout 120 --gloo-timeout-seconds 120 \-np $SLURM_NTASKS $HOSTS_FLAG --network-interface ib0 --gloo \python3.7 tf2_keras_cifar_hvd.py --epochs 10 --batch_size 512 Where we employ 2 servers, each server using 4 GPUs, therefore we will be using 8 GPUs in total. Remember that in Post 2 of this series, the reader can find more detailed information about all the #SBATCH commands we usually use in our supercomputer. The previous listing shows different names, than the previous one for the #SBATCH options. It is done deliberately with the purpose of showing that SLURM has some “flexibility” with the names used. In this section we are going to present an experiment that will help us show how the Horovod API works and, at the same time, be able to experiment with its scalability. The reader will surely think that the canonical test that would be more suitable to evaluate the scalability of Horovod is to perform a set of tests where the same number of epochs are executed with different GPUs: 1,2,4,8,16 and 32. But this is not feasible given the availability of the resources that we have assigned in the master course. To begin with, a larger problem than that of classifying the CIFAR10 would be required to show results that exhibit that take advantage of the computing power of 32 V100 NVIDIA GPUs. Also, it will be required to run a minimum number of epochs per execution to be able to dampen the required initialization. Let’s assume that with the test of 32 GPUs, for example, we would perform a minimum number of 8 epochs. In the ideal canonical comparison test, this would involve running 256 epochs on 1 GPU (32x8) in order to compare. Even in this small problem of classifying the CIFAR40 dataset with a ResNet50, each epoch takes about 40 seconds. That means about 3 hours to train the model with 1 GPU — something totally unfeasible given the resources available for this master course. Likewise, it must be taken into account that a hyperparameter tuning should be performed, which requires many tests. And finally, remember that we should carry out several executions to give statistical validity to the tests given the innate randomness in the behavior of the software stack or the initializations of the system’s initializations. In short, a huge amount of computing resources is required, and, as we have explained, we do not have them available in this master course. Given these constraints, we have thought of a hands-on that performs a specific test, very guaranteeing, for example with a deliberately low learning-rate so that it does not explode in tests with many GPUs. This hands-on designed allows us to show how the throughput of the system increases (images per unit of time) and to focus on the scaling metric. This means that we must completely forget about the Accuracy metric, since to make correct tests at the Accuracy level we should do a more detailed work of the tunning hyperparameters that we cannot do. For this reason, we cannot make any comparisons in the results of this hands-on at the Accuracy level. The literature on the subject shows, that if we do a correct hyperparameter tuning, the loss of Accuracy in the scale is reasonably when using the Horovod API in supercomputers such as CTE-POWER. In summary, we have designed a simple synthetic test where each GPU performs the same number of epochs, and therefore with 32 GPUs, we will perform 32 times more epochs than with 1 GPU. In this scenario, the measurement of time of the training process of each test can serve as a metric of the quality of scaling at the throughput level. That is, if we had a linear speedup, the time should always be the same in all tests. Remember that we focus our hands-on on the computational speed of the process rather than the model’s accuracy, and we will only compare the time required to execute the .fitmethod with the different tests. For this purpose, we will use the following simple code to measure the time: start = time.time()model.fit(train_ds, epochs=epochs, verbose=verbose, callbacks=callbacks)end = time.time()if hvd.rank() == 0: print(‘Total Time:’, round((end — start), 2), ‘(s)’) Once we run the previous python code, in the file .output that has stored the standard output, we find the execution time required to execute the method .fit(). There are different ways to design the experiment, but a simple way seems to be to send a job to SLURM for each test: 1,2,4,8,16 and, 32 GPUs. For example, in our case, we created: [nct010xx@p9login2]$ lsjob_hvd_1node_1gpu.shjob_hvd_1node_2gpu.shjob_hvd_1node_4gpu.shjob_hvd_multi_node_8gpus.shjob_hvd_multi_node_16gpus.shjob_hvd_multi_node_32gpus.shjob_hvd_multi_node_64gpus.sh And each of these SLURM jobs generated a .output file like: [nct010xx@p9login2]$ tail hvd_1_4gpus_4721140.outputEpoch 7/1098/98–41s — loss: 1.6659 — accuracy: 0.3903Epoch 8/1098/98–41s — loss: 1.6420 — accuracy: 0.3992Epoch 9/1098/98–41s — loss: 1.6224 — accuracy: 0.4067Epoch 10/1098/98–41s — loss: 1.5977 — accuracy: 0.4162Total Time: 691.1 (s) where the last line indicates the required to execute the method .fit(). In summary, in the .output files, we have all the times that interest us. The following graph plots the time required for executing 10 epoch using up to 64 GPUs: We can see that the more GPUs we have, despite having the same job per GPU (epochs = 10 * num GPUs), there is more overhead time to add. It should be noted that these times come from a single execution and can vary between several executions. It is evident that if we want to do a good study, we should carry out several tests and then take the averages of the times obtained in each one of them. But given the purpose of this post (and the cost of resources, which we have to save!), it is enough only one execution. Finally, as we already mentioned in previous posts, the speedup is a popular metric in our community. The following graph plots the speedup in blue and in white what is missing to reach the optimal linear speed up. Each column n is obtained by, first, dividing the time required to execute 10 epoch with 1 GPU by the time required when we execute the same workload with n GPU. And finally, multiplying the resulting value by n (the number of GPUs used). We can conclude that the training really scales with regard to images per second processed, which does not mean that in terms of Accuracy it happens the same, since in this example we have ignored the hyperparameter tunning stage and therefore we cannot draw conclusions from the Accuracy we get. If you want to learn more and consolidate the knowledge acquired, now it’s your turn to get your hands dirty to reproduce the above results for the ResNET152V2. Explain why you think these results come out and compare the results with those obtained with ResNET50V2. In this post, we have presented how to distribute the training of a single Deep Neural Network over many servers using Horovod. We only proposed a toy experiment due to the limitations of the resources available. However, from my point of view, It serves the purpose of bringing the reader closer to the Horovod API. This is the last post of this series that I wrote to support my classes in my master course SA-MIRI at UPC Barcelona Tech (with the support of Barcelona Supercomputing Center). I share it at Towards Data Science just in case it can be useful for other readers. Artificial Intelligence is a Supercomputing problemUsing Supercomputers for Deep Learning TrainingScalable Deep Learning on Parallel and Distributed InfrastructuresTrain a Neural Network on multi-GPU with TensorFlowDistributed Deep Learning with Horovod Artificial Intelligence is a Supercomputing problem Using Supercomputers for Deep Learning Training Scalable Deep Learning on Parallel and Distributed Infrastructures Train a Neural Network on multi-GPU with TensorFlow Distributed Deep Learning with Horovod Acknowledgment: Many thanks to Juan Luis Domínguez and Oriol Aranda from BSC-CNS, who wrote the first version of the codes that appear in this series of posts, and to Carlos Tripiana and Francisco Gonzalez for the essential support with the deployment of the software stack of POWER-CTE Supercomputer. Also many thanks to Alvaro Jover Alvarez, Miquel Escobar Castells and Raul Garcia Fuentes for their contributions to the proofreading of this document.
[ { "code": null, "e": 295, "s": 171, "text": "[This post will be used in the master course Supercomputers Architecture at UPC Barcelona Tech with the support of the BSC]" }, { "code": null, "e": 570, "s": 295, "text": "In the previous post we explored how we can scale the training on Multiple GPUs in one Server with TensorFlow using tf.distributed.MirroredStrategy(). Now, in this post, we will use Horovod API to scale the training on multiple servers following data parallelism strategies." }, { "code": null, "e": 1032, "s": 570, "text": "Uber Engineering introduced Michelangelo, an internal ML-as-a-service platform that makes it easy to build and deploy these systems at scale. Horovod, a component of Michelangelo, is an open-source distributed training framework for TensorFlow, PyTorch, and MXNet. Its goal is to make distributed Deep Learning fast and easy to use via ring-allreduce and requires only a few lines of modification to user code. Horovod is available under the Apache 2.0 license." }, { "code": null, "e": 1128, "s": 1032, "text": "Conceptually, the data-parallel distributed training paradigm under Horovod is straightforward:" }, { "code": null, "e": 1189, "s": 1128, "text": "1. Run multiple copies of the training script and each copy:" }, { "code": null, "e": 1215, "s": 1189, "text": "reads a chunk of the data" }, { "code": null, "e": 1241, "s": 1215, "text": "runs it through the model" }, { "code": null, "e": 1276, "s": 1241, "text": "computes model updates (gradients)" }, { "code": null, "e": 1325, "s": 1276, "text": "2. Average gradients among those multiple copies" }, { "code": null, "e": 1345, "s": 1325, "text": "3. Update the model" }, { "code": null, "e": 1369, "s": 1345, "text": "4. Repeat (from Step 1)" }, { "code": null, "e": 1852, "s": 1369, "text": "Horovod applies Baidu’s algorithm for averaging gradients and communicating those gradients to all nodes (steps 2 and 3 above) that follows the ring-allreduce decentralized scheme. The algorithm was based on the approach introduced in the 2009 paper by Patarasuk and Yuan. Horovod replaced the Baidu ring-allreduce implementation with NCCL-2, which is NVIDIA’s library for collective communication that provides a highly optimized version of ring-allreduce across multiple machines." }, { "code": null, "e": 2090, "s": 1852, "text": "The following figure from the paper by Sergeev and Balso shows the ring-allreduce algorithm that allows workers nodes to average gradients and disperses them to all nodes without the need for a centralized scheme with a parameter server." }, { "code": null, "e": 2236, "s": 2090, "text": "A more clear and visual explanation can be obtained in this post from Medium: “Visual intuition on ring-allreduce for distributed Deep Learning”." }, { "code": null, "e": 2761, "s": 2236, "text": "In this ring-allreduce algorithm, each of N nodes communicates with two of its peers 2∗(N−1) times. During this communication, a node sends and receives chunks of the data buffer. In the first N-1 iterations, received values are added to the values in the node’s buffer. In the second N-1 iterations, received values replace the values held in the node’s buffer. Patarasuk and Yuan suggest that this algorithm is bandwidth-optimal, meaning that if the buffer is large enough, it will optimally utilize the available network." }, { "code": null, "e": 3083, "s": 2761, "text": "Horovod is a python package installed using pip, and in general it assumes installation of MPI for worker discovery and reduction coordination and Nvidia’s NCCL-2 libraries to support inter-GPU communication. This is because MPI is used extensively in the supercomputing community for high-performance parallel computing." }, { "code": null, "e": 3296, "s": 3083, "text": "However, if MPI is not installed, Horovod includes Gloo, an open-source collective communications library developed by Facebook. You can choose to use Gloo at runtime by passing the --gloo argument to horovodrun:" }, { "code": null, "e": 3338, "s": 3296, "text": "$ horovodrun --gloo -np 2 python train.py" }, { "code": null, "e": 3628, "s": 3338, "text": "Horovod introduces an hvdobject that has to be initialized and has to wrap the optimizer (Horovod averages the gradients using allreduce or allgather). A GPU is bound to this process using its local rank, and we broadcast variables from rank 0 to all other processes during initialization." }, { "code": null, "e": 3798, "s": 3628, "text": "A Horovod Python program is launched using the mpiruncommand. It takes as parameters the hostname of each server as well as the number of GPUs to be used on each server." }, { "code": null, "e": 3883, "s": 3798, "text": "To use Horovod in Tensorflow, you must make the following additions to your program:" }, { "code": null, "e": 3899, "s": 3883, "text": "Import Horovod:" }, { "code": null, "e": 3915, "s": 3899, "text": "Import Horovod:" }, { "code": null, "e": 3948, "s": 3915, "text": "import horovod.tensorflow as hvd" }, { "code": null, "e": 4002, "s": 3948, "text": "2. Horovod must be initialized before starting using:" }, { "code": null, "e": 4013, "s": 4002, "text": "hvd.init()" }, { "code": null, "e": 4212, "s": 4013, "text": "3. Pin each GPU to a process.We will be employing local rank for that, such that, the first process in the server will be pinned to the first GPU; the second process to the second GPU, and so forth:" }, { "code": null, "e": 4444, "s": 4212, "text": "gpus = tf.config.experimental.list_physical_devices('GPU')for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True)if gpus: tf.config.experimental.set_visible_devices( gpus[hvd.local_rank()], 'GPU')" }, { "code": null, "e": 4716, "s": 4444, "text": "4. Scale the learning rate by the number of workers. Effective batch size in synchronous distributed training is scaled by the number of workers. An increase in learning rate compensates for the increased batch size. You can know more about this in this Facebook’s paper." }, { "code": null, "e": 4767, "s": 4716, "text": "opt = tf.keras.optimizers.SGD(0.0005 * hvd.size())" }, { "code": null, "e": 4990, "s": 4767, "text": "5. Wrap optimizer in hvd.DistributedOptimizer. The distributed optimizer delegates gradient computation to the original optimizer, averages gradients using allreduce or allgather, and then applies those averaged gradients." }, { "code": null, "e": 5026, "s": 4990, "text": "opt = hvd.DistributedOptimizer(opt)" }, { "code": null, "e": 5152, "s": 5026, "text": "6. Specify experimental_run_tf_function=False to ensure TensorFlow uses Horovod’s distributed optimizer to compute gradients." }, { "code": null, "e": 5427, "s": 5152, "text": "7. Add hvd.callbacks.BroadcastGlobalVariablesCallback(0) to broadcast initial variable states from rank 0 to all other processes. This is necessary to ensure consistent initialization of all workers when training is started with random weights or restored from a checkpoint." }, { "code": null, "e": 5497, "s": 5427, "text": "callbacks = [ hvd.callbacks.BroadcastGlobalVariablesCallback(0)]" }, { "code": null, "e": 5770, "s": 5497, "text": "8. If you need to save checkpoints, do it only on worker 0 to prevent other workers from corrupting them. Or if you want to run evaluation or to print information to the standard output, it is recommended to do it on worker 0. This can be accomplished with hvd.rank() = 0." }, { "code": null, "e": 5815, "s": 5770, "text": "if hvd.rank() == 0: print(model.summary())" }, { "code": null, "e": 6008, "s": 5815, "text": "To show how to use Horovod, we will use the same example presented in the previous post, that trains a classifier of CIFAR10 dataset based in a ResNet50, and train it on the CTE-POWER machine." }, { "code": null, "e": 6132, "s": 6008, "text": "Following the steps presented in the above section on how to use Horovod API, below we present the resulting parallel code:" }, { "code": null, "e": 7535, "s": 6132, "text": "import tensorflow as tffrom tensorflow.keras import layersfrom tensorflow.keras import modelsimport horovod.tensorflow.keras as hvdimport numpy as npimport argparseimport timeimport syssys.path.append(‘/gpfs/projects/nct00/nct00002/cifar-utils’)from cifar import load_cifarhvd.init()parser = argparse.ArgumentParser()parser.add_argument(‘ -- epochs’, type=int, default=5)parser.add_argument(‘ -- batch_size’, type=int, default=256)args = parser.parse_args()batch_size = args.batch_sizeepochs = args.epochsmodel_name = args.model_namegpus = tf.config.experimental.list_physical_devices(‘GPU’)for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True)if gpus: tf.config.experimental.set_visible_devices( gpus[hvd.local_rank()], ‘GPU’)train_ds, test_ds = load_cifar(batch_size)model = tf.keras.applications.resnet_v2.ResNet50V2( include_top=True, weights=None, input_shape=(128, 128, 3), classes=10)if hvd.rank() == 0: print(model.summary())opt = tf.keras.optimizers.SGD(0.0005 * hvd.size())opt = hvd.DistributedOptimizer(opt)model.compile( loss=’sparse_categorical_crossentropy’, optimizer=opt, metrics=[‘accuracy’], experimental_run_tf_function=False)callbacks = [ hvd.callbacks.BroadcastGlobalVariablesCallback(0)]if hvd.rank() == 0: verbose = 2else: verbose=0model.fit(train_ds, epochs=epochs, verbose=verbose, callbacks=callbacks)" }, { "code": null, "e": 7747, "s": 7535, "text": "After modifying your sequential python script with the inclusion of Horovod API calls, you must write your job script (.sh file) to submit the job to the SLURM workload manager as we did in the previous section." }, { "code": null, "e": 7890, "s": 7747, "text": "For this concrete example, presented in the previous section, the SLURM script to send the jobs to run on a server with 4GPUs looks like this:" }, { "code": null, "e": 8431, "s": 7890, "text": "#!/bin/bash#SBATCH --job-name horovod1#SBATCH -D .#SBATCH --output hvd_1_%j.output#SBATCH --error hvd_1_%j.err#SBATCH --nodes=1#SBATCH --gres='gpu:4'#SBATCH --ntasks-per-node=4#SBATCH --cpus-per-task 40#SBATCH --time 00:25:00module purge; module load gcc/8.3.0 cuda/10.2 cudnn/7.6.4 nccl/2.4.8 tensorrt/6.0.1 openmpi/4.0.1 atlas/3.10.3 scalapack/2.0.2 fftw/3.3.8 szip/2.1.1 ffmpeg/4.2.1 opencv/4.1.1 python/3.7.4_MLhorovodrun -np $SLURM_NTASKS -H localhost:$SLURM_NTASKS --gloo \\python3.7 tf2_keras_cifar_hvd.py --epochs 10 --batch_size 512" }, { "code": null, "e": 8562, "s": 8431, "text": "If we take a look at this SLURM script, we can find the following variables that will determine how our model will be distributed:" }, { "code": null, "e": 8636, "s": 8562, "text": "nodes: Amount of servers that will be employed to distribute the workload" }, { "code": null, "e": 8689, "s": 8636, "text": "gres: Amount of GPUs’s per server that will be used." }, { "code": null, "e": 9014, "s": 8689, "text": "ntasks-per-node: Number of processes running in a server. In Horovod each GPU gets pinned to a process, therefore this should be equal to the number of GPUs employed in each server (it must be added to create SLURM_NTASKS variable that will be required for the -np flag in horovodrunthat especifies the number of processes)." }, { "code": null, "e": 9174, "s": 9014, "text": "cpu-per-task: In CTE-POWER each server holds 160 cores, therefore this parameter must be 160/ntasks-per-node to employ the maximum amount of cores per process." }, { "code": null, "e": 9300, "s": 9174, "text": "Detailed information about the possible flags for horovodrun command can be obtained executing the command horovodrun --help." }, { "code": null, "e": 9584, "s": 9300, "text": "In the example from above we are using one server with 4 GPUs. If we would like to employ 8 GPUs to do our computation we would need 2 servers, as each server in the CTE-POWER has 4GPUs. To run on more than one server (for example, on two), we need to use the following SLURM script:" }, { "code": null, "e": 10380, "s": 9584, "text": "#!/bin/bash#SBATCH --job-name horovod-multinode#SBATCH --D .#SBATCH --output hvd_multinode_%j.output#SBATCH --error hvd_multinode_%j.error#SBATCH --nodes=2#SBATCH --gres=’gpu:4'#SBATCH --ntasks-per-node=4#SBATCH --cpus-per-task 40#SBATCH --time 00:50:00module purge; module load gcc/8.3.0 cuda/10.2 cudnn/7.6.4 nccl/2.4.8 tensorrt/6.0.1 openmpi/4.0.1 atlas/3.10.3 scalapack/2.0.2 fftw/3.3.8 szip/2.1.1 ffmpeg/4.2.1 opencv/4.1.1 python/3.7.4_MLHOSTS_FLAG=\"-H \"for node in $(scontrol show hostnames \"$SLURM_JOB_NODELIST\"); do HOSTS_FLAG=\"$HOSTS_FLAG$node-ib0:$SLURM_NTASKS_PER_NODE,\"doneHOSTS_FLAG=${HOSTS_FLAG%?}horovodrun --start-timeout 120 --gloo-timeout-seconds 120 \\-np $SLURM_NTASKS $HOSTS_FLAG --network-interface ib0 --gloo \\python3.7 tf2_keras_cifar_hvd.py --epochs 10 --batch_size 512" }, { "code": null, "e": 10477, "s": 10380, "text": "Where we employ 2 servers, each server using 4 GPUs, therefore we will be using 8 GPUs in total." }, { "code": null, "e": 10631, "s": 10477, "text": "Remember that in Post 2 of this series, the reader can find more detailed information about all the #SBATCH commands we usually use in our supercomputer." }, { "code": null, "e": 10829, "s": 10631, "text": "The previous listing shows different names, than the previous one for the #SBATCH options. It is done deliberately with the purpose of showing that SLURM has some “flexibility” with the names used." }, { "code": null, "e": 10999, "s": 10829, "text": "In this section we are going to present an experiment that will help us show how the Horovod API works and, at the same time, be able to experiment with its scalability." }, { "code": null, "e": 11342, "s": 10999, "text": "The reader will surely think that the canonical test that would be more suitable to evaluate the scalability of Horovod is to perform a set of tests where the same number of epochs are executed with different GPUs: 1,2,4,8,16 and 32. But this is not feasible given the availability of the resources that we have assigned in the master course." }, { "code": null, "e": 11525, "s": 11342, "text": "To begin with, a larger problem than that of classifying the CIFAR10 would be required to show results that exhibit that take advantage of the computing power of 32 V100 NVIDIA GPUs." }, { "code": null, "e": 12122, "s": 11525, "text": "Also, it will be required to run a minimum number of epochs per execution to be able to dampen the required initialization. Let’s assume that with the test of 32 GPUs, for example, we would perform a minimum number of 8 epochs. In the ideal canonical comparison test, this would involve running 256 epochs on 1 GPU (32x8) in order to compare. Even in this small problem of classifying the CIFAR40 dataset with a ResNet50, each epoch takes about 40 seconds. That means about 3 hours to train the model with 1 GPU — something totally unfeasible given the resources available for this master course." }, { "code": null, "e": 12469, "s": 12122, "text": "Likewise, it must be taken into account that a hyperparameter tuning should be performed, which requires many tests. And finally, remember that we should carry out several executions to give statistical validity to the tests given the innate randomness in the behavior of the software stack or the initializations of the system’s initializations." }, { "code": null, "e": 12609, "s": 12469, "text": "In short, a huge amount of computing resources is required, and, as we have explained, we do not have them available in this master course." }, { "code": null, "e": 12817, "s": 12609, "text": "Given these constraints, we have thought of a hands-on that performs a specific test, very guaranteeing, for example with a deliberately low learning-rate so that it does not explode in tests with many GPUs." }, { "code": null, "e": 13166, "s": 12817, "text": "This hands-on designed allows us to show how the throughput of the system increases (images per unit of time) and to focus on the scaling metric. This means that we must completely forget about the Accuracy metric, since to make correct tests at the Accuracy level we should do a more detailed work of the tunning hyperparameters that we cannot do." }, { "code": null, "e": 13465, "s": 13166, "text": "For this reason, we cannot make any comparisons in the results of this hands-on at the Accuracy level. The literature on the subject shows, that if we do a correct hyperparameter tuning, the loss of Accuracy in the scale is reasonably when using the Horovod API in supercomputers such as CTE-POWER." }, { "code": null, "e": 13889, "s": 13465, "text": "In summary, we have designed a simple synthetic test where each GPU performs the same number of epochs, and therefore with 32 GPUs, we will perform 32 times more epochs than with 1 GPU. In this scenario, the measurement of time of the training process of each test can serve as a metric of the quality of scaling at the throughput level. That is, if we had a linear speedup, the time should always be the same in all tests." }, { "code": null, "e": 14173, "s": 13889, "text": "Remember that we focus our hands-on on the computational speed of the process rather than the model’s accuracy, and we will only compare the time required to execute the .fitmethod with the different tests. For this purpose, we will use the following simple code to measure the time:" }, { "code": null, "e": 14366, "s": 14173, "text": "start = time.time()model.fit(train_ds, epochs=epochs, verbose=verbose, callbacks=callbacks)end = time.time()if hvd.rank() == 0: print(‘Total Time:’, round((end — start), 2), ‘(s)’)" }, { "code": null, "e": 14527, "s": 14366, "text": "Once we run the previous python code, in the file .output that has stored the standard output, we find the execution time required to execute the method .fit()." }, { "code": null, "e": 14708, "s": 14527, "text": "There are different ways to design the experiment, but a simple way seems to be to send a job to SLURM for each test: 1,2,4,8,16 and, 32 GPUs. For example, in our case, we created:" }, { "code": null, "e": 14906, "s": 14708, "text": "[nct010xx@p9login2]$ lsjob_hvd_1node_1gpu.shjob_hvd_1node_2gpu.shjob_hvd_1node_4gpu.shjob_hvd_multi_node_8gpus.shjob_hvd_multi_node_16gpus.shjob_hvd_multi_node_32gpus.shjob_hvd_multi_node_64gpus.sh" }, { "code": null, "e": 14966, "s": 14906, "text": "And each of these SLURM jobs generated a .output file like:" }, { "code": null, "e": 15253, "s": 14966, "text": "[nct010xx@p9login2]$ tail hvd_1_4gpus_4721140.outputEpoch 7/1098/98–41s — loss: 1.6659 — accuracy: 0.3903Epoch 8/1098/98–41s — loss: 1.6420 — accuracy: 0.3992Epoch 9/1098/98–41s — loss: 1.6224 — accuracy: 0.4067Epoch 10/1098/98–41s — loss: 1.5977 — accuracy: 0.4162Total Time: 691.1 (s)" }, { "code": null, "e": 15326, "s": 15253, "text": "where the last line indicates the required to execute the method .fit()." }, { "code": null, "e": 15488, "s": 15326, "text": "In summary, in the .output files, we have all the times that interest us. The following graph plots the time required for executing 10 epoch using up to 64 GPUs:" }, { "code": null, "e": 16006, "s": 15488, "text": "We can see that the more GPUs we have, despite having the same job per GPU (epochs = 10 * num GPUs), there is more overhead time to add. It should be noted that these times come from a single execution and can vary between several executions. It is evident that if we want to do a good study, we should carry out several tests and then take the averages of the times obtained in each one of them. But given the purpose of this post (and the cost of resources, which we have to save!), it is enough only one execution." }, { "code": null, "e": 16221, "s": 16006, "text": "Finally, as we already mentioned in previous posts, the speedup is a popular metric in our community. The following graph plots the speedup in blue and in white what is missing to reach the optimal linear speed up." }, { "code": null, "e": 16460, "s": 16221, "text": "Each column n is obtained by, first, dividing the time required to execute 10 epoch with 1 GPU by the time required when we execute the same workload with n GPU. And finally, multiplying the resulting value by n (the number of GPUs used)." }, { "code": null, "e": 16757, "s": 16460, "text": "We can conclude that the training really scales with regard to images per second processed, which does not mean that in terms of Accuracy it happens the same, since in this example we have ignored the hyperparameter tunning stage and therefore we cannot draw conclusions from the Accuracy we get." }, { "code": null, "e": 17024, "s": 16757, "text": "If you want to learn more and consolidate the knowledge acquired, now it’s your turn to get your hands dirty to reproduce the above results for the ResNET152V2. Explain why you think these results come out and compare the results with those obtained with ResNET50V2." }, { "code": null, "e": 17341, "s": 17024, "text": "In this post, we have presented how to distribute the training of a single Deep Neural Network over many servers using Horovod. We only proposed a toy experiment due to the limitations of the resources available. However, from my point of view, It serves the purpose of bringing the reader closer to the Horovod API." }, { "code": null, "e": 17602, "s": 17341, "text": "This is the last post of this series that I wrote to support my classes in my master course SA-MIRI at UPC Barcelona Tech (with the support of Barcelona Supercomputing Center). I share it at Towards Data Science just in case it can be useful for other readers." }, { "code": null, "e": 17856, "s": 17602, "text": "Artificial Intelligence is a Supercomputing problemUsing Supercomputers for Deep Learning TrainingScalable Deep Learning on Parallel and Distributed InfrastructuresTrain a Neural Network on multi-GPU with TensorFlowDistributed Deep Learning with Horovod" }, { "code": null, "e": 17908, "s": 17856, "text": "Artificial Intelligence is a Supercomputing problem" }, { "code": null, "e": 17956, "s": 17908, "text": "Using Supercomputers for Deep Learning Training" }, { "code": null, "e": 18023, "s": 17956, "text": "Scalable Deep Learning on Parallel and Distributed Infrastructures" }, { "code": null, "e": 18075, "s": 18023, "text": "Train a Neural Network on multi-GPU with TensorFlow" }, { "code": null, "e": 18114, "s": 18075, "text": "Distributed Deep Learning with Horovod" } ]
Modulo / Remainder in Arduino
The modulo operator in Arduino is exactly the same as in C language, or most other languages for that matter. The operator is %. The syntax is: a % b and it returns the remainder when a is divided by b. The following example illustrates the use of this operator − void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.println(); Serial.println(10%3); Serial.println(4%2); Serial.println(50%9); } void loop() { // put your main code here, to run repeatedly: } The Serial Monitor output is shown below. You can work out the remainders yourself and verify that the output is correct.
[ { "code": null, "e": 1265, "s": 1062, "text": "The modulo operator in Arduino is exactly the same as in C language, or most other languages for that matter. The operator is %. The syntax is: a % b and it returns the remainder when a is divided by b." }, { "code": null, "e": 1326, "s": 1265, "text": "The following example illustrates the use of this operator −" }, { "code": null, "e": 1573, "s": 1326, "text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println();\n\n Serial.println(10%3);\n Serial.println(4%2);\n Serial.println(50%9);\n}\nvoid loop() {\n // put your main code here, to run repeatedly:\n}" }, { "code": null, "e": 1695, "s": 1573, "text": "The Serial Monitor output is shown below. You can work out the remainders yourself and verify that the output is correct." } ]
Write an JDBC example for inserting value for Blob datatype into a table?
Assume we already have a table named MyTable in the database with the following description. +-------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+--------------+------+-----+---------+-------+ | Name | varchar(255) | YES | | NULL | | | image | blob | YES | | NULL | | +-------+--------------+------+-----+---------+-------+ If you need to insert a value int to the blob data type using a JDBC program you need to use the methods which sets binary stream data. PreparedStatement interface provides the following methods to insert image into a table. The void setBinaryStream(int parameterIndex, InputStream x) method sets the data in the given input stream (till the end of the file) as a value to the parameter at the given index. void setBinaryStream(int parameterIndex, InputStream x, int length) void setBinaryStream(int parameterIndex, InputStream x, int length) void setBinaryStream(int parameterIndex, InputStream x, long length) void setBinaryStream(int parameterIndex, InputStream x, long length) The void setBlob(int parameterIndex, Blob x) method sets the given blob object as a value to the parameter at the given index. void setBlob(int parameterIndex, InputStream inputStream) void setBlob(int parameterIndex, InputStream inputStream) void setBlob(int parameterIndex, InputStream inputStream, long length) void setBlob(int parameterIndex, InputStream inputStream, long length) You can set value to the Blob data type using either of these methods. Following example sets value to a Blob datatype using the setBinaryStream() method. import java.io.FileInputStream; import java.io.FileNotFoundException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class IndertingValueForBlob { public static void main(String args[]) throws Exception{ //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/sampleDB"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Inserting values String query = "INSERT INTO MyTable(Name,image) VALUES (?, ?)"; PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, "sample_image"); FileInputStream fin = new FileInputStream("E:\\images\\cat.jpg"); pstmt.setBinaryStream(2, fin); pstmt.execute(); System.out.println("Record inserted ....."); } } Connection established...... Record inserted ...... If you try to view the blob value in the record using the MySQL work bench you can see the image inserted as shown below:
[ { "code": null, "e": 1155, "s": 1062, "text": "Assume we already have a table named MyTable in the database with the following description." }, { "code": null, "e": 1491, "s": 1155, "text": "+-------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+--------------+------+-----+---------+-------+\n| Name | varchar(255) | YES | | NULL | |\n| image | blob | YES | | NULL | |\n+-------+--------------+------+-----+---------+-------+" }, { "code": null, "e": 1716, "s": 1491, "text": "If you need to insert a value int to the blob data type using a JDBC program you need to use the methods which sets binary stream data. PreparedStatement interface provides the following methods to insert image into a table." }, { "code": null, "e": 1898, "s": 1716, "text": "The void setBinaryStream(int parameterIndex, InputStream x) method sets the data in the given input stream (till the end of the file) as a value to the parameter at the given index." }, { "code": null, "e": 1966, "s": 1898, "text": "void setBinaryStream(int parameterIndex, InputStream x, int length)" }, { "code": null, "e": 2034, "s": 1966, "text": "void setBinaryStream(int parameterIndex, InputStream x, int length)" }, { "code": null, "e": 2103, "s": 2034, "text": "void setBinaryStream(int parameterIndex, InputStream x, long length)" }, { "code": null, "e": 2172, "s": 2103, "text": "void setBinaryStream(int parameterIndex, InputStream x, long length)" }, { "code": null, "e": 2299, "s": 2172, "text": "The void setBlob(int parameterIndex, Blob x) method sets the given blob object as a value to the parameter at the given index." }, { "code": null, "e": 2357, "s": 2299, "text": "void setBlob(int parameterIndex, InputStream inputStream)" }, { "code": null, "e": 2415, "s": 2357, "text": "void setBlob(int parameterIndex, InputStream inputStream)" }, { "code": null, "e": 2486, "s": 2415, "text": "void setBlob(int parameterIndex, InputStream inputStream, long length)" }, { "code": null, "e": 2557, "s": 2486, "text": "void setBlob(int parameterIndex, InputStream inputStream, long length)" }, { "code": null, "e": 2628, "s": 2557, "text": "You can set value to the Blob data type using either of these methods." }, { "code": null, "e": 2712, "s": 2628, "text": "Following example sets value to a Blob datatype using the setBinaryStream() method." }, { "code": null, "e": 3718, "s": 2712, "text": "import java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.SQLException;\npublic class IndertingValueForBlob {\n public static void main(String args[]) throws Exception{\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/sampleDB\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n\n //Inserting values\n String query = \"INSERT INTO MyTable(Name,image) VALUES (?, ?)\";\n PreparedStatement pstmt = con.prepareStatement(query);\n pstmt.setString(1, \"sample_image\");\n FileInputStream fin = new FileInputStream(\"E:\\\\images\\\\cat.jpg\");\n pstmt.setBinaryStream(2, fin);\n pstmt.execute();\n System.out.println(\"Record inserted .....\");\n }\n}" }, { "code": null, "e": 3770, "s": 3718, "text": "Connection established......\nRecord inserted ......" }, { "code": null, "e": 3892, "s": 3770, "text": "If you try to view the blob value in the record using the MySQL work bench you can see the image inserted as shown below:" } ]
Modify axis, legend, and plot labels using ggplot2 in R - GeeksforGeeks
05 Jul, 2021 In this article, we are going to see how to modify the axis labels, legend, and plot labels using ggplot2 bar plot in R programming language. For creating a simple bar plot we will use the function geom_bar( ). Syntax: geom_bar(stat, fill, color, width) Parameters : stat : Set the stat parameter to identify the mode.fill : Represents color inside the bars.color : Represents color of outlines of the bars.width : Represents width of the bars. Dataset in use: Let us first visualize the graph as it is so that the changes are apparent. Example: R # Inserting dataODI <- data.frame(match=c("M-1","M-2","M-3","M-4"), runs=c(67,37,74,10))head(ODI) library(ggplot2) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat="identity") perf Output: By default, R will use the variables provided in the Data Frame as the labels of the axis. We can modify them and change their appearance easily. The functions which are used to change axis labels are : xlab( ) : For the horizontal axis. ylab( ) : For the vertical axis. labs( ) : For both the axes simultaneously. element_text( ) : The arguments of this function are : Syntax: element_text( family, face, color, size, hjust, vjust, angle, margin) element_blank( ): To make the labels NULL and remove them from the plot. The argument hjust (Horizontal Adjust) or vjust (Vertical Adjust) is used to move the axis labels. They take numbers in range [0,1] where : hjust = 0 // Depicts left most corner of the axis hjust = 0.5 // Depicts middle of the axis hjust = 1 // Depicts right most corner of the axis The keywords used are : title : To add plot label. subtitle : To add subtitle in the plot. caption : To add caption in the plot. axis.title.x : For horizontal axis. axis.title.y : For vertical axis. Example: R library(ggplot2) # Inserting dataODI <- data.frame(match=c("M-1","M-2","M-3","M-4"), runs=c(67,37,74,10)) # Default axis labels in ggplot2# bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat="identity")perf # Manually adding axis labels and# Plot Labelggp<-perf+labs(x="Matches",y="Runs Scored", title="Runs scored by Virat Kohli in ODI matches")ggp Output: A subtitle can also be included with the main title using labs() function and passing subtitle argument with the required subtitle. Example: R library(ggplot2) # Inserting dataODI <- data.frame(match=c("M-1","M-2","M-3","M-4"), runs=c(67,37,74,10)) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat="identity")perf # Manually adding axis labels and Plot Labelggp<-perf+labs(x="Matches",y="Runs Scored", title="Runs scored by Virat Kohli in ODI matches")ggp # Subtitle and Captionggp+labs(subtitle="Performance",caption="GeeksforGeeks Trophy") Output: To move axis labels hjust argument is set according to the requirement. Example: R library(ggplot2) # Inserting dataODI <- data.frame(match=c("M-1","M-2","M-3","M-4"), runs=c(67,37,74,10)) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat="identity")perf # Manually adding axis labels and Plot Labelggp<-perf+labs(x="Matches",y="Runs Scored", title="Runs scored by Virat Kohli in ODI matches")ggp # Moving axis label to leftggp + theme( axis.title.x = element_text(hjust=0), axis.title.y = element_text(hjust=0) ) # Moving axis label in middleggp + theme( axis.title.x = element_text(hjust=0.5), axis.title.y = element_text(hjust=0.5)) # Moving axis label to rightggp + theme( axis.title.x = element_text(hjust=1), axis.title.y = element_text(hjust=1)) Output: Axis labels and main titles can be changed to reflect the desired appearance. For this element_text() function is passed with the required attributes. Example: R library(ggplot2) # Inserting dataODI <- data.frame(match=c("M-1","M-2","M-3","M-4"), runs=c(67,37,74,10)) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat="identity")perf # Manually adding axis labels and Plot Labelggp<-perf+labs(x="Matches",y="Runs Scored", title="Runs scored by Virat Kohli in ODI matches") # Plot title, axis labels formatggp + theme(plot.title = element_text( colour="#006000", size=14,face="bold"), axis.title.x = element_text( colour="Purple",size=10,face="bold.italic"), axis.title.y = element_text( colour="DarkBlue",size=10,face="bold.italic") ) Output: For this theme() function is called with reference to which part of the plot has to be modified. To these references, pass element_blank() without any argument. Example: R library(ggplot2) # Inserting dataODI <- data.frame(match=c("M-1","M-2","M-3","M-4"), runs=c(67,37,74,10)) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat="identity")perf # Manually adding axis labels and Plot Labelggp<-perf+labs(x="Matches",y="Runs Scored", title="Runs scored by Virat Kohli in ODI matches") # Remove chart title and axis labelggp + theme(plot.title = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank() ) Output: To change the position of the legend theme() function is called with legend.position as argument and to this argument, a required position is passed. Syntax: theme( legend.position = “Pos”) Parameter: Pos : Left, Right, Top, Bottom. Example: R library(ggplot2) # Inserting dataODI <- data.frame(match=c("M-1","M-2","M-3","M-4"), runs=c(67,37,74,10)) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat="identity")perf # Manually adding axis labels and Plot Labelggp<-perf+labs(x="Matches",y="Runs Scored", title="Runs scored by Virat Kohli in ODI matches") # Move legend to top position of the plotggp + theme(legend.position="top") Output: Example: R library(ggplot2) # Inserting dataODI <- data.frame(match=c("M-1","M-2","M-3","M-4"), runs=c(67,37,74,10)) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat="identity")perf # Manually adding axis labels and Plot Labelggp<-perf+labs(x="Matches",y="Runs Scored", title="Runs scored by Virat Kohli in ODI matches") # Move legend to bottom position of the plotggp + theme(legend.position="bottom") Output: sweetyty Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? Group by function in R using Dplyr K-Means Clustering in R Programming Remove rows with NA in one column of R DataFrame How to Split Column Into Multiple Columns in R DataFrame?
[ { "code": null, "e": 24778, "s": 24750, "text": "\n05 Jul, 2021" }, { "code": null, "e": 24920, "s": 24778, "text": "In this article, we are going to see how to modify the axis labels, legend, and plot labels using ggplot2 bar plot in R programming language." }, { "code": null, "e": 24989, "s": 24920, "text": "For creating a simple bar plot we will use the function geom_bar( )." }, { "code": null, "e": 25032, "s": 24989, "text": "Syntax: geom_bar(stat, fill, color, width)" }, { "code": null, "e": 25224, "s": 25032, "text": "Parameters : stat : Set the stat parameter to identify the mode.fill : Represents color inside the bars.color : Represents color of outlines of the bars.width : Represents width of the bars." }, { "code": null, "e": 25240, "s": 25224, "text": "Dataset in use:" }, { "code": null, "e": 25316, "s": 25240, "text": "Let us first visualize the graph as it is so that the changes are apparent." }, { "code": null, "e": 25325, "s": 25316, "text": "Example:" }, { "code": null, "e": 25327, "s": 25325, "text": "R" }, { "code": "# Inserting dataODI <- data.frame(match=c(\"M-1\",\"M-2\",\"M-3\",\"M-4\"), runs=c(67,37,74,10))head(ODI) library(ggplot2) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat=\"identity\") perf", "e": 25591, "s": 25327, "text": null }, { "code": null, "e": 25599, "s": 25591, "text": "Output:" }, { "code": null, "e": 25802, "s": 25599, "text": "By default, R will use the variables provided in the Data Frame as the labels of the axis. We can modify them and change their appearance easily. The functions which are used to change axis labels are :" }, { "code": null, "e": 25837, "s": 25802, "text": "xlab( ) : For the horizontal axis." }, { "code": null, "e": 25870, "s": 25837, "text": "ylab( ) : For the vertical axis." }, { "code": null, "e": 25914, "s": 25870, "text": "labs( ) : For both the axes simultaneously." }, { "code": null, "e": 25969, "s": 25914, "text": "element_text( ) : The arguments of this function are :" }, { "code": null, "e": 25977, "s": 25969, "text": "Syntax:" }, { "code": null, "e": 26047, "s": 25977, "text": "element_text( family, face, color, size, hjust, vjust, angle, margin)" }, { "code": null, "e": 26120, "s": 26047, "text": "element_blank( ): To make the labels NULL and remove them from the plot." }, { "code": null, "e": 26260, "s": 26120, "text": "The argument hjust (Horizontal Adjust) or vjust (Vertical Adjust) is used to move the axis labels. They take numbers in range [0,1] where :" }, { "code": null, "e": 26310, "s": 26260, "text": "hjust = 0 // Depicts left most corner of the axis" }, { "code": null, "e": 26352, "s": 26310, "text": "hjust = 0.5 // Depicts middle of the axis" }, { "code": null, "e": 26403, "s": 26352, "text": "hjust = 1 // Depicts right most corner of the axis" }, { "code": null, "e": 26427, "s": 26403, "text": "The keywords used are :" }, { "code": null, "e": 26454, "s": 26427, "text": "title : To add plot label." }, { "code": null, "e": 26494, "s": 26454, "text": "subtitle : To add subtitle in the plot." }, { "code": null, "e": 26533, "s": 26494, "text": "caption : To add caption in the plot." }, { "code": null, "e": 26569, "s": 26533, "text": "axis.title.x : For horizontal axis." }, { "code": null, "e": 26603, "s": 26569, "text": "axis.title.y : For vertical axis." }, { "code": null, "e": 26612, "s": 26603, "text": "Example:" }, { "code": null, "e": 26614, "s": 26612, "text": "R" }, { "code": "library(ggplot2) # Inserting dataODI <- data.frame(match=c(\"M-1\",\"M-2\",\"M-3\",\"M-4\"), runs=c(67,37,74,10)) # Default axis labels in ggplot2# bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat=\"identity\")perf # Manually adding axis labels and# Plot Labelggp<-perf+labs(x=\"Matches\",y=\"Runs Scored\", title=\"Runs scored by Virat Kohli in ODI matches\")ggp", "e": 27026, "s": 26614, "text": null }, { "code": null, "e": 27038, "s": 27030, "text": "Output:" }, { "code": null, "e": 27174, "s": 27042, "text": "A subtitle can also be included with the main title using labs() function and passing subtitle argument with the required subtitle." }, { "code": null, "e": 27185, "s": 27176, "text": "Example:" }, { "code": null, "e": 27189, "s": 27187, "text": "R" }, { "code": "library(ggplot2) # Inserting dataODI <- data.frame(match=c(\"M-1\",\"M-2\",\"M-3\",\"M-4\"), runs=c(67,37,74,10)) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat=\"identity\")perf # Manually adding axis labels and Plot Labelggp<-perf+labs(x=\"Matches\",y=\"Runs Scored\", title=\"Runs scored by Virat Kohli in ODI matches\")ggp # Subtitle and Captionggp+labs(subtitle=\"Performance\",caption=\"GeeksforGeeks Trophy\")", "e": 27685, "s": 27189, "text": null }, { "code": null, "e": 27697, "s": 27689, "text": "Output:" }, { "code": null, "e": 27774, "s": 27701, "text": " To move axis labels hjust argument is set according to the requirement." }, { "code": null, "e": 27785, "s": 27776, "text": "Example:" }, { "code": null, "e": 27789, "s": 27787, "text": "R" }, { "code": "library(ggplot2) # Inserting dataODI <- data.frame(match=c(\"M-1\",\"M-2\",\"M-3\",\"M-4\"), runs=c(67,37,74,10)) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat=\"identity\")perf # Manually adding axis labels and Plot Labelggp<-perf+labs(x=\"Matches\",y=\"Runs Scored\", title=\"Runs scored by Virat Kohli in ODI matches\")ggp # Moving axis label to leftggp + theme( axis.title.x = element_text(hjust=0), axis.title.y = element_text(hjust=0) ) # Moving axis label in middleggp + theme( axis.title.x = element_text(hjust=0.5), axis.title.y = element_text(hjust=0.5)) # Moving axis label to rightggp + theme( axis.title.x = element_text(hjust=1), axis.title.y = element_text(hjust=1))", "e": 28562, "s": 27789, "text": null }, { "code": null, "e": 28574, "s": 28566, "text": "Output:" }, { "code": null, "e": 28729, "s": 28578, "text": "Axis labels and main titles can be changed to reflect the desired appearance. For this element_text() function is passed with the required attributes." }, { "code": null, "e": 28740, "s": 28731, "text": "Example:" }, { "code": null, "e": 28744, "s": 28742, "text": "R" }, { "code": "library(ggplot2) # Inserting dataODI <- data.frame(match=c(\"M-1\",\"M-2\",\"M-3\",\"M-4\"), runs=c(67,37,74,10)) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat=\"identity\")perf # Manually adding axis labels and Plot Labelggp<-perf+labs(x=\"Matches\",y=\"Runs Scored\", title=\"Runs scored by Virat Kohli in ODI matches\") # Plot title, axis labels formatggp + theme(plot.title = element_text( colour=\"#006000\", size=14,face=\"bold\"), axis.title.x = element_text( colour=\"Purple\",size=10,face=\"bold.italic\"), axis.title.y = element_text( colour=\"DarkBlue\",size=10,face=\"bold.italic\") )", "e": 29498, "s": 28744, "text": null }, { "code": null, "e": 29510, "s": 29502, "text": "Output:" }, { "code": null, "e": 29675, "s": 29514, "text": "For this theme() function is called with reference to which part of the plot has to be modified. To these references, pass element_blank() without any argument." }, { "code": null, "e": 29686, "s": 29677, "text": "Example:" }, { "code": null, "e": 29690, "s": 29688, "text": "R" }, { "code": "library(ggplot2) # Inserting dataODI <- data.frame(match=c(\"M-1\",\"M-2\",\"M-3\",\"M-4\"), runs=c(67,37,74,10)) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat=\"identity\")perf # Manually adding axis labels and Plot Labelggp<-perf+labs(x=\"Matches\",y=\"Runs Scored\", title=\"Runs scored by Virat Kohli in ODI matches\") # Remove chart title and axis labelggp + theme(plot.title = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank() )", "e": 30272, "s": 29690, "text": null }, { "code": null, "e": 30280, "s": 30272, "text": "Output:" }, { "code": null, "e": 30430, "s": 30280, "text": "To change the position of the legend theme() function is called with legend.position as argument and to this argument, a required position is passed." }, { "code": null, "e": 30438, "s": 30430, "text": "Syntax:" }, { "code": null, "e": 30470, "s": 30438, "text": "theme( legend.position = “Pos”)" }, { "code": null, "e": 30481, "s": 30470, "text": "Parameter:" }, { "code": null, "e": 30514, "s": 30481, "text": "Pos : Left, Right, Top, Bottom. " }, { "code": null, "e": 30523, "s": 30514, "text": "Example:" }, { "code": null, "e": 30525, "s": 30523, "text": "R" }, { "code": "library(ggplot2) # Inserting dataODI <- data.frame(match=c(\"M-1\",\"M-2\",\"M-3\",\"M-4\"), runs=c(67,37,74,10)) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat=\"identity\")perf # Manually adding axis labels and Plot Labelggp<-perf+labs(x=\"Matches\",y=\"Runs Scored\", title=\"Runs scored by Virat Kohli in ODI matches\") # Move legend to top position of the plotggp + theme(legend.position=\"top\")", "e": 31008, "s": 30525, "text": null }, { "code": null, "e": 31016, "s": 31008, "text": "Output:" }, { "code": null, "e": 31025, "s": 31016, "text": "Example:" }, { "code": null, "e": 31027, "s": 31025, "text": "R" }, { "code": "library(ggplot2) # Inserting dataODI <- data.frame(match=c(\"M-1\",\"M-2\",\"M-3\",\"M-4\"), runs=c(67,37,74,10)) # Default axis labels in ggplot2 bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat=\"identity\")perf # Manually adding axis labels and Plot Labelggp<-perf+labs(x=\"Matches\",y=\"Runs Scored\", title=\"Runs scored by Virat Kohli in ODI matches\") # Move legend to bottom position of the plotggp + theme(legend.position=\"bottom\")", "e": 31516, "s": 31027, "text": null }, { "code": null, "e": 31524, "s": 31516, "text": "Output:" }, { "code": null, "e": 31533, "s": 31524, "text": "sweetyty" }, { "code": null, "e": 31540, "s": 31533, "text": "Picked" }, { "code": null, "e": 31549, "s": 31540, "text": "R-ggplot" }, { "code": null, "e": 31560, "s": 31549, "text": "R Language" }, { "code": null, "e": 31658, "s": 31560, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31716, "s": 31658, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 31768, "s": 31716, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 31800, "s": 31768, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 31852, "s": 31800, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 31896, "s": 31852, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 31934, "s": 31896, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 31969, "s": 31934, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 32005, "s": 31969, "text": "K-Means Clustering in R Programming" }, { "code": null, "e": 32054, "s": 32005, "text": "Remove rows with NA in one column of R DataFrame" } ]
CakePHP - Logging
Logging in CakePHP is a very easy task. You just have to use one function. You can log errors, exceptions, user activities, action taken by users, for any background process like cronjob. Logging data in CakePHP is easy. The log() function is provided by the LogTrait, which is the common ancestor for almost all CakePHP classes. We can configure the log in file config/app.php. There is a log section in the file, where you can configure logging options as shown in the following screenshot. By default, you will see two log levels − error and debug already configured for you. Each will handle different level of messages. CakePHP supports various logging levels as shown below − Emergency − System is unusable Emergency − System is unusable Alert − Action must be taken immediately Alert − Action must be taken immediately Critical − Critical conditions Critical − Critical conditions Error − Error conditions Error − Error conditions Warning − Warning conditions Warning − Warning conditions Notice − Normal but significant condition Notice − Normal but significant condition Info − Informational messages Info − Informational messages Debug − Debug-level messages Debug − Debug-level messages There are two ways by which, we can write in a Log file. The first is to use the static write() method. The following is the syntax of the static write() method. The severity level of the message being written. The value must be an integer or string matching a known level. Message content to log. Additional data to be used for logging the message. The special scope key can be passed to be used for further filtering of the log engines to be used. If a string or a numerically index array is passed, it will be treated as the scope key. See Cake\Log\Log::config() for more information on logging scopes. boolean Writes the given message and type to all of the configured log adapters. Configured adapters are passed both the $level and $message variables. $level is one of the following strings/values. The second is to use the log() shortcut function available on any using the LogTrait Calling log() will internally call Log::write() − Make changes in the config/routes.php file as shown in the following program. config/routes.php <?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); //$builder->connect('/pages', ['controller'=>'Pages','action'=>'display', 'home']); $builder->connect('logex',['controller'=>'Logexs','action'=>'index']); $builder->fallbacks(); }); Create a LogexsController.php file at src/Controller/LogexsController.php. Copy the following code in the controller file. src/Controller/LogexsController.php <?php namespace App\Controller; use App\Controller\AppController; use Cake\Log\Log; class LogexsController extends AppController{ public function index(){ /*The first way to write to log file.*/ Log::write('debug',"Something didn't work."); /*The second way to write to log file.*/ $this->log("Something didn't work.",'debug'); } } ?> Create a directory Logexs at src/Template and under that directory create a View file called index.php. Copy the following code in that file. src/Template/Logexs/index.php Something is written in log file. Check log file logs\debug.log Execute the above example by visiting the following URL. http://localhost/cakephp4/logex Upon execution, you will receive the following output. The logs will be added to log/debug.log file − Print Add Notes Bookmark this page
[ { "code": null, "e": 2572, "s": 2242, "text": "Logging in CakePHP is a very easy task. You just have to use one function. You can log errors, exceptions, user activities, action taken by users, for any background process like cronjob. Logging data in CakePHP is easy. The log() function is provided by the LogTrait, which is the common ancestor for almost all CakePHP classes." }, { "code": null, "e": 2735, "s": 2572, "text": "We can configure the log in file config/app.php. There is a log section in the file, where you can configure logging options as shown in the following screenshot." }, { "code": null, "e": 2867, "s": 2735, "text": "By default, you will see two log levels − error and debug already configured for you. Each will handle different level of messages." }, { "code": null, "e": 2924, "s": 2867, "text": "CakePHP supports various logging levels as shown below −" }, { "code": null, "e": 2955, "s": 2924, "text": "Emergency − System is unusable" }, { "code": null, "e": 2986, "s": 2955, "text": "Emergency − System is unusable" }, { "code": null, "e": 3027, "s": 2986, "text": "Alert − Action must be taken immediately" }, { "code": null, "e": 3068, "s": 3027, "text": "Alert − Action must be taken immediately" }, { "code": null, "e": 3099, "s": 3068, "text": "Critical − Critical conditions" }, { "code": null, "e": 3130, "s": 3099, "text": "Critical − Critical conditions" }, { "code": null, "e": 3156, "s": 3130, "text": "Error − Error conditions" }, { "code": null, "e": 3182, "s": 3156, "text": "Error − Error conditions" }, { "code": null, "e": 3211, "s": 3182, "text": "Warning − Warning conditions" }, { "code": null, "e": 3240, "s": 3211, "text": "Warning − Warning conditions" }, { "code": null, "e": 3282, "s": 3240, "text": "Notice − Normal but significant condition" }, { "code": null, "e": 3324, "s": 3282, "text": "Notice − Normal but significant condition" }, { "code": null, "e": 3354, "s": 3324, "text": "Info − Informational messages" }, { "code": null, "e": 3384, "s": 3354, "text": "Info − Informational messages" }, { "code": null, "e": 3413, "s": 3384, "text": "Debug − Debug-level messages" }, { "code": null, "e": 3442, "s": 3413, "text": "Debug − Debug-level messages" }, { "code": null, "e": 3499, "s": 3442, "text": "There are two ways by which, we can write in a Log file." }, { "code": null, "e": 3604, "s": 3499, "text": "The first is to use the static write() method. The following is the syntax of the static write() method." }, { "code": null, "e": 3716, "s": 3604, "text": "The severity level of the message being written. The value must be an integer or string matching a known level." }, { "code": null, "e": 3740, "s": 3716, "text": "Message content to log." }, { "code": null, "e": 4048, "s": 3740, "text": "Additional data to be used for logging the message. The special scope key can be passed to be used for further filtering of the log engines to be used. If a string or a numerically index array is passed, it will be treated as the scope key. See Cake\\Log\\Log::config() for more information on logging scopes." }, { "code": null, "e": 4056, "s": 4048, "text": "boolean" }, { "code": null, "e": 4247, "s": 4056, "text": "Writes the given message and type to all of the configured log adapters. Configured adapters are passed both the $level and $message variables. $level is one of the following strings/values." }, { "code": null, "e": 4382, "s": 4247, "text": "The second is to use the log() shortcut function available on any using the LogTrait Calling log() will internally call Log::write() −" }, { "code": null, "e": 4460, "s": 4382, "text": "Make changes in the config/routes.php file as shown in the following program." }, { "code": null, "e": 4478, "s": 4460, "text": "config/routes.php" }, { "code": null, "e": 5041, "s": 4478, "text": "<?php\nuse Cake\\Http\\Middleware\\CsrfProtectionMiddleware;\nuse Cake\\Routing\\Route\\DashedRoute;\nuse Cake\\Routing\\RouteBuilder;\n$routes->setRouteClass(DashedRoute::class);\n$routes->scope('/', function (RouteBuilder $builder) {\n $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([\n 'httpOnly' => true,\n ]));\n $builder->applyMiddleware('csrf');\n //$builder->connect('/pages',\n ['controller'=>'Pages','action'=>'display', 'home']);\n $builder->connect('logex',['controller'=>'Logexs','action'=>'index']);\n $builder->fallbacks();\n});" }, { "code": null, "e": 5164, "s": 5041, "text": "Create a LogexsController.php file at src/Controller/LogexsController.php. Copy the following code in the controller file." }, { "code": null, "e": 5200, "s": 5164, "text": "src/Controller/LogexsController.php" }, { "code": null, "e": 5598, "s": 5200, "text": "<?php\n namespace App\\Controller;\n use App\\Controller\\AppController;\n use Cake\\Log\\Log;\n class LogexsController extends AppController{\n public function index(){\n /*The first way to write to log file.*/\n Log::write('debug',\"Something didn't work.\");\n /*The second way to write to log file.*/\n $this->log(\"Something didn't work.\",'debug');\n }\n }\n?>" }, { "code": null, "e": 5740, "s": 5598, "text": "Create a directory Logexs at src/Template and under that directory create a View file called index.php. Copy the following code in that file." }, { "code": null, "e": 5770, "s": 5740, "text": "src/Template/Logexs/index.php" }, { "code": null, "e": 5835, "s": 5770, "text": "Something is written in log file. Check log file logs\\debug.log\n" }, { "code": null, "e": 5892, "s": 5835, "text": "Execute the above example by visiting the following URL." }, { "code": null, "e": 5924, "s": 5892, "text": "http://localhost/cakephp4/logex" }, { "code": null, "e": 5979, "s": 5924, "text": "Upon execution, you will receive the following output." }, { "code": null, "e": 6026, "s": 5979, "text": "The logs will be added to log/debug.log file −" }, { "code": null, "e": 6033, "s": 6026, "text": " Print" }, { "code": null, "e": 6044, "s": 6033, "text": " Add Notes" } ]